struts2的action封裝數據的三種方式:
1 action自己屬於modle 屬於屬性驅動
public class Regist extends ActionSupport{
private String usename;
private String password;
private int age;
@Override
public String execute() throws Exception {
//這裏的action可自動接受數據,至關於modle
return super.execute();
}
public void setUsename(String usename) {
this.usename = usename;
}
public void setPassword(String password) {
this.password = password;
}
public void setAge(int age) {
this.age = age;
}
}
一在struts2中,action是多實例的,不存在線程問題
二須要單獨使用javabean將數據傳到業務層java
2 將屬性封裝到action的model成員變量:(屬性驅動)
代碼體現:
public class Regist extends ActionSupport{
private User user;
public String execute() throws Exception {
//這裏的action可自動接受數據
return super.execute();
}
public void setUser(User user) {
this.user = user;
}
//必須提供get方法,不然沒法獲取到model對象
public User getUser() {
return user;
}
}
jsp頁面上交時的代碼體現:
<input type="txt" name="user.username"/>jsp
3 使用ModelDriven接口,對請求數據進行封裝 (模型驅動)
public class Regist extends ActionSupport implements ModelDriven<User>{\
//必須手動實例化
private User user=new User();
public String execute() throws Exception {
return NONE;
}
@Override
public User getModel() {
return user;
}
}ide
4 封裝複雜類型參數(集合類型 Collection 、 Map)
1) 封裝數據到Collection 對象
頁面:
產品名稱 <input type="text" name="products[0].name" /><br/>
產品價格 <input type="text" name="products[0].price" /><br/>
Action :
public class ProductAction extends ActionSupport {
private List<Product> products;
public List<Product> getProducts() {
return products;
}this
public void setProducts(List<Product> products) {
this.products = products;
}
}
2) 封裝數據到Map 對象
頁面:
產品名稱 <input type="text" name="map['one'].name" /><br/> ======= one是map的鍵值
Action :
public class ProductAction2 extends ActionSupport {
private Map<String, Product> map;線程
public Map<String, Product> getMap() {
return map;
}對象
public void setMap(Map<String, Product> map) {
this.map = map;
}
}接口