index.jsp
- 代码
- <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>测试ActionForm</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <h1>测试ActionForm</h1>
- <hr>
- <li>测试动态ActionForm</li><br>
- <form action="dyanactionform.do" method="post">
- 姓名:<input type="text" name="username"><br>
- 年龄:<input type="text" name="age"><br>
- <input type="submit" value="提交">
- </form>
- <p>
- <li>测试struts上传文件</li><br>
- <form action="upload.do" method="post" enctype="multipart/form-data">
- 标题:<input type="text" name="title"><br>
- 文件:<input type="file" name="myfile"><br>
- <input type="submit" value="提交">
- </form>
- <p>
- <li>空字段测试</li><br>
- <form action="blankfield.do" method="post">
- 姓名:<input type="text" name="username"><br>
- <input type="submit" value="提交">
- </form>
- <p>
- <li>测试ActionForm类型转换器</li><br>
- <form action="typeconvert.do" method="post">
- intValue:<input type="text" name="intValue"><br>
- doubleValue:<input type="text" name="doubleValue"><br>
- booleanValue:<input type="text" name="booleanValue"><br>
- java.sql.Date:<input type="text" name="sqlDate"><br>
- java.util.Date:<input type="text" name="utilDate"><br>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
配置文件
struts-config.xml
- 代码
- <?xml version="1.0" encoding="ISO-8859-1" ?>
- <!DOCTYPE struts-config PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
- "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
- <struts-config>
- <form-beans>
- <form-bean name="dynaForm" type="org.apache.struts.action.DynaActionForm">
- <form-property name="username" type="java.lang.String"/>
- <form-property name="age" type="java.lang.Integer"/>
- </form-bean>
- <form-bean name="uploadForm" type="com.bjsxt.struts.UploadActionForm"/>
- <form-bean name="blankFieldForm" type="com.bjsxt.struts.BlankFieldActionForm"/>
- <form-bean name="typeconvertForm" type="com.bjsxt.struts.TypeConvertActionForm"/>
- </form-beans>
- <action-mappings>
- <action path="/dyanactionform"
- type="com.bjsxt.struts.DynaActionFormTestAction"
- name="dynaForm"
- scope="request"
- >
- <forward name="success" path="/dyna_actionform.jsp"/>
- </action>
- <action path="/upload"
- type="com.bjsxt.struts.UploadTestAction"
- name="uploadForm"
- scope="request"
- >
- <forward name="success" path="/upload_success.jsp"/>
- </action>
- <action path="/blankfield"
- type="com.bjsxt.struts.BlankFieldTestAction"
- name="blankFieldForm"
- scope="request"
- >
- <forward name="success" path="/blankfield_success.jsp"/>
- </action>
- <action path="/typeconvert"
- type="com.bjsxt.struts.TypeConvertTestAction"
- name="typeconvertForm"
- scope="request"
- >
- <forward name="success" path="/typeconvert_success.jsp"/>
- </action>
- </action-mappings>
- <controller maxFileSize="10M"/>
- <plug-in className="com.bjsxt.struts.UtilDateConverterInitWithPlugin"/>
- </struts-config>
1、AtionForm
- 代码
- package com.bjsxt.struts;
- import org.apache.struts.action.ActionForm;
- /**
- * 测试空字段
- * @author Administrator
- *
- */
- public class BlankFieldActionForm extends ActionForm {
- private String username;
- private String password;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- 代码
- package com.bjsxt.struts;
- 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;
- /**
- * 测试空字段
- * @author Administrator
- *
- */
- public class BlankFieldTestAction extends Action {
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- return mapping.findForward("success");
- }
- }
- 代码
- <%@ page language="java" contentType="text/html; charset=GB18030"
- pageEncoding="GB18030"%>
- <%@ page import="com.bjsxt.struts.*" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <title>Insert title here</title>
- </head>
- <body>
- <%
- BlankFieldActionForm form = (BlankFieldActionForm)request.getAttribute("blankFieldForm");
- %>
- <li>jsp脚本</li><br>
- 姓名:<%=form.getUsername() %><br>
- 密码:<%=form.getPassword() %><br>
- <p>
- <li>el表达式</li><br>
- 姓名:${blankFieldForm.username }<br>
- 密码:${blankFieldForm.password }<br>
- </body>
- </html>
业务逻辑类
DynaActionFormTestAction.java
- 代码
- package com.bjsxt.struts;
- 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.DynaActionForm;
- /**
- * 测试动态ActionForm
- * @author Administrator
- *
- */
- public class DynaActionFormTestAction extends Action {
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- DynaActionForm daf = (DynaActionForm)form;
- String username = (String)daf.get("username");
- Integer age = (Integer)daf.get("age");
- System.out.println("username=" + username);
- System.out.println("age=" + age);
- return mapping.findForward("success");
- }
- }
成功的返回页面
dyna_actionform.jsp
- 代码
- <%@ page language="java" contentType="text/html; charset=GB18030"
- pageEncoding="GB18030"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <title>Insert title here</title>
- </head>
- <body>
- 用户名称:${dynaForm.map.username }<br>
- 年龄:${dynaForm.map.age }<br>
- </body>
- </html>
2、struts上传文件
- 代码
- package com.bjsxt.struts;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.upload.FormFile;
- /**
- * 上传ActionForm
- * @author Administrator
- *
- */
- public class UploadActionForm extends ActionForm {
- private String title;
- //必须采用FormFile
- private FormFile myfile;
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public FormFile getMyfile() {
- return myfile;
- }
- public void setMyfile(FormFile myfile) {
- this.myfile = myfile;
- }
- }
- 代码
- package com.bjsxt.struts;
- import java.io.FileOutputStream;
- 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.upload.FormFile;
- /**
- * 上传Action
- * @author Administrator
- *
- */
- public class UploadTestAction extends Action {
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- UploadActionForm uaf = (UploadActionForm)form;
- System.out.println("title" + uaf.getTitle());
- FormFile myFile = uaf.getMyfile();
- if (myFile != null) {
- System.out.println("fileName=" + myFile.getFileName());
- FileOutputStream fos = new FileOutputStream("c:\\" + myFile.getFileName());
- fos.write(myFile.getFileData());
- fos.flush();
- fos.close();
- }
- return mapping.findForward("success");
- }
- }
成功返回页面
upload_success.jsp
- 代码
- <%@ page language="java" contentType="text/html; charset=GB18030"
- pageEncoding="GB18030"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <title>Insert title here</title>
- </head>
- <body>
- 标题:${uploadForm.title}<br>
- 文件名:${uploadForm.myfile.fileName }<br>
- </body>
- </html>
3、类型转换
- 代码
- package com.bjsxt.struts;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.apache.commons.beanutils.Converter;
- /**
- * java.util.Date类型转换器
- * @author Administrator
- *
- */
- public class UtilDateConverter implements Converter {
- public Object convert(Class type, Object value) {
- System.out.println("UtilDateConverter.value=" + value);
- if (value == null) {
- return value;
- }
- if (value instanceof Date) {
- return value;
- }
- Date d = null;
- if (value instanceof String) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- try {
- d = sdf.parse((String)value);
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return d;
- }
- }
- 代码
- package com.bjsxt.struts;
- import java.util.Date;
- import javax.servlet.ServletException;
- import org.apache.commons.beanutils.ConvertUtils;
- import org.apache.struts.action.ActionServlet;
- import org.apache.struts.action.PlugIn;
- import org.apache.struts.config.ModuleConfig;
- public class UtilDateConverterInitWithPlugin implements PlugIn {
- public void destroy() {
- }
- public void init(ActionServlet servlet, ModuleConfig config)
- throws ServletException {
- System.out.println("UtilDateConverterInitWithPlugin.init()");
- ConvertUtils.register(new UtilDateConverter(), Date.class);
- }
- }
- 代码
- package com.bjsxt.struts;
- import java.util.Date;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import org.apache.commons.beanutils.ConvertUtils;
- /**
- * 注册java.util.date转换器
- * @author Administrator
- *
- */
- public class UtilDateConverterInitWithServlet extends HttpServlet {
- @Override
- public void init() throws ServletException {
- System.out.println("UtilDateConverterInitWithServlet.init()");
- ConvertUtils.register(new UtilDateConverter(), Date.class);
- }
- }
成功返回页面
typeconvert_success.jsp
- 代码
- <%@ page language="java" contentType="text/html; charset=GB18030"
- pageEncoding="GB18030"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <title>Insert title here</title>
- </head>
- <body>
- intValue:${typeconvertForm.intValue }<br>
- doubleValue:${typeconvertForm.doubleValue }<br>
- booleanValue:${typeconvertForm.booleanValue }<br>
- java.sql.dateValue:${typeconvertForm.sqlDate }<br>
- java.util.utilValue:${typeconvertForm.utilDate }<br>
- </body>
- </html>
讲解
1、动态ActionForm
动态ActionForm是为了避免标准ActionForm膨胀而设计的,使用动态ActionForm可以获得标准
ActionForm的所有功能
* 在struts-config.xml文件中定义动态ActionForm,如:
<form-beans>
<form-bean name="dynaForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="username" type="java.lang.String" />
<form-property name="age" type="java.lang.Integer"/>
</form-bean>
</form-beans>
*在Action中使用动态ActionForm,参见DynaActionFormTestAction.java
DynaActionForm daf = (DynaActionForm)form;
String username = (String)daf.get("username");
Integer age = (Integer)daf.get("age");
动态ActionForm其实是把页面中的html元素的名字和值放到了map中,所以通过get方法可以取出相应的值
动态ActionForm采用EL表达式的输出方式,${dynabean.map.prop}, 参见:dyna_actionform.jsp
动态Action的验证,通常使用动态验证框架validator
2、采用struts上传文件
* 页面的配置,如:
<form action="upload.do" method="post" enctype="multipart/form-data">
标题:<input type="text" name="title"><br>
文件:<input type="file" name="myfile"><br>
<input type="submit" value="提交">
</form>
* ActionForm中使用FormFile来接收上传的文件,参见:UploadActionForm.java
* 在Action中调用FormFile取得上传文件数据,采用流输出,即完成上传,参见:UploadTestAction.java
* 采用<controller/>标签配置上传参数,如:<controller maxFileSize="10M"/>
3、空字段测试
* 在表单中没有input输入域,jsp脚本接收到的值为null,el表达式接收到的值为空串
* 如果表单中的值,没有输入,那么jsp脚本和el表达式接收到的值都为空串
4、测试ActionForm类型的自动转换
* boolean:yes,1,on,true都会转换成True类型,而且忽略大小写,其他情况转换成false
* Date类型的转换:
* 如果是java.sql.Date,页面日期的格式必须为yyyy-mm-dd,才可以转换
* 如果是java.util.Date,默认情况下struts无法转换
* 自定义转换器的实现步骤
* 实现converter接口,实现convert方法
* 将实现的conerter注册,通常情况采用servlet注册
* 采用servlet注册需要注意标签的配置,<load-on-startup>10</load-on-startup>(也可以采用struts plugin注册)
Struts对ActionForm的自动搜集过程:
* 将页面数据放到map中,其中map中的key为页面中的名称,map中的value为页面中的value值
* 调用BeanUtils.setProperties方法,将map中的值逐个设置到ActionForm实例上,对于ActionForm中的每个属性
根据类型调用相应的Converter,然后调用相应的convert方法,将相应的字符串转换成ActionForm中指定的类型
可以通过BeanUtils.copyProperties(目标对象,源对象)方法进行对象值的复制。
本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1080869