Ajax分页 Spring MVC + Hibernate
效果图:
1. 添加公共类、方法、代码
1. 分页类:Page.java
package cn.com.aperfect.sso.base.dao; import java.util.ArrayList; import java.util.List; public class Page<T> { // 当前页数 private int currentPage; // 记录偏移量 private int offset; // 总页数 private int totalsPage; // 每页显示记录条数 private int pageSize; // 总记录条数 private int totalsCount; // 查询返回结果 private List<T> result = new ArrayList<T>(); // 分页链接 private String uri; public Page(){} public Page(int currentPage, int pageSize) { this.currentPage = currentPage; this.pageSize = pageSize; this.offset = (currentPage-1)*pageSize; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) throws Exception { if (currentPage < 0) { currentPage = 0; } this.currentPage = currentPage; } public int getTotalsPage() { try { if (totalsCount % pageSize == 0) { totalsPage = totalsCount / pageSize; } else { totalsPage = (totalsCount / pageSize) + 1; } } catch (Exception e) { throw new RuntimeException(e); } return totalsPage; } public void setTotalsPage(int totalsPage) { if (totalsPage < 0) { totalsPage = 0; } this.totalsPage = totalsPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if (pageSize <= 0) { pageSize = 20; } this.pageSize = pageSize; } public int getTotalsCount() { return totalsCount; } public void setTotalsCount(int totalsCount) { if (totalsCount < 0) { totalsCount = 0; } this.totalsCount = totalsCount; } public List<T> getResult() { return result; } public void setResult(List<T> result) { this.result = result; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } }
2. 公共的DAO / DAOImpl
DAO
/** * <b>function:</b> 传入查询语句和查询参数名key对应value,page指定currentPage和pageSize * @param queryHql 查询语句 * @param paramMap 参数 * @param page 当前页和每页几条数据 * @throws Exception */ public Page<T> showPage(String queryHql,String countHql, Map<String, Object> paramMap,int currentPage, int pageSize) throws Exception;
IMPL
public Page<T> showPage(String queryHql, String countHql, Map<String, Object> paramMap, int currentPage, int pageSize) throws Exception { Page<T> page = new Page<T>(currentPage, pageSize); try { int dataCount = queryForInt(countHql, paramMap); page.setResult(queryForList(queryHql, paramMap, page.getOffset(),pageSize)); page.setTotalsCount(dataCount); } catch (Exception e) { throw new RuntimeException(e); } return page; } private final int queryForInt(String queryIntHQL,Map<String, Object> paramMap){ Query query = this.getSession().createQuery(queryIntHQL); setQueryParameterValues(paramMap, query); int result = Integer.parseInt(query.uniqueResult().toString()); return result; } private final List<T> queryForList(String queryHql,Map<String, Object> paramMap, int offset,int pageSize){ Query query = this.getSession().createQuery(queryHql); setQueryParameterValues(paramMap, query); if (offset>=0) { query.setFirstResult(offset); } if (pageSize>0) { query.setMaxResults(pageSize); } return query.list(); } private final void setQueryParameterValues(Map<String, Object> paramMap,Query query){ if (CollectionUtil.isEmpty(paramMap)) return ; for (Entry<String, Object> entry : paramMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } }
2. 代码(Controller)
Controller分别有两个请求的方法,请求的地址是不一样的。
一个用于初始化页面时候请求,另外一个是分页时候Ajax用的请求。
(第一个请求返回的是整个页面,ajax请求返回的只是一个抽取出来的*table.jsp,所以要两个请求,只是返回的jsp不一样。只是使用了js将原来页面的table替换掉新的而已)
方法主体是一样的。
@Controller @RequestMapping("/srmUser") public class SrmUserController { @Resource private ISrmUserService srmUserService; private void doSearch(HttpServletRequest request, HttpServletResponse response) throws Exception{ int currentPage = ServletRequestUtils.getIntParameter(request, "currentPage", 1); int pageSize = ServletRequestUtils.getIntParameter(request, "pageSize", 10); //前台数据传到后台查询 String enterpriseName = ServletRequestUtils.getStringParameter(request, "enterpriseName"); String vendorName = ServletRequestUtils.getStringParameter(request, "vendorName"); String userName = ServletRequestUtils.getStringParameter(request, "userName"); String status = ServletRequestUtils.getStringParameter(request, "status"); String fromCreateDate = ServletRequestUtils.getStringParameter(request, "fromCreateDate"); String toCreateDate = ServletRequestUtils.getStringParameter(request, "toCreateDate"); Page<SrmUser> page = srmUserService.searchUserList(enterpriseName,vendorName,userName,status,fromCreateDate,toCreateDate, currentPage, pageSize); //数据返回前台 request.setAttribute("enterpriseName", enterpriseName); request.setAttribute("vendorName", vendorName); request.setAttribute("userName", userName); request.setAttribute("status", status); request.setAttribute("fromCreateDate", fromCreateDate); request.setAttribute("toCreateDate", toCreateDate); request.setAttribute("toCreateDate", toCreateDate); request.setAttribute("userListDto", page.getResult()); request.setAttribute("pageEntity", page); } @RequestMapping("/searchUser") public String searchUser(HttpServletRequest request, HttpServletResponse response) throws Exception { doSearch(request, response); return "/srm_management/srmUser_manage"; } @RequestMapping("/ajaxSearchUser") public String ajaxSearchUser(HttpServletRequest request, HttpServletResponse response) throws Exception { doSearch(request, response); return "/srm_management/inc/srmUser_table"; } }
具体查询代码
@Override public Page<SrmUser> getUserList(String enterpriseName, String vendorName, String userName, String status, String fromCreateDate, String toCreateDate, int currentPage, int pageSize) throws Exception { Page<SrmUser> page = null; StringBuffer sbHQL = new StringBuffer(); StringBuffer countHQL = new StringBuffer(); Map<String, Object> paramMap = new HashMap<String, Object>(); try { sbHQL.append("from SrmUser u where 1=1 "); countHQL.append("select count(*) from SrmUser u where 1=1 "); if (!StringUtil.isEmpty(enterpriseName)) { sbHQL.append(" and u.enterprise.enterpriseName like :enterpriseName "); countHQL.append(" and u.enterprise.enterpriseName like :enterpriseName "); paramMap.put("enterpriseName", "%"+enterpriseName+"%"); } if (!StringUtil.isEmpty(vendorName)) { sbHQL.append(" and u.userId in ("); sbHQL.append("select userId from SrmUserVendor s where s.vendorId in ("); sbHQL.append("select vendorId from SrmVendor v where v.vendorName like :vendorName)) "); countHQL.append(" and u.userId in ("); countHQL.append("select userId from SrmUserVendor s where s.vendorId in ("); countHQL.append("select vendorId from SrmVendor v where v.vendorName like :vendorName)) "); paramMap.put("vendorName", "%"+vendorName+"%"); } if (!StringUtil.isEmpty(userName)) { sbHQL.append(" and u.userName like :userName "); countHQL.append(" and u.userName like :userName "); paramMap.put("userName", "%"+userName+"%"); } if (!StringUtil.isEmpty(status)) { sbHQL.append(" and u.status = :status "); countHQL.append(" and u.status = :status "); paramMap.put("status", Integer.parseInt(status)); } if (!StringUtil.isEmpty(fromCreateDate)) { sbHQL.append(" and u.createDate >= :fromCreateDate "); countHQL.append(" and u.createDate >= :fromCreateDate "); paramMap.put("fromCreateDate", fromCreateDate); } if (!StringUtil.isEmpty(toCreateDate)) { sbHQL.append(" and u.createDate < :toCreateDate "); countHQL.append(" and u.createDate < :toCreateDate "); //toCreateDate 要加上一天 java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(toCreateDate); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.DATE,1); date= calendar.getTime(); paramMap.put("toCreateDate", date); } sbHQL.append(" order by u.userId asc "); page = showPage(sbHQL.toString(), countHQL.toString(), paramMap, currentPage, pageSize);
3. 前台JSP等
Jsp要分成两部分,一部分是整体的第一次请求的时候的整体页面。
另一部分是*_table.jsp 就是要分页的那个table。
只要在整体里面抽出*_table.jsp页面就可以,然后整体页面里面引用*_table.jsp页面。
将要ajax请求的table替换成下面,这个<span>是用于后面Ajax请求成功的时候要替换的标识
<span id="resourceSpan"> <jsp:include page="inc/srmUser_table.jsp" /> </span>
后台将整个*_table.jsp 页面返回到前台的<span>里面。
*.table.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> <table class="details"> <tr class="noticClsSrm"> <td>企业</td> <td>用户名</td> <td>创建者</td> <td>创建时间</td> <!-- <td>最后编辑者</td> <td>最后更新时间</td> --> <td>状态</td> </tr> <c:forEach var="userDto" items="${requestScope.userListDto}"> <tr> <td>${userDto.enterprise.enterpriseName }</td> <td>${userDto.userName }</td> <td>${userDto.creatorName }</td> <td> <fmt:formatDate value="${userDto.createDate }" pattern="yyyy-MM-dd"/> </td> <%-- <td>${userDto.editorName }</td> <td> <fmt:formatDate value="${userDto.updateDate }" pattern="yyyy-MM-dd"/> </td> --%> <td> <c:if test="${userDto.status==0 }">启动</c:if> <c:if test="${userDto.status==1 }">冻结</c:if> <c:if test="${userDto.status==2 }">删除</c:if> </td> </tr> </c:forEach> </table> <jsp:include page="../../commons/page_ajax.jsp"/> <script type="text/javascript"> //分页跳转 var totalsPage = '${pageEntity.totalsPage}'; if (totalsPage == '') totalsPage = 1; function ajaxGotoPage(currentPage) { if (currentPage == null || currentPage == "") return; if (isNaN(currentPage)) return; if (currentPage < 1) currentPage = 1; else if ((currentPage > totalsPage) || (currentPage==${pageEntity.currentPage})) return; var resourceSpan = $("#resourceSpan"); resourceSpan.html("<br/><img src='${pageContext.request.contextPath }/commons/images/blue-loading.gif'/>"); $.ajax({ url:'${pageContext.request.contextPath }/v/srmUser/ajaxSearchUser', type:'post', data:{ currentPage:currentPage, enterpriseName:$("#enterpriseName").val(), vendorName:$("#vendorName").val(), userName:$("#userName").val(), status:$("#status").val(), fromCreateDate:$("#fromCreateDate").val(), toCreateDate:$("#toCreateDate").val() }, dataType:'text', timeout:60000, error: function(e) { alert(e); }, success: function(result){ resourceSpan.html(result); } }); } function gotoPageByInput(){ var currentPage=document.getElementById('goInput').value; ajaxGotoPage(parseInt(currentPage)); } </script>
page_ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <style> <span style="white-space:pre"> </span>.goSearchButton{background:url(<c:url value='/resources/images/ok.gif' />);border:0 none;height:19px;margin:0 0 0 5px;text-indent:-999px;width:37px;} <span style="white-space:pre"> </span>div.yk-pager {text-align: right;padding:3px 0px;margin: 3px 0px;color:#666666;} <span style="white-space:pre"> </span>div.yk-pager a{color: #036CB4;margin-right: 2px;padding:2px 5px;text-decoration: none;border:1px solid #929196;} <span style="white-space:pre"> </span>div.yk-pager a:hover {padding:2px 5px;margin-right: 2px;background-color:#ccdaf3;border: #a0a0a0 1px solid;} <span style="white-space:pre"> </span>div.yk-pager a:active {padding:2px 5px;margin-right: 2px;background-color:#ccdaf3;border: #a0a0a0 1px solid;} <span style="white-space:pre"> </span>div.yk-pager span.current {font-weight: bold;color: #FFFFFF;padding:2px 5px;margin-right: 2px;background-color:#6390cb;border:1px solid #3d68a0} <span style="white-space:pre"> </span>div.yk-pager span.disabled {color: #ccc;margin-right: 2px;border:1px solid #f3f3f3;padding:2px 5px;} <span style="white-space:pre"> </span>div.yk-pager .goInput{border:1px solid #99bbe8;color:#000000;font-family:Tahoma,SimSun,Arial;height:18px;margin:0 5px;text-align:center;vertical-align:top;width:30px;} <span style="white-space:pre"> </span>div.yk-pager .goButton{background:url(skin/ok.gif);border:0 none;height:19px;margin:0 0 0 5px;text-indent:-999px;width:37px;} </style> <div class="yk-pager"> <a href="javascript:ajaxGotoPage(1);">首页</a> <a href="javascript:ajaxGotoPage(${pageEntity.currentPage-1});"> ◄上一页</a> <a href="javascript:ajaxGotoPage(${pageEntity.currentPage+1});"> 下一页► </a> <a href="javascript:ajaxGotoPage(${pageEntity.totalsPage });"> 末页</a> 总${pageEntity.totalsCount }条,第${pageEntity.currentPage}/${pageEntity.totalsPage }页,到第<input size=2 id="goInput" value=''/>页, <input type="button" class="goButton" onclick="gotoPageByInput();"/> </div>
ok.gif
Ajax分页 Spring MVC + Hibernate的更多相关文章
- IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践
原文:IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践 最近把编辑器换成IntelliJ IDEA,主要是Ecli ...
- Spring + Spring MVC + Hibernate
Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自 ...
- IntelliJIDEA Getting+Started+with+Spring+MVC,+Hibernate+and+JSON
https://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC,+Hibernate+and ...
- Spring + Spring MVC + Hibernate项目开发集成(注解)
在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下. ...
- Java 本地开发环境搭建(框架采用 Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6)
项目搭建采用技术栈为:Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6 搭建环境文档目录结构说明: 使用Intellj Idea 搭建项目过 ...
- spring mvc: Hibernate验证器(字段不能为空,在1-150自己)
spring mvc: Hibernate验证器(字段不能为空,在1-150自己) 准备: 下载Hibernate Validator库 - Hibernate Validator.解压缩hibern ...
- Spring MVC第一课:用IDEA构建一个基于Spring MVC, Hibernate, My SQL的Maven项目
作为一个Spring MVC新手最基本的功夫就是学会如何使用开发工具创建一个完整的Spring MVC项目,本文站在一个新手的角度讲述如何一步一步创建一个基于Spring MVC, Hibernate ...
- Spring MVC Hibernate MySQL Integration(集成) CRUD Example Tutorial【摘】
Spring MVC Hibernate MySQL Integration(集成) CRUD Example Tutorial We learned how to integrate Spring ...
- Spring mvc+hibernate+freemarker(实战)
Spring mvc+hibernate+freemarker(实战) 博客分类: Spring Spring mvchibernatefreemarkerwebjava 今天我为大家做了一个 sp ...
随机推荐
- Python小代码_5_二维矩阵转置
使用列表推导式实现二维矩阵转置 matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(matrix) matrix_t = [[ro ...
- Tarjan笔记1
Tarjan 2822 爱在心中 ** 时间限制: 1 s ** 空间限制: 128000 KB ** 题目等级 : 钻石 Diamond 题解 题目描述 Description"每个人都拥 ...
- ACM 数塔
在讲述DP算法的时候,一个经典的例子就是数塔问题,它是这样描述的: 有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少? 已经告诉你了,这是个DP的题 ...
- PHP MySQL Where 子句
WHERE 子句 WHERE 子句用于提取满足指定标准的的记录. 语法 SELECT column_name(s) FROM table_name WHERE column_name operator ...
- Docker如何获取镜像
可以使用 docker pull 命令来从仓库获取所需要的镜像. 下面的例子将从 Docker Hub 仓库下载一个 Ubuntu 12.04 操作系统的镜像. $ sudo docker pull ...
- Android自定义View(CustomCalendar-定制日历控件)
转载请标明出处: http://blog.csdn.net/xmxkf/article/details/54020386 本文出自:[openXu的博客] 目录: 1分析 2自定义属性 3onMeas ...
- MySQL连接及基本信息查看命令小结
前言 学习PHP就不得不提MySQL,虽然有phpMyadmin这样的工具可以图形化操作数据库,但我还是想借学习PHP的机会使用下命令行方式操作数据库.以下就是我的学习小结,包括命令行连接数据库,查看 ...
- Linux 中交换空间 (swap)应该分多大才好?
前一段时间,我们机房中一台Linux服务器运行缓慢,系统服务出现间歇性停止响应,让我过去处理一下这一问题,登录到服务器之后,发现此服务器的物理内存是16G,而最初装机的时候,系统管理人员却只分配了4G ...
- Linux 高性能服务器编程——I/O复用的高级应用
高级应用一:非阻塞connect connect系统调用的man手册中有如下的一段内容: EINPROGRESS The socket is non-blocking and the connecti ...
- 1.物理系统PhysicsWorld,RayCast
1 3.0物理系统PhysicsWorld T07PhysicsWorld.h #ifndef __T07PhysicsWorld_H__ #define __T07PhysicsWorld_H ...