package com.xxxxxxx.bos.web.action.common;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import org.springframework.data.domain.Page;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
protected T model;
/**
* 相关的术语:
* BaseAction<Area> 参数化类型
* <>中内容:实际类型参数
*/
//子类对象创建,父类无参构造执行
//目的:获取实际类型参数
public BaseAction() {
//1、获取当前运行的class
Class clzz = this.getClass(); //子类Action的Class:AreaAction
System.err.println(clzz);
//获取父类class
//Type getGenericSuperclass()
//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
Type type = clzz.getGenericSuperclass();
//2、获取参数化类型
ParameterizedType pt = (ParameterizedType) type;
System.err.println(pt);
//Type[] getActualTypeArguments()
//返回表示此类型实际类型参数的 Type 对象的数组。
Type[] types = pt.getActualTypeArguments(); //[Area]
//3、获取实际类型参数
Class clzzzzz = (Class) types[0]; //Area 的class
try {
model = (T) clzzzzz.newInstance();
System.out.println(model);
} catch (Exception e) {
e.printStackTrace();
}
}
public T getModel() {
return model;
}
//属性驱动接收datagrid分页组件提交参数
protected int page; //当前页
protected int rows;//每页显示记录数
public void setPage(int page) {
this.page = page;
}
public void setRows(int rows) {
this.rows = rows;
}
/**
* @Description: 将Page对象转为json字符串,向浏览器输出
*/
public void java2Json(Page<T> page, String[] excludes){
try {
Map<String, Object> map = new HashMap<>();
map.put("total", page.getTotalElements());
map.put("rows", page.getContent());
//将fixedares集合属性排除掉,不转json
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
String json = JSONObject.fromObject(map, jsonConfig).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description: 将List集合转为json字符串,向浏览器输出
*/
public void java2Json(List list, String[] excludes){
try {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
String json = JSONArray.fromObject(list, jsonConfig).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}