Struts2 参数传入四种方式
public class UserAction { private String name; private int age; public String add(){ System.out.println(name+age); return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public class UserModelAction { private User user; public String add(){ System.out.println(user.getName()+user.getAge()); return "success"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
public class UserModelDrivenAction implements ModelDriven<User>{ private User user = new User();; public String add(){ System.out.println("姓名"+user.getName()+"年龄:"+user.getAge()); return "success"; } //使用 ModelDriven 将参数值存入对应的对象中,user 对象必须被初始化,在跳转的页面能够得到参数的值 @Override public User getModel() { // TODO Auto-generated method stub return user; } }
配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="param" namespace="/param" extends="struts-default"> <action name="user" class="com.yao.action.paramInput.UserAction" > <result>/ActionParamInput/success.jsp</result> </action> <!-- 参数初始化一个对象 --> <action name="userModel" class="com.yao.action.paramInput.UserModelAction" method="add"> <result>/ActionParamInput/success.jsp</result> </action> <action name="userModelDriver" class="com.yao.action.paramInput.UserModelDrivenAction" method="add"> <result>/ActionParamInput/success.jsp</result> </action> </package> </struts>
(一)页面表单提交
<form action="/param/user!add" method="post"> <input type="text" name="name"> <input type="text" name="age"> <input type="submit" value="submit"> </form>
(二)表单Model方式
<form action="/param/userModel" method="get"> <input type="text" name="user.name"> <input type="text" name="user.age"> <input type="submit" value="submit"> </form>
(三)ModelDriver
<form action="/param/userModelDriver" method="get"> <input type="text" name="name"> <input type="text" name="age"> <input type="submit" value="submit"> </form>
(四)URL
通过链接传递参数 <a href="<%=path%>/param/user!add?name=宋&age=9">添加用户</a> <br> 使用Domain Model接收参数<a href="<%=path%>/param/userModel!add?user.name=song&user.age=8">添加用户</a>