Ajax分页 Spring MVC + Hibernate

前端之家收集整理的这篇文章主要介绍了Ajax分页 Spring MVC + Hibernate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

效果图:


1. 添加公共类、方法代码

1.分页类:Page.java

  1. package cn.com.aperfect.sso.base.dao;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class Page<T> {
  7. // 当前页数
  8. private int currentPage;
  9. // 记录偏移量
  10. private int offset;
  11. // 总页数
  12. private int totalsPage;
  13. // 每页显示记录条数
  14. private int pageSize;
  15. // 总记录条数
  16. private int totalsCount;
  17. // 查询返回结果
  18. private List<T> result = new ArrayList<T>();
  19. // 分页链接
  20. private String uri;
  21. public Page(){}
  22. public Page(int currentPage,int pageSize) {
  23. this.currentPage = currentPage;
  24. this.pageSize = pageSize;
  25. this.offset = (currentPage-1)*pageSize;
  26. }
  27.  
  28. public String getUri() {
  29. return uri;
  30. }
  31.  
  32. public void setUri(String uri) {
  33. this.uri = uri;
  34. }
  35.  
  36. public int getCurrentPage() {
  37. return currentPage;
  38. }
  39.  
  40. public void setCurrentPage(int currentPage) throws Exception {
  41. if (currentPage < 0) {
  42. currentPage = 0;
  43. }
  44. this.currentPage = currentPage;
  45. }
  46.  
  47. public int getTotalsPage() {
  48. try {
  49. if (totalsCount % pageSize == 0) {
  50. totalsPage = totalsCount / pageSize;
  51. } else {
  52. totalsPage = (totalsCount / pageSize) + 1;
  53. }
  54. } catch (Exception e) {
  55. throw new RuntimeException(e);
  56. }
  57. return totalsPage;
  58. }
  59.  
  60. public void setTotalsPage(int totalsPage) {
  61. if (totalsPage < 0) {
  62. totalsPage = 0;
  63. }
  64. this.totalsPage = totalsPage;
  65. }
  66.  
  67. public int getPageSize() {
  68. return pageSize;
  69. }
  70.  
  71. public void setPageSize(int pageSize) {
  72. if (pageSize <= 0) {
  73. pageSize = 20;
  74. }
  75. this.pageSize = pageSize;
  76. }
  77.  
  78. public int getTotalsCount() {
  79. return totalsCount;
  80. }
  81.  
  82. public void setTotalsCount(int totalsCount) {
  83. if (totalsCount < 0) {
  84. totalsCount = 0;
  85. }
  86. this.totalsCount = totalsCount;
  87. }
  88.  
  89. public List<T> getResult() {
  90. return result;
  91. }
  92.  
  93. public void setResult(List<T> result) {
  94. this.result = result;
  95. }
  96.  
  97. public int getOffset() {
  98. return offset;
  99. }
  100.  
  101. public void setOffset(int offset) {
  102. this.offset = offset;
  103. }
  104. }
2. 公共的DAO / DAOImpl

DAO

  1. /**
  2. * <b>function:</b> 传入查询语句和查询参数名key对应value,page指定currentPage和pageSize
  3. * @param queryHql 查询语句
  4. * @param paramMap 参数
  5. * @param page 当前页和每页几条数据
  6. * @throws Exception
  7. */
  8. public Page<T> showPage(String queryHql,String countHql,Map<String,Object> paramMap,int currentPage,int pageSize) throws Exception;
