The ActionForm Class
本文出处:http://www.roseindia.net/struts/strutsActionForms.shtml
In this lesson you will learn about the ActionForm in detail. I will show you a good example of ActionForm. This example will help you understand Struts in detail. We will create user interface to accept the address details and then validate the details on server side. On the successful validation of data, the data will be sent to model (the action class). In the Action class we can add the business processing logic but in this case we are just forwarding it to the sucess.jsp.
What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm
. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
We will first create the class AddressForm which extends the ActionForm class. Here is the code of the class:
AddressForm.java
<!---->
package roseindia.net;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
/** * @author Deepak Kumar * @Web http://www.roseindia.net * @Email roseindia_net@yahoo.com */
/** * Form bean for the Address Entry Screen. * */ public class AddressForm extends ActionForm { private String name=null; private String address=null; private String emailAddress=null;
public void setName(String name){ this.name=name; }
public String getName(){ return this.name; }
public void setAddress(String address){ this.address=address; }
public String getAddress(){ return this.address; }
public void setEmailAddress(String emailAddress){ this.emailAddress=emailAddress; }
public String getEmailAddress(){ return this.emailAddress; }
/** * 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.name=null; this.address=null; this.emailAddress=null; }
/** * Reset all properties to their default values. * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing * @return errors */ public ActionErrors validate( ActionMapping mapping, HttpServletRequest request ) { ActionErrors errors = new ActionErrors(); if( getName() == null || getName().length() < 1 ) { errors.add("name",new ActionMessage("error.name.required")); } if( getAddress() == null || getAddress().length() < 1 ) { errors.add("address",new ActionMessage("error.address.required")); } if( getEmailAddress() == null || getEmailAddress().length() < 1 ) { errors.add("emailaddress",new ActionMessage("error.emailaddress.required")); }
return errors; }
} |
<!---->
<script type="text/javascript"><!----></script>
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script>
<iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-0714075272818912&amp;dt=1180846444031&amp;lmt=1180846444&amp;prev_fmts=120x90_0ads_al_s%2C336x280_as&amp;format=336x280_as&amp;output=html&amp;correlator=1180846443781&amp;url=http%3A%2F%2Fwww.roseindia.net%2Fstruts%2FstrutsActionForms.shtml&amp;color_bg=FFFFFF&amp;color_text=000080&amp;color_link=000080&amp;color_url=000080&amp;color_border=FFFFFF&amp;ad_type=text_image&amp;cc=1382&amp;flash=9&amp;u_h=768&amp;u_w=1024&amp;u_ah=738&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=480&amp;u_java=true" frameborder="0" width="336" scrolling="no" height="280" allowtransparency=""></iframe>
The above class populates the Address Form data and validates it. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object. Note that we are using ActionMessage class, ActionError is now deprecated and will be removed in next version.
Now we will create the Action class which is the model part of the application. Our action class simply forwards the request the Success.jsp. Here is the code of the AddressAction class:
AddressAction.java
<!---->
package roseindia.net;
/** * @author Deepak Kumar * @Web http://www.roseindia.net * @Email roseindia_net@yahoo.com */
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;
public class AddressAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ return mapping.findForward("success"); } } |
|
Now we have to create an entry for form bean in the struts-config.xml. Add the following lines in the struts-config.xml file:
<form-bean
name="AddressForm"
type="roseindia.net.AddressForm"/>
Add the following line in the struts-config.xml file for handling the action "/Address.do":
<action
path="/Address"
type="roseindia.net.AddressAction"
name="AddressForm"
scope="request"
validate="true"
input="/pages/Address.jsp">
<forward name="success" path="/pages/success.jsp"/>
</action>
Now create Address.jsp, which is our form for entering the address details. Code for Address.jsp is as follows:
Address.jsp
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
<title><bean:message key="welcome.title"/></title>
<html:base/>
</head>
<body bgcolor="white">
<html:form action="/Address">
<html:errors/>
<table>
<tr>
<td align="center" colspan="2">
<font size="4">Please Enter the Following Details</font>
</tr>
<tr>
<td align="right">
Name
</td>
<td align="left">
<html:text property="name" size="30" maxlength="30"/>
</td>
</tr>
<tr>
<td align="right">
Address
</td>
<td align="left">
<html:text property="address" size="30" maxlength="30"/>
</td>
</tr>
<tr>
<td align="right">
E-mail address
</td>
<td align="left">
<html:text property="emailAddress" size="30" maxlength="30"/>
</td>
</tr>
<tr>
<td align="right">
<html:submit>Save</html:submit>
</td>
<td align="left">
<html:cancel>Cancel</html:cancel>
</td>
</tr>
</table>
</html:form>
</body>
</html:html>
|
User enter the values in the form and click on the submit form. Form validation is done on the server side and error message is displays on the jsp page. To display the error on the jsp page <html:errors/> tag is used. The <html:errors/> tag displays all the errors in one go. To create text box <html:text .../> is used in jsp page.
e.g.
<html:text property="address" size="30" maxlength="30"/>
Above tag creates text box for entering the address. The address is retrieved from and later stored in the property named address in the form-bean. The tag
<html:submit>Save</html:submit> creates the submit button and the tag
<html:cancel>Cancel</html:cancel> is used to create the Cancel button.
Add the following line in the index.jsp to create a link for testing the Address.jsp form:
<html:link page="/pages/Address.jsp">Test the Address Form</html:link>
Build the application and click on the Test the Address Form link on the index page to test the newly created screen. You should see the following screen.

