- 用Action的属性:
JSP:
<form action="login" method="post" name="form1">
用户名:<s:textfield name="username"/><br/>
密 码:<s:password name="password"/><br/>
<s:submit value="提交"/>
</form>
Action:
在action 里面定义要接收的参数,并提供相应的setter,getter,和提交参数的名称一致,并不用做数据类型的转换。相应提交方式可以用get 和post,如:testAction? name=admin
public class TestAction extends ActionSupport{
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;
}
}
- 使用DomainModel:
在Action 里面不用很多的属性,而是用Model 层用到的模型,保存它的一个对象。相应提交方式可以用get 和post,
如:testAction? resBananRc.name=admin
Action:
public class TestAction extends ActionSupport{
//错误的写法,不能自己实例化,struts会自动实例化 private Users users = new Users();
private Users users;
public Users getUsers(){
return users;
}
public void setUsers(Users users){
this.users=users;
}
User.java
public class Users{
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;
}
}
3, 使用DTO–数据传输对象
它的作用是接收参数,传递参数,并不是项目中的实体类。如用户注册时,会用到确认密码,所以要先把参数接收过来,做处理后,再传递给相应方法去创建User 对象。提交参数的方式的Domain Model 方式的相同。
public class UserDTO {
private String name;
private String password;
private String confirm;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirm() {
return confirm;
}
public void setConfirm(String confirm) {
this.confirm = confirm;
}
}
public class TestAction extends ActionSupport{
private static final long serialVersionUID = -7463970150000893325L;
private UserDTO userDTO;
public UserDTO getUserDTO() {
return userDTO;
}
public void setUserDTO(UserDTO userDTO) {
this.userDTO = userDTO;
}
public void execeute() {
System.out.println("姓名: " + userDTO.getName());
}
}
4.使用ModelDriven:
在创建Action 的时候,Action 实现了ModelDriven 接口,去调用接口的getModel()方法,取到了相关对象。
相应提交方式可以用get 和post,如:testAction? name=admin
public class sysAction extends ActionSupport implements ModelDriven<User>{
private User user = new User(); //手动实例化
public User getModel() {
return user; //返回实例
}
}
5.使用request对象:
此方法与与传统的JSP 等传接参数一样,即使用request. getParameter(“”)方法
public class TestAction extends ActionSupport{
private static final long serialVersionUID = -7463970150000893325L;
public void execeute() {
String name = super.getRequest().getParameter("paraName");
System.out.println("姓名:" + name);
}
}