IMPL
  1. public Page<T> showPage(String queryHql,int pageSize) throws Exception {
  2. Page<T> page = new Page<T>(currentPage,pageSize);
  3. try {
  4. int dataCount = queryForInt(countHql,paramMap);
  5. page.setResult(queryForList(queryHql,paramMap,page.getOffset(),pageSize));
  6. page.setTotalsCount(dataCount);
  7. } catch (Exception e) {
  8. throw new RuntimeException(e);
  9. }
  10. return page;
  11. }
  12. private final int queryForInt(String queryIntHQL,Object> paramMap){
  13. Query query = this.getSession().createQuery(queryIntHQL);
  14. setQueryParameterValues(paramMap,query);
  15. int result = Integer.parseInt(query.uniqueResult().toString());
  16. return result;
  17. }
  18. private final List<T> queryForList(String queryHql,int offset,int pageSize){
  19. Query query = this.getSession().createQuery(queryHql);
  20. setQueryParameterValues(paramMap,query);
  21. if (offset>=0) {
  22. query.setFirstResult(offset);
  23. }
  24. if (pageSize>0) {
  25. query.setMaxResults(pageSize);
  26. }
  27. return query.list();
  28. }
  29. private final void setQueryParameterValues(Map<String,Query query){
  30. if (CollectionUtil.isEmpty(paramMap)) return ;
  31. for (Entry<String,Object> entry : paramMap.entrySet()) {
  32. query.setParameter(entry.getKey(),entry.getValue());
  33. }
  34. }

2. 代码(Controller)

Controller分别有两个请求的方法,请求的地址是不一样的。

一个用于初始化页面时候请求,另外一个是分页时候Ajax用的请求。

(第一个请求返回的是整个页面,ajax请求返回的只是一个抽取出来的*table.jsp,所以要两个请求,只是返回的jsp不一样。只是使用了js将原来页面的table替换掉新的而已)

方法主体是一样的。

  1. @Controller
  2. @RequestMapping("/srmUser")
  3. public class SrmUserController {
  4. @Resource
  5. private ISrmUserService srmUserService;
  6.  
  7. private void doSearch(HttpServletRequest request,HttpServletResponse response) throws Exception{
  8. int currentPage = ServletRequestUtils.getIntParameter(request,"currentPage",1);
  9. int pageSize = ServletRequestUtils.getIntParameter(request,"pageSize",10);
  10. //前台数据传到后台查询
  11. String enterpriseName = ServletRequestUtils.getStringParameter(request,"enterpriseName");
  12. String vendorName = ServletRequestUtils.getStringParameter(request,"vendorName");
  13. String userName = ServletRequestUtils.getStringParameter(request,"userName");
  14. String status = ServletRequestUtils.getStringParameter(request,"status");
  15. String fromCreateDate = ServletRequestUtils.getStringParameter(request,"fromCreateDate");
  16. String toCreateDate = ServletRequestUtils.getStringParameter(request,"toCreateDate");
  17. Page<SrmUser> page = srmUserService.searchUserList(enterpriseName,vendorName,userName,status,fromCreateDate,toCreateDate,currentPage,pageSize);
  18. //数据返回前台
  19. request.setAttribute("enterpriseName",enterpriseName);
  20. request.setAttribute("vendorName",vendorName);
  21. request.setAttribute("userName",userName);
  22. request.setAttribute("status",status);
  23. request.setAttribute("fromCreateDate",fromCreateDate);
  24. request.setAttribute("toCreateDate",toCreateDate);
  25. request.setAttribute("toCreateDate",toCreateDate);
  26. request.setAttribute("userListDto",page.getResult());
  27. request.setAttribute("pageEntity",page);
  28. }
  29. @RequestMapping("/searchUser")
  30. public String searchUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
  31. doSearch(request,response);
  32. return "/srm_management/srmUser_manage";
  33. }
  34. @RequestMapping("/ajaxSearchUser")
  35. public String ajaxSearchUser(HttpServletRequest request,response);
  36. return "/srm_management/inc/srmUser_table";
  37. }
  38.  
  39. }

具体查询代码

  1. @Override
  2. public Page<SrmUser> getUserList(String enterpriseName,String vendorName,String userName,String status,String fromCreateDate,String toCreateDate,int pageSize) throws Exception {
  3.  
  4. Page<SrmUser> page = null;
  5. StringBuffer sbHQL = new StringBuffer();
  6. StringBuffer countHQL = new StringBuffer();
  7. Map<String,Object> paramMap = new HashMap<String,Object>();
  8. try {
  9. sbHQL.append("from SrmUser u where 1=1 ");
  10. countHQL.append("select count(*) from SrmUser u where 1=1 ");
  11. if (!StringUtil.isEmpty(enterpriseName)) {
  12. sbHQL.append(" and u.enterprise.enterpriseName like :enterpriseName ");
  13. countHQL.append(" and u.enterprise.enterpriseName like :enterpriseName ");
  14. paramMap.put("enterpriseName","%"+enterpriseName+"%");
  15. }
  16. if (!StringUtil.isEmpty(vendorName)) {
  17. sbHQL.append(" and u.userId in (");
  18. sbHQL.append("select userId from SrmUserVendor s where s.vendorId in (");
  19. sbHQL.append("select vendorId from SrmVendor v where v.vendorName like :vendorName)) ");
  20. countHQL.append(" and u.userId in (");
  21. countHQL.append("select userId from SrmUserVendor s where s.vendorId in (");
  22. countHQL.append("select vendorId from SrmVendor v where v.vendorName like :vendorName)) ");
  23. paramMap.put("vendorName","%"+vendorName+"%");
  24. }
  25. if (!StringUtil.isEmpty(userName)) {
  26. sbHQL.append(" and u.userName like :userName ");
  27. countHQL.append(" and u.userName like :userName ");
  28. paramMap.put("userName","%"+userName+"%");
  29. }
  30. if (!StringUtil.isEmpty(status)) {
  31. sbHQL.append(" and u.status = :status ");
  32. countHQL.append(" and u.status = :status ");
  33. paramMap.put("status",Integer.parseInt(status));
  34. }
  35. if (!StringUtil.isEmpty(fromCreateDate)) {
  36. sbHQL.append(" and u.createDate >= :fromCreateDate ");
  37. countHQL.append(" and u.createDate >= :fromCreateDate ");
  38. paramMap.put("fromCreateDate",fromCreateDate);
  39. }
  40. if (!StringUtil.isEmpty(toCreateDate)) {
  41. sbHQL.append(" and u.createDate < :toCreateDate ");
  42. countHQL.append(" and u.createDate < :toCreateDate ");
  43. //toCreateDate 要加上一天
  44. java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(toCreateDate);
  45. Calendar calendar = new GregorianCalendar();
  46. calendar.setTime(date);
  47. calendar.add(Calendar.DATE,1);
  48. date= calendar.getTime();
  49. paramMap.put("toCreateDate",date);
  50. }
  51. sbHQL.append(" order by u.userId asc ");
  52. page = showPage(sbHQL.toString(),countHQL.toString(),pageSize);

3. 前台JSP等

Jsp要分成两部分,一部分是整体的第一次请求的时候的整体页面

另一部分是*_table.jsp 就是要分页的那个table。

只要在整体里面抽出*_table.jsp页面就可以,然后整体页面里面引用*_table.jsp页面


将要ajax请求的table替换成下面,这个<span>是用于后面Ajax请求成功的时候要替换的标识

  1. <span id="resourceSpan">
  2. <jsp:include page="inc/srmUser_table.jsp" />
  3. </span>

后台将整个*_table.jsp 页面返回到前台的<span>里面。

*.table.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>
  2. <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
  3. <table class="details">
  4. <tr class="noticClsSrm">
  5. <td>企业</td>
  6. <td>用户名</td>
  7. <td>创建者</td>
  8. <td>创建时间</td>
  9. <!-- <td>最后编辑者</td>
  10. <td>最后更新时间</td> -->
  11. <td>状态</td>
  12. </tr>
  13. <c:forEach var="userDto" items="${requestScope.userListDto}">
  14. <tr>
  15. <td>${userDto.enterprise.enterpriseName }</td>
  16. <td>${userDto.userName }</td>
  17. <td>${userDto.creatorName }</td>
  18. <td>
  19. <fmt:formatDate value="${userDto.createDate }" pattern="yyyy-MM-dd"/>
  20. </td>
  21. <%-- <td>${userDto.editorName }</td>
  22. <td>
  23. <fmt:formatDate value="${userDto.updateDate }" pattern="yyyy-MM-dd"/>
  24. </td> --%>
  25. <td>
  26. <c:if test="${userDto.status==0 }">启动</c:if>
  27. <c:if test="${userDto.status==1 }">冻结</c:if>
  28. <c:if test="${userDto.status==2 }">删除</c:if>
  29. </td>
  30. </tr>
  31. </c:forEach>
  32. </table>
  33. <jsp:include page="../../commons/page_ajax.jsp"/>
  34. <script type="text/javascript">
  35. //分页跳转
  36. var totalsPage = '${pageEntity.totalsPage}';
  37. if (totalsPage == '') totalsPage = 1;
  38. function ajaxGotoPage(currentPage) {
  39. if (currentPage == null || currentPage == "") return;
  40. if (isNaN(currentPage)) return;
  41. if (currentPage < 1) currentPage = 1;
  42. else if ((currentPage > totalsPage) || (currentPage==${pageEntity.currentPage})) return;
  43. var resourceSpan = $("#resourceSpan");
  44. resourceSpan.html("<br/><img src='${pageContext.request.contextPath }/commons/images/blue-loading.gif'/>");
  45. $.ajax({
  46. url:'${pageContext.request.contextPath }/v/srmUser/ajaxSearchUser',type:'post',data:{
  47. currentPage:currentPage,enterpriseName:$("#enterpriseName").val(),vendorName:$("#vendorName").val(),userName:$("#userName").val(),status:$("#status").val(),fromCreateDate:$("#fromCreateDate").val(),toCreateDate:$("#toCreateDate").val()
  48. },dataType:'text',timeout:60000,error: function(e) {
  49. alert(e);
  50. },success: function(result){
  51. resourceSpan.html(result);
  52. }
  53. });
  54. }
  55. function gotoPageByInput(){
  56. var currentPage=document.getElementById('goInput').value;
  57. ajaxGotoPage(parseInt(currentPage));
  58. }
  59. </script>

page_ajax.jsp
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  2. <style>
  3. <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;}
  4. <span style="white-space:pre"> </span>div.yk-pager {text-align: right;padding:3px 0px;margin: 3px 0px;color:#666666;}
  5. <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;}
  6. <span style="white-space:pre"> </span>div.yk-pager a:hover {padding:2px 5px;margin-right: 2px;background-color:#ccdaf3;border: #a0a0a0 1px solid;}
  7. <span style="white-space:pre"> </span>div.yk-pager a:active {padding:2px 5px;margin-right: 2px;background-color:#ccdaf3;border: #a0a0a0 1px solid;}
  8. <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}
  9. <span style="white-space:pre"> </span>div.yk-pager span.disabled {color: #ccc;margin-right: 2px;border:1px solid #f3f3f3;padding:2px 5px;}
  10. <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;}
  11. <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;}
  12. </style>
  13. <div class="yk-pager">
  14. <a href="javascript:ajaxGotoPage(1);">首页</a>
  15. <a href="javascript:ajaxGotoPage(${pageEntity.currentPage-1});">上一页</a>
  16. <a href="javascript:ajaxGotoPage(${pageEntity.currentPage+1});"> 下一页</a>
  17. <a href="javascript:ajaxGotoPage(${pageEntity.totalsPage });"> 末页</a>
  18. 总${pageEntity.totalsCount }条,第${pageEntity.currentPage}/${pageEntity.totalsPage }页,到第<input size=2 id="goInput" value=''/>页,<input type="button" class="goButton" onclick="gotoPageByInput();"/>
  19. </div>
ok.gif

猜你在找的Ajax相关文章