在struts2,参数传递方式有如下三种。
一、使用Action熟悉接受参数
(1)UserAction
package com.struts2.study.yy;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
private int age;
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 String add(){
System.out.println("name=" + name + ",age=" + age);
return SUCCESS;
}
}
即在UserAction中定义两个变量name和age。
(2)struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="user" extends="struts-default" namespace="/user">
<action name="user" class="com.struts2.study.yy.UserAction">
<result>/user_add_success.jsp</result>
</action>
</package>
</struts>
(3)index.jsp
使用action属性接收参数<a href="user/user!add?name=yy&age=25">add user</a>
二、使用Domain Model接受参数
即借助于一个实体类
(1)User.java
public class User {
private String name;
private int age;
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;
}
}
(2)UserAction.java
package com.struts2.study.yy;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String add(){
System.out.println("name=" + user.getName() + ",age=" + user.getAge());
return SUCCESS;
}
}
(3)struts.xml
<package name="user" extends="struts-default" namespace="/user">
<action name="user" class="com.struts2.study.yy.UserAction">
<result>/user_add_success.jsp</result>
</action>
</package>
(4)程序入口
使用Domain Model接收参数<a href="user/user!add?user.name=yy&user.age=25">Add user</a>
三、使用模型驱动ModelDriven
主要是在action中实现ModelDriven接口,如下:
package com.struts2.study.yy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction3 extends ActionSupport implements ModelDriven<User>{
private static final long serialVersionUID = 1L;
private User user = new User();
public String add(){
System.out.println("name=" + user.getName() + ",age=" + user.getAge());
return SUCCESS;
}
@Override
public User getModel() {
// TODO Auto-generated method stub
return user;
}
}
重写getModel方法,返回实体对象。页面调用与二相同。