prams拦截器,可以把请求数据自动填充的action的属性中 举例1: JSP <input type=text name=userName /> <input type=text name=pwd /> Action class UserAction{ // 封装请求数据 private String userName; private String pwd; //.. set方法 } 举例2: JSP <input type=text name=user.userName /> <input type=text name=user.pwd /> Action class UserAction{ // 封装请求数据 private User user; .. } 举例3:(模型驱动) JSP <input type=text name=userName /> <input type=text name=pwd /> Action class UserAction{ // 封装请求数据 private User user; .. }
步骤及原理
步骤:
1. 实现ModelDriver接口
2. 实现接口方法: 接口方法返回的就是要封装的对象
3. 对象一定要实例化。
package loaderman.b_form; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.util.ValueStack; /** * 1. 数据回显 * 2. 模型驱动 * */ public class UserAction extends ActionSupport implements ModelDriven<User> { // 封装请求数据 private User user = new User(); public void setUser(User user) { this.user = user; } public User getUser() { return user; } // 实现模型驱动接口方法 @Override public User getModel() { return user; } public String add() { // 测试: 使用了模型驱动,是否数据正常? Ok System.out.println(user); return "success"; } // 进入修改页面 public String viewUpdate() { // 模拟一个对象(先获取一个id,再根据id调用service查询,把查到的结果保存到域) User userInfo = new User(); userInfo.setUserName("Jack"); userInfo.setEmail("yuanjie@loaderman.cn"); ActionContext ac = ActionContext.getContext(); // Map<String,Object> request = (Map<String, Object>) ac.get("request"); // request.put("userInfo", userInfo); /************* 数据回显***************/ // 获取值栈 ValueStack vs = ac.getValueStack(); vs.pop();// 移除栈顶元素 vs.push(userInfo); // 入栈 // 进入修改页面 return "viewUpdate"; } // 业务方法 public String index() { // 保存数据到request域 ActionContext ac = ActionContext.getContext(); Map<String,Object> request = (Map<String, Object>) ac.get("request"); request.put("cn", "China"); return SUCCESS; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <s:form action="/user_add" method="post"> 用户名:<s:textfield name="userName"></s:textfield> <br/> 密码:<s:textfield name="pwd"></s:textfield> <br/> <s:submit value="保存用户"></s:submit> </s:form> </body> </html>