实例学习 Struts

来源:互联网 发布:淘宝异想星球活动 编辑:程序博客网 时间:2024/05/05 13:45

实例学习 Struts

选用纯 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 Homepageprompt.username=Usernameprompt.password=Passwordindex.logon=Log onmain.title=Struts Main pagemain.logoff=Log offerror.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"));    }}

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

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 二岁宝宝流鼻涕怎么办 小婴儿有点鼻塞怎么办 宝宝流鼻涕总不好怎么办 孩子鼻炎睡不好怎么办 鼻炎清鼻涕不止怎么办 宝宝持续低烧流鼻涕怎么办 孩子鼻塞不通气怎么办 2月婴儿感冒怎么办 长期流黄鼻涕怎么办 孩子流清水鼻涕怎么办 小孩有点流鼻子怎么办 初生婴儿堵鼻子怎么办? 小孩反复发烧了怎么办 小孩突然发烧了怎么办 40天宝宝鼻塞怎么办 宝宝伤风鼻子不通怎么办 鼻子伤风不通气怎么办 宝宝伤风流鼻子怎么办 十个月婴儿上火怎么办 一个多月宝宝鼻子有鼻屎怎么办 三个月婴儿感冒发烧怎么办 小孩感冒发烧流鼻涕怎么办 小孩感冒发烧反反复复怎么办 宝宝反复发烧39怎么办 一岁婴儿流鼻涕怎么办 四岁宝宝发烧怎么办 小孩流清鼻涕怎么办? 5宝宝光流清鼻涕怎么办 孩子一直流鼻子怎么办 10岁天天流鼻涕怎么办 喉咙痛又痒咳嗽怎么办 60天宝宝流鼻涕怎么办 宝宝流鼻子严重怎么办 鼻炎鼻涕多鼻塞怎么办 夏天老人感冒流鼻涕怎么办 鼻窦炎流清鼻涕怎么办 鼻子有脓鼻涕怎么办 宝宝有脓鼻涕怎么办 小孩脓鼻涕咳嗽怎么办 哺乳期流黄鼻涕怎么办 宝宝鼻塞流脓涕怎么办