Mybatis拦截器实现分页

Stella981
• 阅读 742

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

import org.apache.ibatis.executor.resultset.ResultSetHandler; import org.apache.ibatis.plugin.*;

import java.sql.Statement; import java.util.Properties;

/** * 插件签名,告诉mybaits单线插件用来拦截哪个插件对象的哪个方法 */ @Intercepts({ @Signature(type= ResultSetHandler.class, method = "handleResultSets", args = Statement.class) }) public class MyFirstInterceptor1 implements Interceptor { //拦截目标对象的目标方法的 public Object intercept(Invocation invocation) throws Throwable {

    System.out.println("拦截的目标对象:"+invocation.getTarget());
    System.out.println("拦截的目标方法:"+invocation.getMethod());
    System.out.println("拦截的目标参数:"+invocation.getArgs());
    Object object=invocation.proceed();

    return object;
}
//包装目标对象 为目标对象创建代理对象的
public Object plugin(Object o) {
    System.out.println("将要包装的目标对象"+o);
    return Plugin.wrap(o,this);
}

public void setProperties(Properties properties) {
    System.out.println("插件配置的初始化参数"+properties);
}

}

public void testCollection() { SqlSession sqlSession = this.getSqlSessionFactory().openSession(); PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); Person person=personMapper.getPersonByCollection(new int[]{1,2}); System.out.println(person);

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

Mybatis拦截器实现分页

public List getAllPersons();

public void getAllPersons() {

SqlSession sqlSession = this.getSqlSessionFactory().openSession();

PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

Page page= PageHelper.startPage(1,10);

List persons=personMapper.getAllPersons();

PageInfo pageInfo=new PageInfo(persons,9); for (Person person:persons) { System.out.println(person.getId()); }

System.out.println(page.getPageNum());//current page System.out.println(page.getTotal());//total System.out.println(page.getPageSize());//page size

System.out.println(pageInfo.isIsFirstPage());

System.out.println(pageInfo.getPages());// total pages

int[] nums=pageInfo.getNavigatepageNums();

for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } }

===================传统分页===========

package com.imooc.project.util;

import java.util.List;

/** * create by imooc */ public class PageUtil {

private int currentPageNum; //当前要看哪一页

private int pageSize=10;//每页显示的条数

private int totalSize;//总记录条数

private int startIndex;//查询开始记录的索引 limit ? ?

private int totalPageNum;//总页数

private int prePageNum;//上一页

private int nextPageNum;//下一页

private List records;//当前页的记录集

//用于显示页面上的导航的页号 用户可自定义 private int startPageNum; private int endPageNum; private String url;

//使用构造方法,传递必要的两个参数.第一个是页码,第二个总记录条数 public PageUtil(int currentPageNum,int totalrecords) { this.currentPageNum=currentPageNum; this.totalSize=totalrecords; //计算开始记录索引 startIndex=(currentPageNum-1)*pageSize; //计算总页数 totalPageNum=totalSize%pageSize==0?totalSize/pageSize:totalSize/pageSize+1; //计算开始和结束页号 这个根据自身可设计 if(totalPageNum>9) { startPageNum=currentPageNum-4; endPageNum=currentPageNum+4;

     if(startPageNum<1)
     {
        startPageNum=1;
        endPageNum=startPageNum+8;
     }
     if(endPageNum>totalPageNum)
     {
        endPageNum=totalPageNum;
        startPageNum=endPageNum-8;
     }
  }
  else
  {
     startPageNum=1;
     endPageNum=totalPageNum;
  } 

}

 public int getStartPageNum() {
  return startPageNum;

}

public void setStartPageNum(int startPageNum) { this.startPageNum = startPageNum; }

public int getEndPageNum() { return endPageNum; }

public void setEndPageNum(int endPageNum) { this.endPageNum = endPageNum; }

public int getPrePageNum() { prePageNum=currentPageNum-1;

  if(prePageNum<=0)
  {
     prePageNum=1;
  }
  return prePageNum;

}

public int getNextPageNum() {

  nextPageNum=currentPageNum+1;
  
  if(nextPageNum>totalPageNum)
  {
     nextPageNum=totalPageNum;
  }
  return nextPageNum;

} public int getCurrentPageNum() { return currentPageNum; } public void setCurrentPageNum(int currentPageNum) { this.currentPageNum = currentPageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { this.totalSize = totalSize; } public int getStartIndex() { return startIndex; } public void setStartIndex(int startIndex) { this.startIndex = startIndex; } public int getTotalPageNum() { return totalPageNum; } public void setTotalPageNum(int totalPageNum) { this.totalPageNum = totalPageNum; } public List getRecords() { return records; } public void setRecords(List records) { this.records = records; }

public void setPrePageNum(int prePageNum) { this.prePageNum = prePageNum; } public void setNextPageNum(int nextPageNum) { this.nextPageNum = nextPageNum; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }

package com.imooc.project.web;

import java.io.IOException;

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 com.imooc.project.service.UserService; import com.imooc.project.service.impl.UserServiceImpl; import com.imooc.project.util.PageUtil;

@WebServlet("/servlet/UserServlet") public class UserServlet extends HttpServlet {

private UserService userService=new UserServiceImpl();

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response);

  }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method=request.getParameter("method");

  if(method.equals("all"))
 {
   selectAllUsers(request,response);
 }

}

