struts2接收参数的几种形式
1. 用Action的属性:
在action 里面定义要接收的参数,并提供相应的setter,getter,和提交参数的名称一致,并不用做数据类型的转换。
相应提交方式可以用get 和post,如:testAction? name=admin
如:
1 public class TestAction extends ActionSupport{ 2 private static final long serialVersionUID = -7463970150000893325L; 3 private String name; 4 5 public void execeute() { 6 System.out.println(name + " : " + name); 7 } 8 9 public String getName() { 10 return name; 11 } 12 13 public void setName(String name) { 14 this.name = name; 15 } 16 }
2. 使用DomainModel:
在Action 里面不用很多的属性,而是用Model 层用到的模型,保存它的一个对象。相应提交方式可以用get 和post,
如:testAction? resBananRc.name=admin
如:
1 public class TestAction extends ActionSupport{ 2 private static final long serialVersionUID = -7463970150000893325L; 3 private ResBananRc resBananRc; 4 5 public ResBananRc getResBananRc() { 6 return resBananRc; 7 } 8 9 public void setResBananRc(ResBananRc resBananRc) { 10 this.resBananRc = resBananRc; 11 } 12 13 public void execeute() { 14 System.out.println("姓名: " + resBananRc.getName()); 15 } 16 }
3. 使用DTO--数据传输对象
它的作用是接收参数,传递参数,并不是项目中的实体类。如用户注册时,会用到确认密码,所以要先把参数接收过
来,做处理后,再传递给相应方法去创建User 对象。提交参数的方式的Domain Model 方式的相同。
DTO:
1 public class UserDTO { 2 private String name; 3 private String password; 4 private String confirm; 5 6 public String getName() { 7 return name; 8 } 9 public void setName(String name) { 10 this.name = name; 11 } 12 public String getPassword() { 13 return password; 14 } 15 public void setPassword(String password) { 16 this.password = password; 17 } 18 public String getConfirm() { 19 return confirm; 20 } 21 public void setConfirm(String confirm) { 22 this.confirm = confirm; 23 } 24 }
Action:
1 public class TestAction extends ActionSupport{ 2 private static final long serialVersionUID = -7463970150000893325L; 3 private UserDTO userDTO; 4 5 public UserDTO getUserDTO() { 6 return userDTO; 7 } 8 public void setUserDTO(UserDTO userDTO) { 9 this.userDTO = userDTO; 10 } 11 public void execeute() { 12 System.out.println("姓名: " + userDTO.getName()); 13 } 14 }
4.使用ModelDriven:
在创建Action 的时候,Action 实现了ModelDriven 接口,去调用接口的getModel()方法,取到了相关对象。
相应提交方式可以用get 和post,如:testAction? name=admin
1 public class TestAction extends ActionSupport implements ModelDriven<ResBananRc> { 2 private static final long serialVersionUID = -7463970150000893325L; 3 private ResBananRc resBananRc = new ResBananRc();// 这里要手动的New下 4 5 public ResBananRc getModel() { 6 return resBananRc; 7 } 8 public void execeute() { 9 System.out.println("姓名:" + resBananRc.getName()); 10 } 11 }
5.使用request对象:
此方法与与传统的JSP 等传接参数一样,即使用request. getParameter(“”)方法
1 public class TestAction extends ActionSupport{ 2 private static final long serialVersionUID = -7463970150000893325L; 3 4 public void execeute() { 5 String name = super.getRequest().getParameter("paraName"); 6 System.out.println("姓名:" + name); 7 } 8 }
转载自:http://www.cnblogs.com/o-andy-o/archive/2012/08/12/2635537.html