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

public abstract class BaseAction extends ActionSupport implements
ModelDriven {


// 模型驱动
protected T model;


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


// 构造器 完成model实例化
public BaseAction() {
// 构造子类Action对象 ,获取继承父类型的泛型
// XXXAction extends BaseAction
// BaseAction
Type genericSuperclass = this.getClass().getGenericSuperclass();
// 获取类型第一个泛型参数
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Class modelClass = (Class) 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 pageData) {
Map result = new HashMap();
result.put("total", pageData.getTotalElements());
result.put("rows", pageData.getContent());


ActionContext.getContext().getValueStack().push(result);
}
}

你可能感兴趣的:(代码重构)