Struts2接收参数的几种方式
一、用Action属性
在action里定义要接收的参数,并提供相应的set和get方法。
如:
public class LoginAction extends ActionSupport { private String username; private String password; //对应的get set方法 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; } public String execute() { // TODO Auto-generated method stub System.out.println("username = "+username); System.out.println("password = "+password); return SUCCESS; } }
<form action="login" method="post"> 用户名:<input type="text" name="username"><br/> 密 码:<input type="password" name="password"><br/> <input type="submit" value="提交"> </form>
二、使用DomainModel
如果Action中属性过多,则可以Model保存为一个对象,并提供get和set
Model类
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; } }
Action类
public class LoginAction extends ActionSupport { private User user; public String execute() { // TODO Auto-generated method stub System.out.println("username = "+user.getUsername()); System.out.println("password = "+user.getPassword()); return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
JSP
<form action="login" method="post"> 用户名:<input type="text" name="user.username"><br/> 密 码:<input type="password" name="user.password"><br/> <input type="submit" value="提交"> </form>
三、使用ModelDriven(模型驱动)
使用模型驱动模式时,Acton必须实现ModelDriven接口,实现该接口则必须实现getModel()方法,该方法用于把Action和与之对应的Model实例关联起来。
Model类同DomainModel
Action类
public class LoginAction extends ActionSupport implements ModelDriven<User> { private User user = new User(); //需实例化 public String execute() { // TODO Auto-generated method stub System.out.println("username = "+user.getUsername()); System.out.println("password = "+user.getPassword()); return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public User getModel() { // TODO Auto-generated method stub return user; } }
JSP
<form action="login" method="post"> <!-- 属性可以为 对象.XXX 也可以直接为XXX 则前提Action中要自己实例化Model对象 --> 用户名:<input type="text" name="user.username"><br/> 密 码:<input type="password" name="password"><br/> <input type="submit" value="提交"> </form>
四、使用request接收参数
此方法和传统的JSP页面接收参数一样,用request.getParameter("")方法。
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!