In this lesson you learned how to create data entry form using struts, validate and finally send process the business logic in the model part of the struts.

分享到:
相关推荐
The ActionForm class ActionForm maintains the session state for the Web application. ActionForm is an abstract class that is sub-classed for each input form model. When I say input form model, I am ...
public class UpLoadAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // ...
// Save the file to server directory FileUtils.copyFile(file, new File("uploads/" + fileName)); } catch (Exception e) { // Handle exception } return SUCCESS; } // getters and setters } ``` ##...
// Replace values for the template plugin template_replace_values : { username : "Some User", staffid : "991234" } }); <form name="actionForm" method="post" action="exPlainInfo.action?method=...
public class CustForm extends ActionForm { private String phone; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } ``` - **解释**:这个...
public class UpLoadAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (form...
public class MyForm extends ActionForm { private String username; // getters and setters... } ``` 5. **处理表单提交**:在Action类中,处理用户提交的表单数据。Struts会自动调用Validator进行验证,...
在 Struts1 中,我们需要创建一个 ActionForm 类来接收和封装请求参数。但在 Struts2 中,我们可以直接在 Action 类中定义属性,Struts2 会自动将请求参数绑定到这些属性。下面是 JSP 页面中用于用户输入的表单: ``...
// Save the file to the server item.write(new File("path/to/save/uploaded/files/" + fileName)); } } } // Continue with normal action processing } ``` - 在JSP页面中创建一个表单,使用`enctype=...
- `Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()`:这段代码是为了注册并加载Oracle的JDBC驱动,使得应用程序能够与Oracle数据库建立连接。 - `DriverManager.getConnection(dbUrl, theUser, ...
The ID is: ("id") %> ``` 在上面的示例中,我们使用`request.getParameter("id")`获取了从URL传递过来的ID参数。 #### 八、总结 通过以上步骤,我们已经成功地利用UrlRewriteFilter实现了页面的伪静态化。这种...
public ActionForward addCall(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ServletContext context = this.getServlet().getServletContext(); //...
189、Can a Java Thread be started from Servlet class, and what will be the implications? 45 190、What is HTTP Session tracking and why is it important? 45 191、What is session management, and how is ...
public class UploadForm extends ActionForm { private FormFile file; // getters and setters } public class UploadAction extends Action { public ActionForward execute(ActionMapping mapping, ...
public class UpLoadAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if ...
- **Struts**: 使用 `ActionForm` 类来封装表单数据,框架会自动将表单提交的参数与 `ActionForm` 类中的属性进行匹配,并填充这些属性。 - **Spring**: 通过 `ModelAttribute` 注解或者默认的方法,Spring MVC 能够...
值栈是一个基于栈的数据结构,用于存储应用程序中的不同对象,如Action对象、ActionForm对象等。它的主要作用是提供一种统一的方式来访问和管理这些对象。值栈可以通过JSP、Velocity或Freemarker的标签进行操作。在...