package wb.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 org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
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 CommonAction<T> extends ActionSupport implements ModelDriven<T> {
private T model;
public T getModel() {
return model;
}
public CommonAction() {
//获取父类类型
ParameterizedType superclass = (ParameterizedType)this.getClass().getGenericSuperclass();
//获取父类上面的泛型数组
Type[] types = superclass.getActualTypeArguments();
//获取泛型类型
Class<T> modelClass = (Class<T>)types[0];
//通过反射创建对象
try {
model = modelClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
private int page;
private int rows;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
/*
* 分页查询结果转json
*/
public void page2json(Page<T> page, String[] excludes){
Map<String, Object> map = new HashMap<>();
if (page != null) {
map.put("total", page.getTotalElements());
map.put("rows", page.getContent());
}
JsonConfig config = new JsonConfig();
config.setExcludes(excludes);
try {
String json = JSONObject.fromObject(map, config).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
ServletActionContext.getResponse().getWriter().print(json);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 查询的结果集转json
*/
public void list2json(List list,String[] excludes){
JsonConfig config = new JsonConfig();
config.setExcludes(excludes);
try {
String json = JSONArray.fromObject(list, config).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
ServletActionContext.getResponse().getWriter().print(json);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 查询的对象转json
*/
public void object2json(Object object, String[] excludes){
JsonConfig config = new JsonConfig();
config.setExcludes(excludes);
try {
String json = JSONArray.fromObject(object, config).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
ServletActionContext.getResponse().getWriter().print(json);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 分页查询
*/
public Pageable getPageable(){
Pageable pageable = new PageRequest(getPage() - 1, getRows());
return pageable;
}
}
struts的common类
最新推荐文章于 2021-03-31 00:07:21 发布