Struts2的屬性驅動原理和模型驅動原理
阿新 • • 發佈:2019-02-09
屬性驅動:(靠的是ParameterInterceptor攔截器,setValue方法操作值桟屬性)
* 在action中設定屬性,屬性的名稱和頁面上表單中的name屬性的名稱保持一致
* 在action中的屬性,必須有set和get方法
* 好處: 這樣設計可以保證action與servlet容器鬆耦合
* 如果屬性驅動和模型驅動屬性名重複,只有模型驅動能取到值,屬性驅動為null
屬性驅動原理圖:
例子:
表單頁面
<body> <s:form action="testParameterInterceptor_Login"> 帳號<s:textfield name="userName"/><br> 密碼<s:password name="passWord"/><br> <s:submit value="提交"/> </s:form> </body>
Action
public class TestParameterInterceptorAction extends ActionSupport { private String userName; private String passWord; public String execute() throws Exception { return SUCCESS; } public String Login() throws Exception { System.out.println("userName--->"+userName); System.out.println("passWord--->"+passWord); return null; } 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; } }
模型驅動:
* 如果在頁面上的表單中,表單的內容很多,這個時候就會在action中寫很多屬性和屬性的set,get方法,這樣寫程式碼結構不好
* 採用javabean
* 讓該action實現ModelDriver
模型驅動原理圖:
例子:
javaBean
public class User { 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; } }
表單頁面
<body>
<s:form action="testModelDrivenInterceptor_Login">
帳號<s:textfield name="userName"/><br>
密碼<s:password name="passWord"/><br>
<s:submit value="提交"/>
</s:form>
</body>
Action
/**
* 要用模型驅動攔截器,就需要實現ModelDriven介面,覆寫getModel()
*/
public class TestmodelDrivenInterceptorAction extends ActionSupport implements ModelDriven<User>{
private User user = new User();
public String execute() throws Exception {
return SUCCESS;
}
public String Login() throws Exception {
System.out.println(user.getUserName());
System.out.println(user.getPassWord());
return null;
}
public User getModel() {
return this.user;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}