struts2教程(3)--请求参数处理
Action處理請求參數(shù)
struts2 和 MVC定義關(guān)系
StrutsPrepareAndExecuteFilter : 控制器
JSP : 視圖
Action : 可以作為模型,也可以是控制器
struts2 Action 接受請求參數(shù) :屬性驅(qū)動(dòng) 和 模型驅(qū)動(dòng)
一、Action處理請求參數(shù)三種方式
第一種 :Action 本身作為model對象,通過成員setter封裝 (屬性驅(qū)動(dòng) )
頁面:
用戶名 <input type="text" name="username" /> <br/>Action :
public class RegistAction1 extends ActionSupport {private String username;public void setUsername(String username) {this.username = username;}}問題一: Action封裝數(shù)據(jù),會(huì)不會(huì)有線程問題 ?
??* struts2 Action 是多實(shí)例 ,為了在Action封裝數(shù)據(jù) ?(struts1 Action是單例的 )
問題二: 在使用第一種數(shù)據(jù)封裝方式,數(shù)據(jù)封裝到Action屬性中,不可能將Action對象傳遞給 業(yè)務(wù)層
??* 需要再定義單獨(dú)JavaBean,將Action屬性封裝到JavaBean
??
第二種 :創(chuàng)建獨(dú)立model對象,頁面通過ognl表達(dá)式封裝 (屬性驅(qū)動(dòng))
頁面:
用戶名 <input type="text" name="user.username" /> <br/> ----- 基于OGNL表達(dá)式的寫法Action:
public class RegistAction2 extends ActionSupport {private User user;public void setUser(User user) {this.user = user;}public User getUser() {return user;}}問題: 誰來完成的參數(shù)封裝
<interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>第三種?:使用ModelDriven接口,對請求數(shù)據(jù)進(jìn)行封裝 (模型驅(qū)動(dòng) )----- 主流
頁面:
用戶名 <input type="text" name="username" /> <br/>
?
Action :
public class RegistAction3 extends ActionSupport implements ModelDriven<User> {private User user = new User(); // 必須手動(dòng)實(shí)例化public User getModel() {return user;}}?struts2 有很多圍繞模型驅(qū)動(dòng)的特性
<interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>為模型驅(qū)動(dòng)提供了更多特性
總結(jié):
對比第二種、第三種 :第三種只能在Action中指定一個(gè)model對象,第二種可以在Action中定義多個(gè)model對象
<input type="text" name="user.username" />
<input type="text" name="product.info" />
二、封裝數(shù)據(jù)到Collection和Map
1) 封裝數(shù)據(jù)到Collection對象
頁面:
產(chǎn)品名稱 <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) 封裝數(shù)據(jù)到Map對象
頁面:
產(chǎn)品名稱 <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;}}總結(jié)
以上是生活随笔為你收集整理的struts2教程(3)--请求参数处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2教程(2)--配置
- 下一篇: struts2教程(4)--类型转换