- 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