读书人

Struts2中action接收参数的三种方法及

发布时间: 2012-09-15 19:09:28 作者: rapoo

Struts2中action接收参数的三种方法及ModelDriven和Preparable接口结合JAVA反射机制的灵活用法
Struts2中Action接收参数的方法主要有以下三种:

1.使用Action的属性接收参数(最原始的方式):
a.定义:在Action类中定义属性,创建get和set方法;
b.接收:通过属性接收参数,如:userName;
c.发送:使用属性名传递参数,如:user1!add?userName=jim;
2.使用DomainModel接收参数:
a.定义:定义Model类,在Action中定义Model类的对象(不需要new),创建该对象的get和set方法;
b.接收:通过对象的属性接收参数,如:user.getUserName();
c.发送:使用对象的属性传递参数,如:user2!add?user.userName=mike;
3.使用ModelDriven接收参数(现在用的比较多的方式):
a.定义:Action实现ModelDriven泛型接口,定义Model类的对象(必须new),通过getModel方法返回该对象;
b.接收:通过对象的属性接收参数,如:user.getUserName();
c.发送:直接使用属性名传递参数,如:user2!add?userName=tom

在Struts2.3.4的文档里面有这样说明:
To use ModelDriven actions, make sure that the Model Driven Interceptor is applied to your action. This interceptor is part of the default interceptor stack defaultStack so it is applied to all actions by default.

Action class:



在Model Driven Interceptor里面这样说道:
To create a Model Driven action, implement the ModelDriven interface by adding a model property, or at least the accessor.

public Object getModel() ...

In the implementation of getModel, acquire an instance of a business object and return it.

On the page, you can address any JavaBean properties on the business object as if they were coded directly on the Action class. (The framework pushes the Model object onto the ValueStack.)

Many developers use Spring to acquire the business object. With the addition of a setModel method, the business logic can be injected automatically.

所以如果实现 ModelDriven 接口,那么必须至少构造一个getModel方法,并return一个实体对象。而且在struts.xml文件中需要配置名为modelDriven的拦截器Interceptor,如果没有指定拦截器栈,那么使用默认的defaultStack,这个拦截器栈里面已经引用了modelDriven的拦截器,所以默认下你的package包extends了struts-default那么就不用配置。
struts.xml:


下面这段代码可以充分体现ModelDriven和Preparable接口结合JAVA反射机制的灵活用法,大大方便节省了开发code时间,注意这里用的是paramsPrepareParamsStack拦截器栈,所以params拦截器会在Preparable接口的方法之前执行。

读书人网 >编程

热点推荐