在Struts2的Action中取得请求参数值的几种方法

public class GetRequestParameterAction extends ActionSupport {  
  
    private String bookName;  
    private String bookPrice;  
      
    public String getBookName() {  
        return bookName;  
    }  
  
    public void setBookName(String bookName) {  
        this.bookName = bookName;  
    }  
  
    public String getBookPrice() {  
        return bookPrice;  
    }  
  
    public void setBookPrice(String bookPrice) {  
        this.bookPrice = bookPrice;  
    }  
      
      
    public String  execute() throws Exception{  
          
          
        //方式一: 将参数做为Action的类属性,让OGNL自动填充  
           
        System.out.println("方法一,把参数做为Action的类属性,让OGNL自动填充:");  
        System.out.println("bookName: "+this.bookName);  
        System.out.println("bookPrice: " +this.bookPrice);  
          
          
        //方法二:在Action中使用ActionContext获得parameterMap获取参数:  
        ActionContext context=ActionContext.getContext();  
        Map  parameterMap=context.getParameters();  
          
        String bookName2[]=(String[])parameterMap.get("bookName");  
        String bookPrice2[]=(String[])parameterMap.get("bookPrice");  
          
        System.out.println("方法二,在Action中使用ActionContext获得parameterMap获取参数:");  
        System.out.println("bookName: " +bookName2[0]);  
        System.out.println("bookPrice: " +bookPrice2[0]);  
          
          
        //方法三:在Action中取得HttpServletRequest对象,使用request.getParameter获取参数  
        HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);   
           
        String bookName=request.getParameter("bookName");  
        String bookPrice=request.getParameter("bookPrice");  
          
        System.out.println("方法三,在Action中取得HttpServletRequest对象,使用request.getParameter
        获取参数:");  
        System.out.println("bookName: " +bookName);  
        System.out.println("bookPrice: " +bookPrice);  
        return SUCCESS;  
          
    }  
  
}

 

  • 方法一:当把参数做为Action的类属性,且提供属性的getter/setter方法时,xwork的OGNL会自动把request参数的值设置到类属性中,此时访问请求参数只须要访问类属性便可。数组

  • 方法二:能够经过ActionContext对象Map  parameterMap=context.getParameters();方法,获得请求参数Map,而后经过parameterMap来获取请求参 数。须要注意的是:当经过parameterMap的键取得参数值时,取得是一个数组对象,即同名参数的值的集合。this

  • 方法三:经过ActionContext取得HttpServletRequest对象,而后使用request.getParameter("参数名")获得参数值。spa

    -------------------------code

  • 方法四:域模型对象

  • 方法五:ModelDriven,它是Struts2种独有的一种接收用户输入的机制,想在项目中使用模型驱动(ModelDriven)须要让Action实现com.opensymphony.xwork2.ModelDriven 接口,使用它的getModel()方法来通知Struts2要注入的属性类型,而且声明属性时必定要实例化,但不需get,set方法接口

相关文章
相关标签/搜索