Java代碼
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的鍵取得參數值時,取得是一個數組對象,即同名參數的值的集合。
方法三:通過ActionContext取得HttpServletRequest對象,然後使用request.getParameter("參數名")得到參數值。