ajax 如何实现分页功能

2017-11-08 19:13:51来源:CSDN作者:niceLiuSir人点击

分享

这里用ajax简单的实现一下分页功能,作为一个例子

ajax实现分页,首先需要工具类,Page.java,如下:

package com.feelingsys.bean;/** * Page * @author LIU * @version 1.0 2017-09-28 */public class Page {    /**     * 总记录数     */    private int totalCount;    /**     * 每页显示的记录数     */    private int currCount;    /**     * 总页数     */    private int sumPage;    /**     * 当前页码     */    private int currPage;    /**     * 当前页起始坐标     */    private int start;    /**     * 总记录数     *TODO     *LIU     * @return int     *上午11:23:12     */    public int getTotalCount() {        return totalCount;    }    /**     * 总记录数     *TODO     *LIU     * @param totalCount     *上午11:23:34     */    public void setTotalCount(int totalCount) {        this.totalCount = totalCount;    }    /**     * 每页显示的记录数     *TODO     *LIU     * @return int     *上午11:23:40     */    public int getCurrCount() {        return currCount;    }    /**     * 每页显示的记录数     *TODO     *LIU     * @param currCount     *上午11:24:00     */    public void setCurrCount(int currCount) {        this.currCount = currCount;    }    /**     * 获取总页数(必须先设置总记录数和每页显示数量)     *TODO     *LIU     * @return int     *上午11:24:11     */    public int getSumPage() {        if(this.getTotalCount() % this.getCurrCount() == 0){ // 设置表的总页数            return (this.getTotalCount() / this.getCurrCount());        }        return (this.getTotalCount() / this.getCurrCount() + 1);    }    /**     * 总页数     *TODO     *LIU     * @param sumPage     *上午11:24:30     */    public void setSumPage(int sumPage) {        this.sumPage = sumPage;    }    /**     * 当前页码     *TODO     *LIU     * @return int     *上午11:24:38     */    public int getCurrPage() {        return currPage;    }    /**     * 当前页码     *TODO     *LIU     * @param currPage     *上午11:24:54     */    public void setCurrPage(int currPage) {        this.currPage = currPage;    }    /**     * 当前页码起始下标(Mysql数据库需要)     *TODO     *LIU     * @return int     *上午11:24:38     */    public int getStart() {        return (this.getCurrPage()-1) * this.getCurrCount();    }    /**     * 当前页码起始下标标(Mysql数据库需要)     *TODO     *LIU     * @param currPage     *上午11:24:54     */    public void setStart(int start) {        this.start = start;    }}

ajax实现分页,需要两个jsp文件,currList.jsp 和 showAll.jsp文件。
showAll.jsp如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <script type="text/javascript" src="js/jquery-1.8.3.js"></script>    <script type="text/javascript" src="js/showAll.js"></script>  </head>  <body>    <div id="all">        <p>心情足迹</p>        <a href="add.jsp">记录心情</a>        <div id="fun">        <table border="1" cellspacing="0">            <tr>                <th>心情日记</th>                <th>日志分类</th>                <th>编写日期</th>                <th>操作</th>            </tr>            <c:forEach var="f" items="${feelingList }">                <tr>                    <td>${f.ftitle }</td>                    <c:choose>                      <c:when test="${f.ftype==1 }"><td>踩脚印</td></c:when>                      <c:when test="${f.ftype==2 }"><td>有感而发</td></c:when>                      <c:when test="${f.ftype==3 }"><td>杂七杂八</td></c:when>                    </c:choose>                    <td>${f.fdate }</td>                    <td><a href="ShowOneServlet?fid=${f.fid }">查看</a></td>                </tr>            </c:forEach>        </table>        <p class="ppage">        当前页数[<span id="currPage">${page.currPage }</span>/<span id="sumPage">${page.sumPage }</span>]&nbsp;&nbsp;&nbsp;&nbsp;        <span class="pages">首页</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="pages">上一页</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="pages">下一页</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="pages">尾页</span>        </p>        </div>    </div>  </body></html>

currList.jsp如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <script type="text/javascript" src="js/jquery-1.8.3.js"></script>    <script type="text/javascript" src="js/showAll.js"></script>  </head>  <body>    <div id="all">        <table border="1" cellspacing="0">            <tr>                <th>心情日记</th>                <th>日志分类</th>                <th>编写日期</th>                <th>操作</th>            </tr>            <c:forEach var="f" items="${feelingList }">                <tr>                    <td>${f.ftitle }</td>                    <c:choose>                      <c:when test="${f.ftype==1 }"><td>踩脚印</td></c:when>                      <c:when test="${f.ftype==2 }"><td>有感而发</td></c:when>                      <c:when test="${f.ftype==3 }"><td>杂七杂八</td></c:when>                    </c:choose>                    <td>${f.fdate }</td>                    <td><a href="ShowOneServlet?fid=${f.fid }">查看</a></td>                </tr>            </c:forEach>        </table>        <p class="ppage">        当前页数[<span id="currPage">${page.currPage }</span>/<span id="sumPage">${page.sumPage }</span>]&nbsp;&nbsp;&nbsp;&nbsp;        <span class="pages">首页</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="pages">上一页</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="pages">下一页</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="pages">尾页</span>        </p>    </div>  </body></html>

show.js的代码如下:

$(function(){    // 点击页面处理    $(".pages").unbind("click").bind("click", function(){        var op = $(this).html();        var curr = $("#currPage").html();        if(op == "首页"){            curr = 1;        }else if(op == "尾页"){            curr = $("#sumPage").html();        }else if(op == "上一页"){            if($("#currPage").html() == 1){                curr = 1;            }else{                curr = $("#currPage").html() - 1;            }        }else if(op == "下一页"){            if($("#currPage").html() == $("#sumPage").html()){                curr == $("#sumPage").html();            }else{                curr = parseInt($("#currPage").html()) + 1;            }        }        // 分页显示请求        $.ajax({            url:"ShowAllServlet",            type:"post",            data:{"curr":curr},            dataType:"html",            async:true,            success:function(result){                $("#fun").html(result);            }           });    });});

控制器ShowAllServlet.java的doPost方法如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {    response.setContentType("text/html;charset=utf-8");    request.setCharacterEncoding("utf-8");    response.setCharacterEncoding("utf-8");    FeelingService feelingService = new FeelingServiceImpl();    Page page = new Page();    page.setCurrCount(4);    page.setTotalCount(feelingService.getAllCounts());    if(request.getParameter("curr") == null){        page.setCurrPage(1);        List<Feeling> feelingList = feelingService.showAll(page);        request.setAttribute("feelingList", feelingList);        request.setAttribute("page", page);        request.getRequestDispatcher("showAll.jsp").forward(request, response);    }else{        page.setCurrPage(Integer.parseInt(request.getParameter("curr")));        List<Feeling> feelingList = feelingService.showAll(page);        request.setAttribute("feelingList", feelingList);        request.setAttribute("page", page);        request.getRequestDispatcher("currList.jsp").forward(request, response);    }       }

数据映射文件 FeelingMapper.xml:

<?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.feelingsys.mapper.FeelingMapper">  <resultMap id="FeelingResultMap" type="com.feelingsys.bean.Feeling">    <id property="fid" column="fid" />    <result property="ftitle" column="ftitle"/>    <result property="fcontent" column="fcontent"/>    <result property="fdate" column="fdate"/>    <result property="ftype" column="ftype"/>  </resultMap> <select id="getAllCounts" resultType="int">    select count(fid) from feeling  </select>  <select id="showAll" parameterType="com.feelingsys.bean.Page" resultMap="FeelingResultMap">    select fid,ftitle,fcontent,fdate,ftype from feeling order by fdate desc limit #{start},#{currCount}  </select></mapper>

数据访问实现类 FeelingMapperImpl.java 查询方法如下:

/**     * 分页显示全部心情日志     *TODO     *LIU     * @param page     * @return     *上午10:26:18     */    @Override    public List<Feeling> showAll(Page page) {        // TODO Auto-generated method stub        List<Feeling> feelingList = new ArrayList<Feeling>();        SqlSession session = null;        try {            session = getSession(path);            feelingList = session.selectList("com.feelingsys.mapper.FeelingMapper.showAll", page);        } catch (Exception e) {            e.printStackTrace();        }finally{            session.close();        }        return feelingList;    }    /**     * 获取所有记录数     *TODO     *LIU     * @return     *上午10:30:35     */    @Override    public int getAllCounts() {        // TODO Auto-generated method stub        SqlSession session = null;        int result = 0;        try {            session = getSession(path);            result = session.selectOne("com.feelingsys.mapper.FeelingMapper.getAllCounts");        } catch (Exception e) {            e.printStackTrace();        }finally{            session.close();        }        return result;    }

本例是使用单独的 mybatis 实现的数据库连接,mybatis.xml 和web.xml 文件如何配置不在讨论范围之内。

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台