Struts-第一个Struts应用

摘自:《精通struts.基于MVC的.Java.Web设计与开发》---电子出版社--2004年8月第1版

应用首页:

Struts-第一个Struts应用_第1张图片

输入test,单击提交后显示:

Struts-第一个Struts应用_第2张图片

保持输入框为空再次提交:

Struts-第一个Struts应用_第3张图片

最后输入Monster,显示页面如下:

Struts-第一个Struts应用_第4张图片

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

整个程序的结构图,如下:

Struts-第一个Struts应用_第5张图片

你可能感兴趣的:(Struts-第一个Struts应用)