使用ajax和pageHelper实现简单的分页

直接上代码:

 

数据库:

 

 

 

使用mybatis框架操作数据库:

这里我使用逆反工程建立的:

Goods实体类:

package cn.kgc.pojo;

import java.util.Date;

public class Goods {
    private Integer goodsId;

    private String goodsName;

    private Date startTime;

    public Integer getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName == null ? null : goodsName.trim();
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
}
pojo

 

GoodsMapper接口:

 

 

这里只要这个查询方法就够了.

 

GoodsMapper.xml:

GoodsMapper.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="cn.kgc.dao.GoodsMapper">
  <resultMap id="BaseResultMap" type="cn.kgc.pojo.Goods">
    <id column="goods_id" jdbcType="INTEGER" property="goodsId" />
    <result column="goods_name" jdbcType="VARCHAR" property="goodsName" />
    <result column="start_time" jdbcType="TIMESTAMP" property="startTime" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from goods
    where goods_id = #{goodsId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="cn.kgc.pojo.Goods">
    insert into goods (goods_id, goods_name, start_time
      )
    values (#{goodsId,jdbcType=INTEGER}, #{goodsName,jdbcType=VARCHAR}, #{startTime,jdbcType=TIMESTAMP}
      )
  </insert>
  <update id="updateByPrimaryKey" parameterType="cn.kgc.pojo.Goods">
    update goods
    set goods_name = #{goodsName,jdbcType=VARCHAR},
      start_time = #{startTime,jdbcType=TIMESTAMP}
    where goods_id = #{goodsId,jdbcType=INTEGER}
  </update>
  
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select goods_id, goods_name, start_time
    from goods
    where goods_id = #{goodsId,jdbcType=INTEGER}
  </select>
  <select id="selectAll" resultMap="BaseResultMap">
    select goods_id, goods_name, start_time
    from goods
  </select>
  
</mapper>

 

 

Service层:

GoodsServiceDao接口:

package cn.kgc.service;

import cn.kgc.pojo.Goods;

import java.util.List;

public interface GoodsServiceDao {


    List<Goods> getStus(Integer pageIndex, Integer pageSize);


}
GoodsServiceDao

GoodsServiceDaoImpl:

package cn.kgc.service;

import cn.kgc.dao.GoodsMapper;
import cn.kgc.pojo.Goods;
import cn.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class GoodsServiceDaoImpl implements GoodsServiceDao{

    SqlSession sqlSession = MyBatisUtil.createSqlSession();

    GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);

    @Override
    public List<Goods> getStus(Integer pageIndex, Integer pageSize) {

        /**
         * 1.进行分页处理
         * 2.显示第pageIndex页的pageSize条数据
         * 3.在查询之前执行PageHelper的startPage方法之后紧跟要进行分页的查询语句
         */

        PageHelper.startPage(pageIndex,pageSize);
//        List<Goods> lists = studentMapper.getStus(student);

        List<Goods> list = mapper.selectAll();

//        MyBatisUtil.closeSqlSession(sqlSession);

        return list;

    }
}
GoodsServiceDaoImpl

 

Servlet层:

package cn.kgc.servlet;

import cn.kgc.pojo.Goods;
import cn.kgc.service.GoodsServiceDao;
import cn.kgc.service.GoodsServiceDaoImpl;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/BackServlet")
public class BackServlet extends HttpServlet {
    private static final GoodsServiceDao goodsServiceDao = new GoodsServiceDaoImpl();
//    static int pageIndex = NextServlet.pageIndex;
    Gson gson = new Gson();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("是否进入请求");

        resp.setContentType("text/html;charset=UTF-8");
        System.out.println("Back:"+Servlet.pageIndex);


