選用純 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"));
}
}
到浏覽器裡面欣賞一下吧,不過還不到開香槟的時候,也許你應該為這個應用考慮一些安全措施,下一次我再講咯。