摘自:《精通struts.基于MVC的.Java.Web设计与开发》---电子出版社--2004年8月第1版
应用首页:
输入test,单击提交后显示:
保持输入框为空再次提交:
最后输入Monster,显示页面如下:
<?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>
<%@ 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>
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>标签显示。
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. */ } }
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");
package hello; public final class Constants { /** * The application scope attribute under which our user database * is stored */ public static final String PERSON_KEY = "presonbean"; }
<?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>
# 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
整个程序的结构图,如下: