1. 程式人生 > >分頁工具類 BaseAction

分頁工具類 BaseAction

ont 實體 protected imp span sta ext ota xxx

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

分頁工具類 BaseAction