- public class TestAction 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;
- }
- }
總結:
數組
Struts2中Action接收參數的方法主要有如下三種:
1.使用Action的屬性接收參數:
a.定義:在Action類中定義屬性,建立get和set方法;
b.接收:經過屬性接收參數,如:userName;
c.發送:使用屬性名傳遞參數,如:user1!add?userName=Magci;
2.使用DomainModel接收參數:
a.定義:定義Model類,在Action中定義Model類的對象(不須要new),建立該對象的get和set方法;
b.接收:經過對象的屬性接收參數,如:user.getUserName();
c.發送:使用對象的屬性傳遞參數,如:user2!add?user.userName=MGC;
3.使用ModelDriven接收參數:
a.定義:Action實現ModelDriven泛型接口,定義Model類的對象(必須new),經過getModel方法返回該對象;
b.接收:經過對象的屬性接收參數,如:user.getUserName();
c.發送:直接使用屬性名傳遞參數,如:user2!add?userName=MGC;ide