使用struts2时,同一系统内会有许多重复代码,常用的继承ActionSupport、实现ModelDriven接口、向值栈中写入数据等,每个action中都写一遍耗费时间和精力,这时候我们可以统一抽取一下,代码复用,提高编码效率,下面就简单的介绍一下Baction的抽取
[Java] 纯文本查看 复制代码 package cn.itcast.base.action;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Controller
@Scope("prototype")
@ParentPackage("struts-default")
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
// 具体的对象,对象的类型,是由具体模块的action确定
private T model = null; //dept
// 具体的对象的类型
private Class<T> clazz = null;
// 构造函数确定clazz的类型
@SuppressWarnings("unchecked")
public BaseAction() {
System.out.println("this 表示当前运行类" + this);// DeptAction
System.out.println("当然运行类的父类: " + this.getClass().getSuperclass()); //BaseAction
System.out.println("当前运行类的泛型父类:" + this.getClass().getGenericSuperclass());
// 获取当前运行类的泛型父类:BaseAction<Dept>, 就是参数化类型
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
// 调用方法,获取参数化类型的实际类型的定义
Type[] types = pt.getActualTypeArguments();
// 获取实际类型
clazz = (Class<T>) types[0];
// 创建对象
try {
model = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// ModelDriven 拦截器会调用下面的方法,封装请求数据,放入值栈
@Override
public T getModel() {
return model;
}
// 封装datagrid提交的分页参数
private int page;
private int rows;
public int getPage() {
return page;
}
public int getRows() {
return rows;
}
public void setPage(int page) {
this.page = page;
}
public void setRows(int rows) {
this.rows = rows;
}
public void set(String key,Object value){
ActionContext.getContext().getValueStack().set(key, value);
}
public void push(Object obj){
ActionContext.getContext().getValueStack().push(obj);
}
}
注意,这个时候我们的spring注解扫描是不能扫描抽取出来的BaseAction的。
写完这个后,我们就可以通过继承BaseAction直接来直接使用相应的方法啦。
|