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);
public List
public void getAllPersons() {
SqlSession sqlSession = this.getSqlSessionFactory().openSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
Page
List
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
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
SqlSession sqlSession=this.getSqlSessionFactory().openSession();
PersonMapper personMapper=sqlSession.getMapper(PersonMapper.class);
List<Person> persons=personMapper.getAllPersons();
return persons;
}
public List