java编程使用EasyUI进行分页查询前后端代码编写
使用EasyUI显示分页信息特别简单,但是想要把前后台功能完完整整的做出来对于新手而言还是有一定的难度,前两天让一个新同事做这个功能,他在编码过程中遇到各种小问题,我在这里也总结一下,以便帮助以后的同学使用。
显示的分页功能页面如下图(图1):
一、前端代码在查询的时候使用分页属性即可:
$('#grid').datagrid({
url:'dep_getListByPage.action',
columns:[[
{field:"uuid",title:"部门编号",width:100},
{field:"name",title:"部门名称",width:100},
{field:"tele",title:"部门电话",width:100}
]],
singleSelect:true,
pagination:true
});
但是添加属性后只能页面只是能显示分页条,功能并不能真正起作用,还需要后台接收分页信息,使用浏览器可以查看浏览器向后台传递的参数如下(图2):
二、后台代码如下:(接口和配置均已省略)
1.(控制层---action层)接收前台的参数(使用属性驱动),进行查询代码如下:
private IDepBiz depBiz;
public void setDepBiz(IDepBiz depBiz) {
this.depBiz = depBiz;
}
private int page;
private int rows;
private Dep dep1;
public Dep getDep1() {
return dep1;
}
public void setDep1(Dep dep1) {
this.dep1 = dep1;
}
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;
}
* 按条件查询部门(分页)
*/
public void getListByPage(){
int firstResult = (page-1)*rows;
List<Dep> depList = depBiz.getListByPage(dep1,firstResult,rows);//调用业务层进行分页查寻
Long count = depBiz.getCount(dep1);//调用业务层查询库表中总记录数(原因是后台返回到前台的结果如图3)
//把查询出来的对象封装到Map集合中(原因是后台返回到前台的结果如图3)
Map map = new HashMap<>();
map.put("total",count);
map.put("rows", depList);
String jsonString = JSON.toJSONString(map);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
try {
response.getWriter().print(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
2.业务层调用持久层,代码如下:
private IDepDao depDao;
public void setDepDao(IDepDao depDao) {
this.depDao = depDao;
}
/**
* 按条件查询部门(分页)
*/
public List<Dep> getListByPage(Dep dep1,int firstResult,int maxResults){
return depDao.getListByPage(dep1, dep2, param, firstResult, maxResults);
}
/**
* 获取查询结果的总记录数
*/
public Long getCount(Dep dep1,Dep dep2,Object param){
return depDao.getCount(dep1);
}
3.持久层的代码如下:
/**
* 按条件查询部门(分页)
*/
public List<Dep> getListByPage(Dep dep1,int firstResult,int maxResults){
DetachedCriteria depClass = DetachedCriteria.forClass(Dep.class);//使用离线查询
//返回所有部门的集合
return (List<Dep>) getHibernateTemplate().findByCriteria(depClass, firstResult, maxResults);
}
/**
* 获取查询结果的总记录数
*/
public Long getCount(Dep dep1,Dep dep2,Object param){
DetachedCriteria depClass = DetachedCriteria.forClass(Dep.class);
//使用投影查询获取方法可以获取到总记录数
depClass.setProjection(Projections.rowCount());
List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(depClass);//相当于select count(*) from
return list.get(0);//返回查询结果的总记录数
}