package com.lyric.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;
/**
* 公共Action
* @author admin
*
* @param <T>
*/
public class CommonAction<T> extends ActionSupport implements ModelDriven<T> {
protected Integer page;
protected Integer rows;
public void setPage(Integer page) {
this.page = page;
}
public void setRows(Integer rows) {
this.rows = rows;
}
private T model;
@Override
public T getModel() {
return model;
}
public CommonAction(){
ParameterizedType genericSuperclass = (ParameterizedType)this.getClass().getGenericSuperclass();
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
Class<T> entityClass = (Class<T>)actualTypeArguments[0];
try {
model = entityClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 公共方法:将page对象转json 通过输出流写回页面
* @param page
* @param excludes
* @throws IOException
*/
public void page2Json(Page<T> page,String[] excludes) throws IOException{
long totalElements = page.getTotalElements();
List<T> content = page.getContent();
Map<String,Object> map = new HashMap<>();
map.put("total", totalElements);
map.put("rows", content);
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().print(json);
}
/**
* list集合转json 数据 通过输出流返回浏览器
* @param list
* @throws IOException
*/
public void list2Json(List<?> list,String[] excludes) throws IOException{
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().print(json);
}
}