模板模式抽取Struts2模型驱动及分页重复代码,简化开发

public abstract class BaseAction extends ActionSupport implements
ModelDriven<T> {


// 模型驱动
protected T model;


@Override
public T getModel() {
return model;
}


// 构造器 完成model实例化
public BaseAction() {
// 构造子类Action对象 ,获取继承父类型的泛型
// XXXAction extends BaseAction<XXX>
// BaseAction<XXX>
Type genericSuperclass = this.getClass().getGenericSuperclass();
// 获取类型第一个泛型参数
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Class<T> modelClass = (Class<T>) parameterizedType
.getActualTypeArguments()[0];
try {
model = modelClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
//此处可以写入错误日志,并打印到控制台
}
}

//分页代码提取
// 接收分页查询参数
protected int page;
protected int rows;


public void setPage(int page) {
this.page = page;
}


public void setRows(int rows) {
this.rows = rows;
}


// 将分页查询结果数据,压入值栈的方法
protected void pushPageDataToValueStack(Page<T> pageData) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("total", pageData.getTotalElements());
result.put("rows", pageData.getContent());


ActionContext.getContext().getValueStack().push(result);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章