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方法接口