即使世界明天毁灭,我也要在今天种下我的葡萄树。
posts - 112, comments - 14, trackbacks - 0, articles - 11

实例学习 Struts

Posted on 2006-05-25 15:19 阅读(211) 评论(0)  编辑  收藏 所属分类: WEB Design

选用纯 JSP 还是纯 Servlet 设计站点都有它的局限性,Struts 就是把它们联系在一起的一种有力工具。采用 Struts 能开发出基于 MVC 模式的应用,关于 MVC 的概念可以参见 GoF 的《设计模式——可复用面向对象软件的基础》。

你现在要做的是,下载、安装、配置好以下的工具,版本不同的话操作可能会有些差异,具体的看它们的文档吧:

  • Tomcat 4.1.24
  • Apache 2.0.43, w/ mod_jk2 2.0.43
  • Java 2 SDK Standard Edition 1.4.0
  • Struts 1.1
  • Eclipse 2.1.0

Struts 是用 Java 写的,应此它需要 JDK 1.2 或者更高版本。如果你用的是 JDK 1.4,就像我,XML parser 和 JDBC 2.0 Optional Package Binary 就已经被默认的包含了。

新项目

在这个例程中我们要开发一个简单的 web 应用,允许用户登录和注销。简单起见,数据被设定为常数,而不是保存在数据库中,毕竟这里要讲的是 Struts,而不是 Java。

首先在你的 Tomcat 配置的应用主目录中创建一个目录,比方说 logonApp。在 logonApp 中创建目录 src 和 WEB-INF,在 WEB-INF 中创建目录 classes 和 lib,从 Struts 的分发中拷贝 struts.jar 到 lib 目录,而且也把拷贝 $CATALINA_HOME/common/lib/servlets.jar 到 lib 目录。从 Struts 的分发中拷贝所有的 struts*.tld 到 WEB-INF 目录。

现在打开 Eclipse,你会看到四个 view。现在我们要建立一个新的项目,点击 File -> New Project,打开了一个窗口,在第一个窗格中选择 Java,在第二个窗格中选择 Java Project,点击 Next。输入项目名称(为了好记,就也叫 logonApp 吧),去掉 use default 复选框的对勾,浏览到 logonApp 目录,点击 Next。出现一个新的窗口,在 Source tab 上点击 Add Folder,添加 $APP_BASE/src,在 Default output folder 中填入 $APP_BASE/WEB-INF/classes,点击 Finish。点击 Window -> Open Perspective -> Resource,看看 .project 文件是否已经自动包含了 lib 目录中所有的 jar 文件。

你的 logonApp/WEB-INF/web.xml 应该如下所示:

<?xml version="1.0"?>
<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>
  <!-- Action Servlet Configuration -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!-- The Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>
</web-app>

Struts 的配置文件 logonApp/WEB-INF/struts-config.xml 如下:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <form-beans>
    <form-bean name="logonForm" 
      type="org.apache.struts.validator.DynaValidatorForm">
      <form-property name="username" type="java.lang.String"/>
      <form-property name="password" type="java.lang.String"/>
    </form-bean>
  </form-beans>

  <global-forwards>
    <forward   name="success"              path="/main.jsp"/>
    <forward   name="logoff"               path="/logoff.do"/>
  </global-forwards>

  <action-mappings>
    <action    path="/logon"
               type="org.monotonous.struts.LogonAction"
               name="logonForm"
               scope="session"
               input="logon">
    </action>

    <action    path="/logoff"
               type="org.monotonous.struts.LogoffAction">
      <forward name="success"              path="/index.jsp"/>
    </action>
  </action-mappings>

  <controller>
    <!-- The "input" parameter on "action" elements is the name of a
         local or global "forward" rather than a module-relative path -->
    <set-property property="inputForward" value="true"/>
  </controller>

  <message-resources parameter="org.monotonous.struts.ApplicationResources"/>
</struts-config>

创建 View

现在回到 Eclipse,建立一个新页面 index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html:html locale="true">
<head>
  <title><bean:message key="index.title" /></title>
  <html:base/>
</head>

<body>
<html:errors/>
<html:form action="/logon">
  <bean:message key="prompt.username"/>
  <html:text property="username"/>
  <br/>
  <bean:message key="prompt.password"/>
  <html:password property="password"/>
  <br/>
  <html:submit>
    <bean:message key="index.logon"/>
  </html:submit>
</html:form>
</body>
</html:html>

成功登录后的页面 main.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html:html>
<head>
  <title><bean:message key="main.title"/></title>
  <html:base/>
</head>
<body>
<html:link forward="logoff">
<bean:message key="main.logoff"/>
</html:link>
</body>
</html:html>

你可能注意到这两个页面中都使用了方便国际化的特性,这至少需要一个默认的属性文件 ApplicationResources.properties:

index.title=Struts Homepage
prompt.username=Username
prompt.password=Password
index.logon=Log on
main.title=Struts Main page
main.logoff=Log off
error.password.mismatch=Invalid username and/or password.

创建 Controller

LogonAction.java:

package org.monotonous.struts;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.apache.commons.beanutils.PropertyUtils;

public final class LogonAction extends Action {
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {
        Locale locale = getLocale(request);
        MessageResources messages = getResources(request);

        // Validate the request parameters specified by the user
        ActionErrors errors = new ActionErrors();
        String username =
            (String) PropertyUtils.getSimpleProperty(form, "username");
        String password =
            (String) PropertyUtils.getSimpleProperty(form, "password");

        if ((username != "foo") || (password != "bar"))
            errors.add(ActionErrors.GLOBAL_ERROR,
                new ActionError("error.password.mismatch"));

        // Report any errors we have discovered back to the original form
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return (mapping.getInputForward());
        }

        // Save our logged-in user in the session
        HttpSession session = request.getSession();
        // Do something with session...

        // Remove the obsolete form bean
        if (mapping.getAttribute() != null) {
            if ("request".equals(mapping.getScope()))
                request.removeAttribute(mapping.getAttribute());
            else
                session.removeAttribute(mapping.getAttribute());
        }

        // Forward control to the specified success URI
        return (mapping.findForward("success"));
    }
}

LogoffAction.java:

package org.monotonous.struts;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

public final class LogoffAction extends Action {
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

        Locale locale = getLocale(request);
        MessageResources messages = getResources(request);
        HttpSession session = request.getSession();

        session.removeAttribute("userattrib");
        session.invalidate();

        // Forward control to the specified success URI
        return (mapping.findForward("success"));
    }
}

到浏览器里面欣赏一下吧,不过还不到开香槟的时候,也许你应该为这个应用考虑一些安全措施,下一次我再讲咯。


只有注册用户登录后才能发表评论。


网站导航: