在struts2中提供了ModelDriven模型驱动,实现ModelDriven接口,会实现方法getModel。这样做的好处就是页面传过来的多个实体对象的属性,架构就会自动的将数据传给对象。
建立Action继承ActionSupport,并实现ModelDriven接口,当页面将User对象的属性值传到Action的时候,ModelDriven就会将数据赋值给user。当return success时,会将属性值传递给对应的result页面。
package syq.action; import syq.vo.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class UserAction extends ActionSupport implements ModelDriven<User> { //驱动模型使用对象 private User user=new User(); public User getModel() { return user; } public String regist(){ return SUCCESS; } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <!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=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/regist.action" method="post"> <table> <tbody> <tr> <td> 用户名:<input type="text" id="name" name="name" class="text" maxlength="20"> </td> </tr> <tr> <td> 密 码:<input type="text" id="password" name="password" class="text" maxlength="20"> </td> </tr> <tr> <td> 性 别:<input type="text" id="sex" name="sex" class="text" maxlength="20"> </td> </tr> <tr> <td> 年 龄:<input type="text" id="age" name="age" class="text" maxlength="20"> </td> </tr> <tr> <td> 爱 好:<input type="text" id="hobby" name="hobby" class="text" maxlength="20"> </td> </tr> <tr> <td> <input type="submit" id="submit" value="注册"> </td> </tr> <tbody> <table> </form> </body> </html>
显示注册信息页面,接受返回的对象的属性值,并显示到页面。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <!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=ISO-8859-1"> <title>用户信息</title> </head> <body> 姓名:<s:property value="name"/></br> 年龄:<s:property value="age"/></br> 性别:<s:property value="sex"/></br> 年龄:<s:property value="hobby"/></br> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts2_ModelDriven" extends="struts-default"> <action name="regist" class="syq.action.UserAction" method="regist"> <result name="success">/WEB-INF/show.jsp</result> </action> </package> </struts>
利用ModelDriven,会使访问对象的属性时更简单,也体现了封装性。
源码地址:http://pan.baidu.com/s/1pJ1kg6R
提取码:hdgi