qGrid4.2实践-2-集成Spring MVC
记录一下以作参考
SpringMVC的安装可以参考SpringMVC3.0+rest小例子
jsp页面
其中几个关键的属性
url :查询请求地址
datatype :返回值类型,这里使用JSON进行传递
prmNames :传递给后台的属性定义,本例中定义search:"search",如果不这么定义的话,后台接收到的将会是_search。
jsonReader :页面接收后台数据属性定义,具体参考API解释
Controller类
@RequestMapping(value="/list") @ResponseBody public DataResponselist(@RequestParam(defaultValue="1",value="page") String page, @RequestParam(defaultValue="20",value="rows") String rows, @RequestParam("sidx") String sidx, @RequestParam("sord") String sord, @RequestParam("_search") boolean search, @RequestParam(required=false,value="searchField") String searchField, @RequestParam(required=false,value="searchOper") String searchOper, @RequestParam(required=false,value="searchString") String searchString, @RequestParam(required=false,value="filters") String filters ){ try { DataRequest request = new DataRequest(); request.setPage(StringUtils.isEmpty(page) ? 1 : Integer.valueOf(page)); request.setRows(StringUtils.isEmpty(rows) ? 20 : Integer.valueOf(rows)); request.setSidx(sidx); request.setSord(sord); request.setSearch(search); request.setSearchField(searchField); request.setSearchOper(searchOper); request.setSearchString(searchString); return customSearchUtil.search(request, User.class); } catch (Exception e) { e.printStackTrace(); } return null; }
为接收前台数据,特定义了DataRequest类,其中的属性跟页面传递过来的属性一一对应
public class DataRequest implements java.io.Serializable { private static final long serialVersionUID = 1L; //当前页码 private int page; //页面可显示行数 private int rows; //用于排序的列名 private String sidx; //排序的方式desc/asc private String sord; //是否是搜索请求 private boolean search; //已经发送的请求的次数 private String nd;}
给前台发送数据也定义了相应的DataResponse类
public class DataResponse{ //需要显示的数据集 private List rows; //每页显示数量 private int page; //数据总数 private int records; //可显示的页数 private int total; //自定义数据 private Map userdata;}
Controller类接收数据后即传给后台service类处理并返回DataResponse对象给页面
处理方法如下
public DataResponsesearch(DataRequest request, Class cls) { DataResponse response = new DataResponse (); int count;//总记录数 int limit = request.getRows() <= 0 ? 20 : request.getRows();//每页显示数量 int totalPages;//总页数 int page = request.getPage() <= 0 ? 1 : request.getPage();//当前显示页码 List list; Set set = initSearchCondition(request.isSearch(), request.getSearchField(), request.getSearchOper(), request.getSearchString()); count = customDao.count(cls, set); totalPages = count / limit; if (count % limit != 0) { totalPages++; } int currPage = Math.min(totalPages, page); int start = currPage * limit - limit; start = start < 0 ? 0 : start; list = customDao.list(cls, set, start, limit); response.setRecords(count); response.setTotal(totalPages); response.setPage(currPage); response.setRows(list); return response; }