Action處理請求參數
struts2 和 MVC 定義關係
StrutsPrepareAndExecuteFilter : 控制器
JSP : 視圖
Action : 可以作爲模型,也可以是控制器
struts2 Action 接受請求參數 :屬性驅動 和 模型驅動
Action處理請求參數三種方式
第一種 :Action 本身作爲model對象,通過成員setter封裝 (屬性驅動 )
頁面:
用戶名 <input type="text" name="username" /> <br/>
Action :
public class RegistAction1 extends ActionSupport {
private String username;
public void setUsername(String username) {
this.username = username;
}
}
問題一: Action封裝數據,會不會有線程問題 ?
* struts2 Action 是多實例 ,爲了在Action封裝數據 (struts1 Action 是單例的 )
問題二: 在使用第一種數據封裝方式,數據封裝到Action屬性中,不可能將Action對象傳遞給 業務層
* 需要再定義單獨JavaBean ,將Action屬性封裝到 JavaBean
第二種 :創建獨立model對象,頁面通過ognl表達式封裝 (屬性驅動)
頁面:
用戶名 <input type="text" name="user.username" /> <br/> ----- 基於OGNL表達式的寫法
Action:
public class RegistAction2 extends ActionSupport {
private User user;
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
問題: 誰來完成的參數封裝
<interceptor name="params"
class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>
第三種 :使用ModelDriven接口,對請求數據進行封裝 (模型驅動 ) ----- 主流
頁面:
用戶名 <input type="text" name="username" /> <br/>
Action :
public class RegistAction3 extends ActionSupport implements ModelDriven<User> {
private User user = new User(); // 必須手動實例化
public User getModel() {
return user;
}
}
* struts2 有很多圍繞模型驅動的特性
* <interceptor name="modelDriven"
class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/> 爲模型驅動提供了更多特性
對比第二種、第三種 : 第三種只能在Action中指定一個model對象,第二種可以在Action中定義多個model對象
<input type="text" name="user.username" />
<input type="text" name="product.info" />
封裝數據到Collection和Map
1) 封裝數據到Collection 對象
頁面:
產品名稱 <input type="text" name="products[0].name" /><br/>
Action :
public class ProductAction extends ActionSupport {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
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;
}
}