        if(Servlet.pageIndex>1) {
            Servlet.pageIndex -= 1;
        }
//        System.out.println("pageIndex:"+pageIndex);
//
        List<Goods> goods = goodsServiceDao.getStus(Servlet.pageIndex, Servlet.pageSize);
//
        PageInfo<Goods> pageInfo = new PageInfo<Goods>(goods);
//

////
        if(Servlet.pageIndex>=1){
            resp.getWriter().println(gson.toJson(goods));
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
BackServlet

 

package cn.kgc.servlet;

import cn.kgc.pojo.Goods;
import cn.kgc.service.GoodsServiceDao;
import cn.kgc.service.GoodsServiceDaoImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/NextServlet")
public class NextServlet extends HttpServlet {
    private static final GoodsServiceDao goodsServiceDao = new GoodsServiceDaoImpl();

    Gson gson = new Gson();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("是否进入请求");

        resp.setContentType("text/html;charset=UTF-8");
        if(Servlet.pageIndex<4) {
            Servlet.pageIndex += 1;
        }
        List<Goods> goods = goodsServiceDao.getStus(Servlet.pageIndex, Servlet.pageSize);


        PageInfo<Goods> pageInfo = new PageInfo<Goods>(goods);
        long total = pageInfo.getTotal();

        System.out.println(total);
        if(Servlet.pageIndex<=total/5+1){
            resp.getWriter().println(gson.toJson(goods));
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
NextServlet 

 

package cn.kgc.servlet;


import cn.kgc.pojo.Goods;
import cn.kgc.service.GoodsServiceDao;
import cn.kgc.service.GoodsServiceDaoImpl;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/Servlet")
public class Servlet extends HttpServlet {

    static int pageIndex = 1;
    static int  pageSize = 5;
    private static final GoodsServiceDao goodsServiceDao = new GoodsServiceDaoImpl();

    Gson gson = new Gson();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("是否进入请求");

        resp.setContentType("text/html;charset=UTF-8");



//        String pageIndex1 = req.getParameter("pageIndex");
//        int i = Integer.parseInt(pageIndex1);

        List<Goods> goods = goodsServiceDao.getStus(pageIndex, pageSize);

        resp.getWriter().println(gson.toJson(goods));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
Servlet

 

 

 

WEB层:

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2019/10/25
  Time: 12:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery.min.js"></script>
    <script>
        $(function () {


            $("#back").click(function () {

                $.ajax(
                    {
                        "url": "BackServlet",//要提交的url路径
                        "type": "get",     // 发送的请求方法
                        "data": "back=" + "1",  // 要发送到服务器的数据
                        "dataType": "json",   // 指定返回的数据格式
                        "success": callBack,    //响应成功后要执行的代码
                        "error": function () {  // 请求失败后要执行的代码
                            alert("用户名验证时出现错误,请稍后再试或与管理员联系!");
                        }
                    });
            }),
            $("#next").click(function () {

                $.ajax(
                    {
                        "url": "NextServlet",//要提交的url路径
                        "type": "get",     // 发送的请求方法
                        "data": "next=" + "1",  // 要发送到服务器的数据
                        "dataType": "json",   // 指定返回的数据格式
                        "success": callBack,    //响应成功后要执行的代码
                        "error": function () {  // 请求失败后要执行的代码
                            alert("用户名验证时出现错误,请稍后再试或与管理员联系!");
                        }
                    });
            }),

            $.ajax(
                {
                    "url": "Servlet",//要提交的url路径
                    "type": "get",     // 发送的请求方法
                    "data": "pageIndex=" + "1",  // 要发送到服务器的数据
                    "dataType": "json",   // 指定返回的数据格式
                    "success": callBack,    //响应成功后要执行的代码
                    "error": function () {  // 请求失败后要执行的代码
                        alert("用户名验证时出现错误,请稍后再试或与管理员联系!");
                    }
                });
            function callBack(data) {
                // 添加新数据之前先删除之前的数据
                // $("#tabl tr:not(:first)").remove();
                var trs = "<tr><td>商品ID</td><td>商品名称</td><td>开始时间</td></tr>";
                $.each(data,function (i,val) {

                    trs += "<tr><td>"+data[i].goodsId+"</td><td>"+data[i].goodsName+"</td><td>"+data[i].startTime+"</td></tr>";
                })

                $("#b").html(trs);
            }
})

    </script>

</head>
<body>

<%--<button id="bto">按钮</button>--%>
<table id="b" border="1" width="300px"height="100px"align="center">

<%--    <button id="back">上一页</button>--%>
    <button id="back">back</button>
    <button id="next">next</button>

</table>


</body>
</html>
index.jsp

 

 

测试结果:

 

 

 

 

 注意:

网址:

1、需要到网址下jar包

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

 2、再配置一下mybatis.xml

网址里面有:

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    加载database.properties-->
    <properties resource="database.properties"></properties>
<!--定义别名,之后该包的类就不用写完整的路径名,可以直接写类名-->
<!--    <typeAliases>-->
<!--        <package name="com.pojo"/>-->
<!--    </typeAliases>-->

    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
            <property name="param1" value="value1"/>
        </plugin>
    </plugins>
<!--    定义数据源-->
    <environments default="development">
        <environment id="development">
<!--            配置事务管理,采用jdbc的事务管理-->
            <transactionManager type="JDBC"></transactionManager>
<!--            POOLED:mybatis自带的数据源,JNDI:基于Tomcat的数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
<!--映射(接口)文件-->
    <mappers>

        <mapper resource="EduCourseMapper.xml"/>
    </mappers>
</configuration>
mybatis.xml

 

 

 

该方法可能存在问题,若有建议,请给出评论,我会多加修改。谢谢!!

 

posted @ 2019-10-25 17:36  AxeBurner  阅读(1382)  评论(0编辑  收藏  举报