使用PageHelper插件实现分页功能

在我们使用mybatis进行数据库的访问时,分页的操作和不需要分页的操作往往需要两个方法完成,但是其实他们有大量的代码重复,那么有没有什么方案解决这个问题呢?答案就是使用分页插件。
分页插件的原理:PageHelper内部都是创建了分页page,调用分页的地方传入page,最后在mybatis中的拦截器中取得传入的page并利用反射重新拼接sql再执行。
下面我们看代码案例

1.工具类

package com.openlab.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static final ThreadLocal<SqlSession> SQLSESSION = new ThreadLocal<>();
    private static SqlSessionFactory factory ;
    static {
        String resource = "mybatis/mybatis-config.xml";
        try {
            InputStream is = Resources.getResourceAsStream(resource);
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private MybatisUtil(){

    }

    public static SqlSession getSqlSession(){
        SqlSession sqlSession = SQLSESSION.get();
        if (sqlSession == null){
            SQLSESSION.set(factory.openSession());
        }
        return SQLSESSION.get();
    }

    public static void close(){
        SqlSession sqlSession = SQLSESSION.get();
        if (sqlSession !=null ){
            sqlSession.close();
            SQLSESSION.set(null);
        }
    }
}

package com.openlab.utils;

import com.openlab.mapper.UserMapper;

public class PageUtil {
    private static int total ;
    static {
        total = MybatisUtil.getSqlSession().getMapper(UserMapper.class).queryAll().size();
    }

    private PageUtil(){

    }
    public static int getPageNum(int cur,int pageSize,String opt){
        switch (opt){
            case "first":
                return first(cur,pageSize,total);
            case "last":
                return last(cur,pageSize,total);
            case "before":
                return before(cur,pageSize,total);
                default:return next(cur,pageSize,total);
        }
    }

    private static int next(int cur, int pageSize, int total) {
        int last = total % pageSize == 0 ? total / pageSize : total /pageSize + 1;
        if (cur == last){
            return cur;
        }else {
            return cur + 1 ;
        }

    }

    private static int before(int cur, int pageSize, int total) {
        if (cur == 1){
            return 1;
        }else {
            return cur - 1;
        }
    }

    private static int last(int cur, int pageSize, int total) {
        return total % pageSize == 0 ? total / pageSize : total /pageSize + 1;
    }

    private static int first(int cur, int pageSize, int total) {
        return 1;
    }

    public static int getTotal() {
        return total;
    }
}

2.配置文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.openlab.limit</groupId>
  <artifactId>Limit</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Limit Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>


  </dependencies>

  <build>
    <finalName>Limit</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

<?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>
    <properties resource="database/jdbc.properties"></properties>
    <typeAliases>
        <package name="com.openlab.pojo"></package>
    </typeAliases>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
        </plugin>
    </plugins>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/openlab/mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>

3.DAO层

package com.openlab.mapper;

import com.openlab.pojo.User;

import java.util.List;

public interface UserMapper {

    public List<User> queryAll();
}

<?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.openlab.mapper.UserMapper">
    <select id="queryAll" resultType="User">
        SELECT
          id,userName,gender,birthday,phone,address
        FROM smbms_user
    </select>
</mapper>

4.service层

为了简便这里省去

5.控制层

package com.openlab.servlet;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.openlab.mapper.UserMapper;
import com.openlab.pojo.User;
import com.openlab.utils.MybatisUtil;
import com.openlab.utils.PageUtil;
import org.apache.ibatis.session.SqlSession;

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(value = "/info")
public class LimitServlet extends HttpServlet {
    private static final int PAGESIZE = 5;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        System.out.println("进入");
        Integer curPageNum = (Integer) request.getSession().getAttribute("curPageNum");
        System.out.println("传入得:"+curPageNum);
        if (curPageNum == null){
            curPageNum = 1 ;
            Integer total = PageUtil.getTotal() % PAGESIZE == 0 ? PageUtil.getTotal() / PAGESIZE :PageUtil.getTotal() / PAGESIZE+1;
            request.getSession().setAttribute("total",total);
        }else {
            String opt = request.getParameter("option");
            System.out.println(opt);
            curPageNum = PageUtil.getPageNum(curPageNum,PAGESIZE,opt);
            System.out.println("新的curPageNum"+curPageNum);
        }
        PageHelper.startPage(curPageNum,PAGESIZE);
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.queryAll();
        MybatisUtil.close();
        request.getSession().setAttribute("curPageNum",curPageNum);
        request.getSession().setAttribute("users",users);
        response.sendRedirect(request.getContextPath()+"/info.jsp");

    }
}

6.视图层

<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %><%--
  Created by IntelliJ IDEA.
  User: 上杉
  Date: 2020/8/10
  Time: 20:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>Title</title>
    <style type="text/css">
        .tb {
            margin: auto;
            margin-top: 0px;
            font-family: verdana,arial,sans-serif;
            font-size:16px;
            color:#333333;
            border-width: 1px;
            border-color: #666666;
            border-collapse: collapse;
        }

        .tb td {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
            background-color: #ffffff;
        }

        .tb tr {
            text-align: center;
        }
        a {
            text-decoration: none;
        }

    </style>
</head>
<body style="background-color: #333333">
    <table class="tb" style="text-align: center">
        <tr style="text-align: center">
            <th>ID</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>电话</th>
            <th>地址</th>
        </tr>
        <c:forEach var="user" items="${users}">
            <tr>
                <td>${user.id}</td>
                <td>${user.userName}</td>
                <td>
                    <c:if test="${user.gender==1}"></c:if>
                    <c:if test="${user.gender==2}"></c:if>
                </td>
                <td>
                    <fmt:formatDate value="${user.birthday}" type="date" dateStyle="default"></fmt:formatDate>
                </td>
                <td>${user.phone}</td>
                <td>${user.address}</td>
            </tr>
        </c:forEach>
        <tr style="text-align: center">
            <td colspan="6">
                总页数${total}&nbsp;
                <a href="${pageContext.request.contextPath}/info?option=<%="first"%>">首页</a>
                <a href="${pageContext.request.contextPath}/info?option=<%="before"%>">上一页</a>
                <a href="">${curPageNum}</a>
                <a href="${pageContext.request.contextPath}/info?option=<%="next"%>">下一页</a>
                <a href="${pageContext.request.contextPath}/info?option=<%="last"%>">尾页</a>
            </td>
        </tr>
    </table>
</body>
</html>


7.测试结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值