struts2有三种接收参数的方式:
1、Action属性
2、Domain Model
3、ModelDriven
login.jsp页面:
<body> <form action="loginAction.action" method="post" > 用户名:<input type="text" name="username"/> 密码:<input type="password" name="password"/> <input type="submit" value="login" /> </form> </body>
1、Action属性方法:
通过表单的username和action属性username直接对应传递过来。
public class LoginAction extends ActionSupport{ private String username; private String password; public String login(){ System.out.println(username); //... return SUCCESS; } 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; } }
2、通过Domain Model方法:
先建立User类,有username和password两个属性。
(1)login.jsp页面要修改name属性,才能和action中代码对应
<form action="loginAction.action" method="post" > 用户名:<input type="text" name="user.username"/> 密码:<input type="password" name="user.password"/> <input type="submit" value="login" /> </form>
(2)loginAction.java类,user和表单中的user对应:
public class LoginAction extends ActionSupport{ private User user; public String login(){ System.out.println(user.getUsername()); //... return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
3、ModelDriven方法:
(1)login.jsp页面,稍微改动name属性
用户名:<input type="text" name="username"/> 密码:<input type="password" name="password"/>
(2)LoginAction.java类,要实现ModelDriven类,泛型为User。声明user对象时要实例化,在Domain Model方法中不用。
public class LoginAction extends ActionSupport implements ModelDriven<User>{ private User user=new User(); public String login(){ System.out.println(user.getUsername()); //... return SUCCESS; } @Override public User getModel() { return null; } }
玩了好多天,赶紧做个笔记回回神。
本文出自 “Sunny” 博客,请务必保留此出处http://qmkkd.blog.51cto.com/9511687/1837114
原文地址:http://qmkkd.blog.51cto.com/9511687/1837114