Struts2中Action接收參數的方法主要有以下三種:
1.使用Action的屬性接收參數:(通過屬性驅動式)
a.定義:在Action類中定義屬性,創建get和set方法;
b.接收:通過屬性接收參數,如:userName;
c.發送:使用屬性名傳遞參數,如:user1!add?userName=Magci;
JSP:
<form action="sys/login.action" method="post"> <input type="text" name="username"> <input type="submit" value="submit"> </form>
Action:直接通過get、set方法獲取。
public class sysAction extends ActionSupport{ private String username; public String login() throws Exception { System.out.println(username); return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username= username; } }
2.使用ModelDriven接收參數:(模型驅動方式,必須要實現ModelDriven<T>接口。對於要傳入多個model第二種方式不方便)
a.定義:Action實現ModelDriven泛型接口,定義Model類的對象(必須new),通過getModel方法返回該對象;
b.接收:通過對象的屬性接收參數,如:user.getUserName();
c.發送:直接使用屬性名傳遞參數,如:user2!add?userName=MGC
JSP:
<form action="sys/login.action" method="post"> <input type="text" name="username"> <input type="submit" value="submit"> </form>
Action:必須實現getModel() 方法
public class sysAction extends ActionSupport implements ModelDriven<User>{ private User user; public String login() throws Exception { System.out.println(getModel().getUsername()); return SUCCESS; } public User getModel() { if (null == user) { return user = new User(); } return user; } }
3.使用DomainModel接收參數:(第三種領域模型方式可以完全不實現ModelDriven<T>,也可使用多個model對象的屬性。)
a.定義:定義Model類,在Action中定義Model類的對象(不需要new),創建該對象的get和set方法;
b.接收:通過對象的屬性接收參數,如:user.getUserName();
c.發送:使用對象的屬性傳遞參數,如:user2!add?user.userName=MGC;
JSP:
<form action="sys/login.action" method="post"> <input type="text" name="user.username"> <input type="text" name="teacher.level"> <input type="submit" value="submit"> </form>
Action: 必須提供set方法
public class sysAction extends ActionSupport{ private User user; private Teacher teacher; public String login() throws Exception { System.out.println(user.getUsername()); System.out.println(teacher.getLevel()); return SUCCESS; } public void setUser(User user) { this.user = user; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } }