摘自:《精通struts.基于MVC的.Java.Web設計與開發》---電子出版社--2004年8月第1版
應用首頁:
輸入test,單擊送出後顯示:
保持輸入框為空再次送出:
最後輸入Monster,顯示頁面如下:
1.配置web.xml,加入Struts架構:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>HelloApp Struts Application</display-name>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
<!-- Standard 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>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
2.編寫視圖頁面hello.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html xhtml="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><bean:message key="hello.jsp.title" /></title>
</head>
<body bgcolor="white">
<h2><bean:message key="hello.jsp.page.heading" /></h2>
<html:errors />
<logic:present name="presonbean" scope="request">
<h2>
<bean:message key="hello.jsp.page.hello" />
<bean:write name="presonbean" property="userName" />!
</h2>
</logic:present>
<html:form action="/HelloWorld.do" focus="userName">
<bean:message key="hello.jsp.prompt.person" />
<html:text property="userName" size="16" maxlength="16" /><br/>
<html:submit property="submit" value="送出" />
<html:reset />
</html:form><br />
<html:img page="/struts-power.gif" alt="Powered by Struts" />
</body>
</html:html>
- <bean:message>:用于輸出本地化的文本内容,它的Key屬性指定properties資源檔案的消息key。
- <bean:write>:用于輸出JavaBean的屬性值。本例中,它用于輸出personbean對象的userName屬性。
- <html:form>:用于建立HTML表單,它能夠把HTML表單的字段和ActionFrom Bean的屬性關聯起來。
- <html:text>:該标簽是<html:form>的子标簽,用于建立HTML表單的文本框。它和ActionFrom Bean的屬性相關聯。
- <html:errors>:用于顯示Struts 架構中其他元件産生的錯誤消息。它通過把request範圍内的ActionErrors對象包含的錯誤消息顯示出來。
- <logic:presont>:用于判斷JavaBean在特定的範圍内是否存在,隻有當JavaBean存在時,才會執行标簽主體中的内容。
3.編寫HelloForm.java
package hello;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class HelloForm extends ActionForm {
/**
* Version ID
*/
private static final long serialVersionUID = 1L;
private String userName="null";
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Reset all properties to their default values.
*/
public void reset(ActionMapping Mapping, HttpServletRequest request) {
this.userName = null;
}
/**
* Validate the properties posted in this request. If validation errors are
* found, return an <code>ActionErrors</code> object containing the errors.
* If no validation errors occur, return <code>null</code> or an empty
* <code>ActionErrors</code> object.
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if((userName==null)|(userName.length()<1))
errors.add("username", new ActionMessage("hello.no.username.error"));
return errors;
}
}
當使用者送出HTML表單後,Struts架構将自動把表單資料組裝到ActionForm Bean中,接下來Struts架構會自動調用ActionForm Bean的Validate()方法進行表單驗證。如果validate()方法傳回的ActionErrors對象為null,或者不包含任何ActionMessage對象,就表示沒有錯誤,資料驗證通過。如果ActionErrors中包含ActionMessage對象,就表示發生了驗證錯誤,Struts架構會把ActionErrors對象 儲存到request範圍内,然後把請求轉發到恰當的視圖,視圖元件通過<html:errors>标簽顯示。
4.編寫PresonBean.java:
package hello;
public class PersonBean {
private String userName = null;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* This is a stub method that would be used for the Model to save
* the information submitted to persistent store. In this sample
* application it is not
*/
public void saveToPersistentStore() {
/**
* This is a stub method that might be used to save the person's
* name to persistent store(i.e. database)if this were a real application.
*
* The actual business operations that would exist within a Model
* component would depend upon the requirements of application.
*/
}
}
5.編寫HelloAction.jsp:
package hello;
import javax.servlet.http.HttpServletRequest;
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.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
public class HelloAction extends Action {
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already bean completed.
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// These "messages" come from the ApplicationResource.properties file
MessageResources messages = getResources(request);
/*
* Validate the request parameters specified by the user
* Note: Basic field validation done in HelloForm.java
* Business logic validation done in HelloAction.java
*/
ActionMessages errors = new ActionMessages();
String userName = (String)((HelloForm)form).getUserName();
String badUserName = "Monster";
if(userName.equalsIgnoreCase(badUserName)) {
errors.add("username", new ActionMessage("hello.dont.talk.to.monster",
badUserName));
saveErrors(request, errors);
return(new ActionForward(mapping.getInput()));
}
/*
* Having received and validated the data submitted
* from the View, we now update the model
*/
PersonBean pb = new PersonBean();
pb.setUserName(userName);
pb.saveToPersistentStore();
/*
* If there was choice of View components that depended on the model
* (or some other)status, we'd make the decision here as to which
* to display. In this case,there is only one View component.
*
* We pass data to the View components by setting them as attributes
* in the page, request, session or servlet context. In this case, the
* most appropriate scoping is the "request" context since the data
* will not be neaded after the View is generated.
*
* Constants.PERSON_KEY provides a key accessible by both the
* Controller component(i.e. this class) and the View component
* (i.e the jsp file we forward to).
*/
request.setAttribute(Constants.PERSON_KEY, pb);
// Remove the Form Bean - don't need to carry values forward
request.removeAttribute(mapping.getAttribute());
// Forward control to the specified success URI
return (mapping.findForward("SayHello"));
}
}
在Action類中定義了getResources(HtttpServletRequest requets)方法,該方法傳回目前預設的MessageResources對象,它封裝了Resource Bundle中的文本内容,接下來Action類可以通過MessageResources對象通路properties資源檔案的内容,例如,讀取消息Key為"hello.jsp.title"對應的文本内容,可以調用MessageResources類的getMessage(String key)方法:
MessageResources messages = getResources(request);
String title = messages.getMessage("hello.jsp.title");
6.建立存放常量的Constants.java檔案:
package hello;
public final class Constants {
/**
* The application scope attribute under which our user database
* is stored
*/
public static final String PERSON_KEY = "presonbean";
}
7.配置struts-config.xml檔案管理Action:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<!--
This is the Struts configuration file for the "Hello!" sample application
-->
<struts-config>
<!--=============================From Bean Definitions -->
<form-beans>
<form-bean name="HelloForm" type="hello.HelloForm" />
</form-beans>
<!-- ============================Action Mapping Definitions -->
<action-mappings>
<!-- Say Hello! -->
<action path="/HelloWorld" type="hello.HelloAction"
name="HelloForm" scope="request"
validate="true" input="/hello.jsp">
<forward name="SayHello" path="/hello.jsp" />
</action>
</action-mappings>
<!-- ===============Message Resources Definitions=========== -->
<message-resources parameter="hello.application" />
</struts-config>
8.建立資源檔案application.properties:
# Application Resources for the "Hello" sample application
hello.jsp.title=Hello - 第一個Struts程式
hello.jsp.page.heading=Hello World!第一個Struts應用
hello.jsp.prompt.person=請輸入一個昵稱來打個招呼hello:
hello.jsp.page.hello=Hello
# Validation and error messages for HelloForm.java and HelloAction.java
hello.dont.talk.to.monster=不能向Monster說Hello!!!
hello.no.username.error=請輸入一個<i>使用者名</i>!
為了解決中文編碼問題,使用下列指令進行轉碼:
native2ascii -encoding UTF-8 source.properties dest.properties
9.本應用引入的Struts1.3的Jar包如下:
- struts-core-1.3.10.jar
- struts-taglib-1.3.10.jar
- commons-beanutils-1.8.0.jar
- commons-chain-1.2.jar
- commons-digester-1.8.jar
- commons-logging-1.0.4.jar
整個程式的結構圖,如下: