方法1.ajax+json这种前后端交互的模式
(1)首先效果展示页面展示 (2)这里给出我页面布局代码:
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12 c1" id="ecommerceRecentOrder" style="margin-top:0"> <div class="widget widget-shadow table-row" style="margin-bottom: 0"> <div style="font-size: 20px;padding-left: 20px;padding-top: 10px"> <div>预报船期数据</div> </div> <div class="widget-content bg-white table-responsive"> <table class="table table-bordered table-striped table-condensed" style="margin-bottom: 10px"> <thead> <tr style="font-size: 14px"> <th>船名</th> <th>航次</th> <th>IMO号</th> <th>预报抵港时间</th> <th>货物</th> <th>吨数</th> </tr> </thead> <tbody id="con"> //遍历list </tbody> </table> </div> <!-- 提示分页信息行 --> <div class="row"> <!-- 分页文字信息 :拿到控制器处理请求时封装在pageInfo里面的分页信息--> <div class="col-sm-5" id="page_info_area"> <div class="dataTables_info" id="dataTableExample_info" style="margin-left: 20px"> </div> </div> <div class="col-sm-7"> <!-- 分页码 --> <div class="dataTables_paginate paging_simple_numbers" id="dataTableExample_paginate" style="line-height: 32.4px"> <!-- 1.pageContext.request.contextPath表示当前项目路径,采用的是绝对路径表达方式。一般为http:localhost:8080/项目名 。 2.首页,末页的逻辑:pn=1访问第一次,pn=${pageInfo.pages}访问最后一页 --> <!-- 如果还有前页就访问当前页码-1的页面, --> <!--遍历所有导航页码,如果遍历的页码页当前页码相等就高亮显示,如果相等就普通显示 --> <!-- 如果还有后页就访问当前页码+1的页面, --> </div> </div> </div> </div> </div>(3)js部分:
后台从数据库获取时间用需要格式化下:
//获得毫秒数 再转化为需要时间格式。形如:yyyy-MM-dd var format = function(time, format) { var t = new Date(time); var tf = function(i) { return (i < 10 ? '0': '') + i }; return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) { switch (a) { case 'yyyy': return tf(t.getFullYear()); break; case 'MM': return tf(t.getMonth() + 1); break; case 'mm': return tf(t.getMinutes()); break; case 'dd': return tf(t.getDate()); break; case 'HH': return tf(t.getHours()); break; case 'ss': return tf(t.getSeconds()); break; } }); } $(function () { toSomePage(1); }); 每次调用此函数都发送一次请求,变量pn是默认开始页面 function toSomePage(pn) { $.ajax({ url: ctx + "/SspShipVoyage/getSspShipTotalList", type: "post", data: "pn=" + pn, success: function (result) { build_user_table(result);//构建用户表格 build_pagination_info(result);//构建分页信息 build_pagination_nav(result)//构建分页导航 } }) }: /** 创建一张用户表显示读取的数据 */ function build_user_table(result) { //先清空表格,不然会直接回追加到上次查询结果上 $("con").empty(); //获取服务器返回的json数据 var users = result.pageInfo.list; con = ""; //$.each()是jquery的遍历方法 $.each(users, function (index, item) { // var date = new Date(parseInt(item.eta)); // date.format("yyyy-MM-dd"); // var ww= HdUtil.Date.prototype.format(item.eta); var formatDate= format(item.eta, 'yyyy-MM-dd HH:mm:ss'); con += "<tr><td>" + item.cShipNam + "</td>"; con += "<td>" + item.iVoyage + "</td>"; con += "<td>" + item.shipMmsi + "</td>"; con += "<td>" +formatDate + "</td>"; con += "<td>" + item.cargoName + "</td>"; con += "<td>" + item.ton + "</td></tr>"; }) $("#con").html(con); } /** 创建分页信息 */ function build_pagination_info(result) { $("#dataTableExample_info").empty(); //得到服务器返回的jason数据里的分页信息,然后拼接 var pageNum = result.pageInfo.pageNum; var pageSize = result.pageInfo.pages; var total = result.pageInfo.total; //"当前"+pageNum+"页,共"+pages+"页,总"+total+"条记录" // $("#dataTableExample_info").append("第"+ pageNum+ "至"+ pageSize+" 项,共"+ total+" 项"); $("#dataTableExample_info").append("当前" + pageNum + "页,共" + pageSize + "页,总" + total + "条记录") } /** 创建分页导航条: 根据bootstrap文档里的分页说明,使用jquery创建元素。 */ function build_pagination_nav(result) { $("#dataTableExample_paginate").empty(); //首页 var fristPageLi = $("<li></li>").append($("<a></a>").attr("href", "javacript:void(0);").append("首页")); //前一页 var prePageLi = $("<li></li>").append($("<a></a>").attr("href", "javacript:void(0);").append($("<span></span>").append("«"))); //如果没有前一页,就让按钮不能被点击,否则绑定点击事件,重新发送ajax请求,访问相应页面 if (result.pageInfo.hasPreviousPage == false) { fristPageLi.addClass("disable"); prePageLi.addClass("disable"); } else { fristPageLi.click(function () { toSomePage(1); }); prePageLi.click(function () { toSomePage(result.pageInfo.pageNum - 1); }); } var ul = $("<ul class=\"pagination\" style=\"float: right\"></ul>").addClass("pagination").append(fristPageLi).append(prePageLi); $.each(result.pageInfo.navigatepageNums, function (index, element) { var numLi = $("<li></li>").append($("<a></a>").attr("href", "javacript:void(0);").append(element)); //如果遍历的页码等于当前页面,就高亮显示,然后添加点击事件,如果有点击,就重新发送ajax请求,访问当前页面(pn=element) if (result.pageInfo.pageNum == element) { numLi.addClass("active"); } numLi.click(function () { toSomePage(element); }) ul.append(numLi); }) //下一页 var nextPageLi = $("<li></li>").append($("<a></a>").attr("href", "javacript:void(0);").append($("<span></span>").append("»"))); //末页 var lastPageLi = $("<li></li>").append($("<a></a>").attr("href", "javacript:void(0);").append("末页")); //如果没有后一页,就让按钮不能被点击,否则绑定点击事件,重新发送ajax请求,访问相应页面 if (result.pageInfo.hasNextPage == false) { nextPageLi.addClass("disable"); lastPageLi.addClass("disable"); } else { nextPageLi.click(function () { toSomePage(result.pageInfo.pageNum + 1); }); lastPageLi.click(function () { toSomePage(result.pageInfo.pages); }); } ul.append(nextPageLi).append(lastPageLi); $("<nav></nav>").append(ul).appendTo("#dataTableExample_paginate"); }(4)controller里返回的是json数据
public Map<String, Object> getSspShipTotalList(@RequestParam(value="pn",defaultValue="1") Integer pn) { //startPage是PageHelper的静态方法,参数1:默认开始页面,参数2:每页显示数据的条数 PageHelper.startPage(pn, 5); List<String> list = sspShipVoyageMapper.getSspShipTotalList(); //使用PageInfo包装查询页面,封装了详细的分页信息.第二个参数表示连续显示的页数 PageInfo page = new PageInfo(list,5); Map<String, Object> map = new HashMap<String, Object>(); map.put("pageInfo", page); return map; }这是ajax请求的json数据: 总结:主要利用pageHelper的插件把List集合封装一下,SQL还是正常写.(前端用js控制)
方法2:分页
(1)效果图 (2)新增Page这个类专门为分页提供必要信息
public class Page { private int start; //开始页数 private int count; //每页显示个数 private int total; //总个数 private String param; //参数 private static final int defaultCount = 5; //默认每页显示5条 public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public Page (){ count = defaultCount; } public Page(int start, int count) { this(); this.start = start; this.count = count; } public boolean isHasPreviouse(){ if(start==0) return false; return true; } public boolean isHasNext(){ if(start==getLast()) return false; return true; } public int getTotalPage(){ int totalPage; // 假设总数是50,是能够被5整除的,那么就有10页 if (0 == total % count) totalPage = total /count; // 假设总数是51,不能够被5整除的,那么就有11页 else totalPage = total / count + 1; if(0==totalPage) totalPage = 1; return totalPage; } public int getLast(){ int last; // 假设总数是50,是能够被5整除的,那么最后一页的开始就是45 if (0 == total % count) last = total - count; // 假设总数是51,不能够被5整除的,那么最后一页的开始就是50 else last = total - total % count; last = last<0?0:last; return last; } @Override public String toString() { return "Page [start=" + start + ", count=" + count + ", total=" + total + ", getStart()=" + getStart() + ", getCount()=" + getCount() + ", isHasPreviouse()=" + isHasPreviouse() + ", isHasNext()=" + isHasNext() + ", getTotalPage()=" + getTotalPage() + ", getLast()=" + getLast() + "]"; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getParam() { return param; } public void setParam(String param) { this.param = param; } }(3)提供带分页的查询语句和获取总数的sql语句
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.how2java.tmall.mapper.CategoryMapper"> <select id="list" resultType="Category"> select * from category order by id desc <if test="start!=null and count!=null"> limit #{start},#{count} </if> </select> <select id="total" resultType="int"> select count(*) from category </select> </mapper>(4)提供一个支持分页的查询方法list(Page page)和获取总数的方法total
public interface CategoryMapper { public List<Category> list(Page page); public int total(); } //提供一个支持分页的查询方法list(Page page)和获取总数的方法total public interface CategoryService{ int total(); List<Category> list(Page page); } // @Service public class CategoryServiceImpl implements CategoryService { @Autowired CategoryMapper categoryMapper; @Override public List<Category> list(Page page) { return categoryMapper.list(page); } @Override public int total() { return categoryMapper.total(); } }(5)控制类
@Controller @RequestMapping("") public class CategoryController { @Autowired CategoryService categoryService; @RequestMapping("admin_category_list") public String list(Model model,Page page){ List<Category> cs= categoryService.list(page); int total = categoryService.total(); page.setTotal(total); model.addAttribute("cs", cs); model.addAttribute("page", page); return "admin/listCategory"; } }(6)页面布局代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%> <script> $(function(){ $("ul.pagination li.disabled a").click(function(){ return false; }); }); </script> <nav> <ul class="pagination"> <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>> <a href="?start=0${page.param}" aria-label="Previous" > <span aria-hidden="true">«</span> </a> </li> <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>> <a href="?start=${page.start-page.count}${page.param}" aria-label="Previous" > <span aria-hidden="true">‹</span> </a> </li> <c:forEach begin="0" end="${page.totalPage-1}" varStatus="status"> <li <c:if test="${status.index*page.count==page.start}">class="disabled"</c:if>> <a href="?start=${status.index*page.count}${page.param}" <c:if test="${status.index*page.count==page.start}">class="current"</c:if> >${status.count}</a> </li> </c:forEach> <li <c:if test="${!page.hasNext}">class="disabled"</c:if>> <a href="?start=${page.start+page.count}${page.param}" aria-label="Next"> <span aria-hidden="true">›</span> </a> </li> <li <c:if test="${!page.hasNext}">class="disabled"</c:if>> <a href="?start=${page.last}${page.param}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav>