接上一篇文章
package test;import com.opensymphony.xwork2.ActionSupport; import javax.servlet.http.*; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import java.util.*; public class HelloAction extends ActionSupport {public String jname = "";public String jid = "";@Overridepublic String execute() throws Exception {// TODO Auto-generated method stubreturn super.execute();}private String str = "";public String hello() {this.str = "hello!!!";System.out.println("方法一,把参数作为Action的类属性,让OGNL自动填充:");System.out.println("jname:" + jname + " jid:" + jid);ActionContext context=ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);System.out.println("方法二,在Action中取得HttpServletRequest对象,使用request.getParameter获取参数");System.out.println("jname:" + request.getParameter("jname") + " jid:" + request.getParameter("jid"));Map parameterMap=context.getParameters(); String bookName2[]=(String[])parameterMap.get("jname"); String bookPrice2[]=(String[])parameterMap.get("jid"); System.out.println("方法三,在Action中使用ActionContext得到parameterMap获取参数:"); System.out.println("jname: " +bookName2[0]); System.out.println("jid: " +bookPrice2[0]); return "success";}public String getStr() {return str;}public void setStr(String str) {this.str = str;}public String getJname() {return jname;}public void setJname(String jname) {this.jname = jname;}public String getJid() {return jid;}public void setJid(String jid) {this.jid = jid;} }
总结:
方法一:当把参数作为Action的类属性,且提供属性的getter/setter方法时,xwork的OGNL会自动把request参数的值设置到类属性中,此时访问请求参数只需要访问类属性即可。
方法二:可以通过ActionContext对象Map parameterMap=context.getParameters();方法,得到请求参数Map,然后通过parameterMap来获取请求参数。需要注意的是:当通过parameterMap的键取得参数值时,取得是一个数组对象,即同名参数的值的集合。
方法三:通过ActionContext取得HttpServletRequest对象,然后使用request.getParameter("参数名")得到参数值。
参考:http://www.cnblogs.com/bmbm/archive/2011/11/28/2342273.html