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);
}
}