//获取所有的用户信息

private void selectAllUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String num=request.getParameter("num");

    if(null==num)
  {
     num="1";
  }

  PageUtil page=null;

  try {
     page=userService.getAllUsers(num);
  } catch (Exception e) {
     e.printStackTrace();
  }
  request.setAttribute("page",page);
  request.getRequestDispatcher("/users.jsp").forward(request,response);

}

}

package com.imooc.project.service.impl;

import com.imooc.project.dao.PersonMapper; import com.imooc.project.dao.UserDao; import com.imooc.project.dao.impl.UserDaoImpl; import com.imooc.project.entity.Person; import com.imooc.project.entity.User; import com.imooc.project.service.UserService; import com.imooc.project.util.PageUtil; 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.Reader; import java.util.List;

/** * Created by imooc */ public class UserServiceImpl implements UserService {

 private UserDao userDao=new UserDaoImpl();

public static SqlSessionFactory sqlSessionFactory = null;

public static SqlSessionFactory getSqlSessionFactory() {
    if (sqlSessionFactory == null) {
        String resource = "mybatis-config.xml";
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sqlSessionFactory;
}

/** @Override public List getAllUsersBypageHelper() {

    SqlSession sqlSession=this.getSqlSessionFactory().openSession();

    PersonMapper personMapper=sqlSession.getMapper(PersonMapper.class);

    List<Person> persons=personMapper.getAllPersons();


    return persons;
}

**/ @Override public PageUtil getAllUsers(String num) throws Exception {

    int currentPageNum=1;

    if(null!=num&&!num.trim().equals(""))
    {
        currentPageNum=Integer.parseInt(num);
    }

    int totalRecords=userDao.totalRecords();

    PageUtil pu=new PageUtil(currentPageNum,totalRecords);

    List<User> users= userDao.getAllUsers(pu.getStartIndex(),pu.getPageSize());

    pu.setRecords(users);

    return pu;
}

}

package com.imooc.project.dao.impl;

import com.imooc.project.dao.BaseDao; import com.imooc.project.dao.UserDao; import com.imooc.project.entity.User; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.ibatis.executor.ReuseExecutor;

import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.sql.PreparedStatement;

/** * Created by imooc */ public class UserDaoImpl extends BaseDao implements UserDao {

QueryRunner queryRunner=new QueryRunner();

@Override
public List<User> getAllUsers(int startIndex, int pageSize) throws Exception {

    String sql="select \* from t\_user limit ?,?";

    List<User> users=null;

    users=queryRunner.query(this.getConnection(),sql,new BeanListHandler<User>(User.class),new Object\[\]{startIndex,pageSize});

    return users;
}

@Override
public int totalRecords() throws Exception {
    int result=0;

    Connection conn=this.getConnection();
    PreparedStatement ps=null;

    ResultSet rs=null;

    String sql="select count(\*)  count from t\_user";
    ps=conn.prepareStatement(sql);
    rs=ps.executeQuery();

    if(rs.next())
    {
        result=rs.getInt("count");
    }

    return result;

}

}

===============pageHelper============

package com.imooc.project.web;

import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.imooc.project.entity.Person; import com.imooc.project.service.UserService; import com.imooc.project.service.impl.UserServiceImpl; import com.imooc.project.util.PageUtil;

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/UserServlet2") public class UserServlet2 extends HttpServlet {

private UserService userService=new UserServiceImpl();

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response);

  }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  String method=request.getParameter("method");

  if(method.equals("all"))
 {
   selectAllUsers(request,response);
 }

}

//获取所有的用户信息

private void selectAllUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String num=request.getParameter("num");

    if(null==num)
  {
     num="1";
  }

  // Page PageInfo

  Page<?> page=PageHelper.startPage(Integer.parseInt(num),5);

  List<Person> persons=userService.getAllUsersBypageHelper();

  PageInfo<?> pageHelper=page.toPageInfo();

  request.setAttribute("persons",persons);
  request.setAttribute("pagehelper",pageHelper);

    request.getRequestDispatcher("/persons.jsp").forward(request,response);

  /\*PageUtil page=null;

  try {
     page=userService.getAllUsers(num);
  } catch (Exception e) {
     e.printStackTrace();
  }
  request.setAttribute("page",page);
  request.getRequestDispatcher("/users.jsp").forward(request,response);\*/

}

}

@Override public List getAllUsersBypageHelper() {

SqlSession sqlSession=this.getSqlSessionFactory().openSession();

PersonMapper personMapper=sqlSession.getMapper(PersonMapper.class);

List<Person> persons=personMapper.getAllPersons();


return persons;

}

public List getAllPersons();

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这