struts2中的Action有三种方式接收前台的数据:
1.基本数据类型的属性对应
2.域对象的对应
3.模型对应
前两种是属于属性驱动FieldDriven,后面一种是模型驱动ModelDriven
第一种:
前台代码:
<form action="LoginAction.action" method="post">
账号<input type="text" name="userName" />
密码<input type="password" name="userPass" />
<input type="submit" value="提交">
</form>
后台action代码:
public class LoginAction extends ActionSupport {
private String userName;
private String userPass;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public String execute throws Exception(){
return "success";
}
}
第二种:
前台代码:
<form action="LoginAction.action" method="post" >
账号<input type="text" name="user.userName" />
密码<input type="password" name="user.userPass" />
<input type="submit" value="提交">
</form>
后台action代码:
public class LoginAction extends ActionSupport {
private User user = new User();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String execute throws Exception(){
return "success";
}
}
前台代码:
<form action="LoginAction.action" method="post" >
账号<input type="text" name="userName" />
密码<input type="password" name="userPass" />
<input type="submit" value="提交">
</form>
后台action代码:
public class LoginAction extends ActionSupport implements ModelDriven{
private User user = new User();
public Object getModel(){
return user;
}
public String execute throws Exception(){
return "success";
}
}
PS. 三种 方式可以一起使用;
也可以不写getter/setter方法,直接用public,但是不建议,因为这样不安全;
传入多个数据时,前台的name值写一样,action中的属性设置成数组就可以了;
传多个对象也可以,在前台用数组如user[1].userName,后台用list<User> user创建对象;