今天得到一本书名为《Struts Kick Start》的书,于是开始学习Struts,并学习了第一个范例。
Hello.jsp
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html locale="true">
<head>
<title><bean:message key="hello.jsp.title"/></title>
<html:base/>
</head>
<body bgcolor="white"><p>
<h2><bean:message key="hello.jsp.page.heading"/></h2><p>
<html:errors/><p>
<logic:present name="com.javaby.hello" scope="request">
<h2>
Hello <bean:write name="com.javaby.hello" property="person" />!<p>
</h2>
</logic:present>
<html:form action="/HelloWorld.do?action=gotName" focus="person">
<bean:message key="hello.jsp.prompt.person"/>
<html:text property="person" size="16" maxlength="16"/><br>
<html:submit property="submit" value="Submit"/>
<html:reset/>
</html:form><br>
<html:img page="/struts-power.gif" alt="Powered by Struts"/>
</body>
</html:html> 这是一个简单的输入一个名称,返回hello+<名称>的例子,页面中很多Struts的自定义标记。
<bean:message key="hello.jsp.prompt.person"/>在表单中打印提示信息,key定义在property文件中。
而开始的几行
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
则是定义jsp页面使用的标记库。
Application.properties文件
; Application Resources for the "Hello" Sample application
;
; Application Resources that are specific to the Hello.jsp file
hello.jsp.title = Hello - A first Struts program
hello.jsp.page.heading = Hello World! A first Struts application
hello.jsp.prompt.person = Please enter a name to say hello to :
; Validation and error messages for HelloForm.java and HelloAction.java
com.javaby.hello.dont.talk.to.atilla = I told you not to talk to Atilla!!!
com.javaby.hello.no.person.error = Please enter a <i>PERSON</i> to say hello to! Struts表单中的数据被填装到一个被称为FormBean的java bean中,HelloForm.java
package com.javaby.hello;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
/**//**
* Form bean for Chapter 03 sample application, "Hello World!"
*
* @author Kevin Bedell
*/
public final class HelloForm extends ActionForm {
// --------------------------------------------------- Instance Variables
/**//**
* The person we want to say "Hello!" to
*/
private String person = null;
// ----------------------------------------------------------- Properties
/**//**
* Return the person to say "Hello!" to
*
* @return String person the person to say "Hello!" to
*/
public String getPerson() {
return (this.person);
}
/**//**
* Set the person.
*
* @param person The person to say "Hello!" to
*/
public void setPerson(String person) {
this.person = person;
}
// --------------------------------------------------------- Public Methods
/**//**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.person = 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.
*
* @param mapping The current mapping (from struts-config.xml)
* @param request The servlet request object
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((person == null) || (person.length() < 1))
errors.add("person", new ActionError("com.javaby.hello.no.person.error"));
return errors;
}
}
Action类HelloAction.java
package com.javaby.hello;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
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;
/**//**
* The <strong>Action</strong> class for our "Hello" application.<p>
* This is the "Controller" class in the Struts MVC architecture.
*
* @author Kevin Bedell
*/
public final 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 been completed.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception Exception if business logic throws an exception
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
/**//*
* This Action is executed either by calling
*
* /hello.do - when loading the initial page
* - or -
* /hello.do?action=getName - whenever we post the form
*
*/
// If this is first time, go straight to page
String action = request.getParameter("action");
if (action == null) {
return (mapping.findForward("SayHello"));
}
// These "messages" come from the ApplicationResources.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
*/
ActionErrors errors = new ActionErrors();
String person = (String)
PropertyUtils.getSimpleProperty(form, "person");
String badPerson = "Atilla the Hun";
if (person.equals(badPerson)) {
errors.add("person",
new ActionError("com.javaby.hello.dont.talk.to.atilla", badPerson ));
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
/**//*
* Having received and validated the data submitted from the View,
* we now update the model
*/
HelloModel hm = new HelloModel();
hm.setPerson(person);
hm.saveToPersistentStore();
/**//*
* If there was a choice of View components that depended on the model
* (oe some other) status, we'd make the decisoin 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 nedded after the View is generated.
*
* Constants.HELLO_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.HELLO_KEY, hm);
// 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类的主要方法是execute()。而值得一提的是与Model组件的交互,在HelloModel hm=new HelloModel();一段中Controller建立了一个新的Model组件,为其设定了数值,同时调用一个方法将数据保存到永久性存储中。另外,request.setAttribute(Constants.HELLO_KEY,hm);完成了将Model实例设置为request的一个属性,并传递到View组件中,request.removeAttribute(mapping.getAttribute());则在request中删除表单bean。
HelloModel.java
package com.javaby.hello;
/**//**
* <p>This is a Model object which simply contains the name of the perons we
* want to say "Hello!" to.<p>
*
* In a more advanced application, this Model component might update
* a persistent store with the person name, use it in an argument in a web
* service call, or send it to a remote system for processing.
*
* @author Kevin Bedell
*/
public class HelloModel {
// --------------------------------------------------- Instance Variables
/**//**
* The new person we want to say "Hello!" to
*/
private String _person = null;
// ----------------------------------------------------------- Properties
/**//**
* Return the new person we want to say "Hello!" to
*
* @return String person the person to say "Hello!" to
*/
public String getPerson() {
return this._person;
}
/**//**
* Set the new person we want to say "Hello!" to
*
* @param person The new person we want to say "Hello!" to
*/
public void setPerson(String person) {
this._person = person;
}
// --------------------------------------------------------- Public Methods
/**//**
* This is a stub method that would be used for the Model to save
* the information submitted to a persistent store. In this sample
* application it is not used.
*/
public void saveToPersistentStore() {
/**//*
* This is a stub method that might be used to save the person's
* name to a persistent store if this were a real application.
*
* The actual business operations that would exist within a Model
* component would be dependedn upon the rquirements of the application.
*/
}
}
通过使用属性向View传递数据Constants.java
package com.javaby.hello;
/**//**
* Constants to be used in the Hello World! Example
* Chapter 03 of "Struts Kickstart"
*
* @author Kevin Bedell
*/
public final class Constants {
/**//**
* The application scope attribute used for passing a HelloModel
* bean from the Action class to the View component
*/
public static final String HELLO_KEY = "com.javaby.hello";
}
完成代码编写之后,还要整合组件,struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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="HelloForm" type="com.javaby.hello.HelloForm"/>
</form-beans>
<action-mappings>
<action name="HelloForm" path="/HelloWorld" type="com.javaby.hello.HelloAction" scope="request" validate="true" input="/Hello.jsp">
<forward name="SayHello" path="/Hello.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.javaby.hello.Application"/>
</struts-config>
这里如果使用JBuilder编写struts-config.xml文件要方便很多,完全图形化操作。这个就是完整的一个很简单的Struts应用。
posted on 2005-07-19 15:44
Java BY 阅读(377)
评论(0) 编辑 收藏 所属分类:
Bo java学习笔记