如何通过分页插件在ssm框架中实现分页功能?


package cn.kgc.test;

import static org.junit.Assert.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 org.junit.Test;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.kgc.dao.EmployeeMapper;
import cn.kgc.pojo.Employee;

public class EmpTest {

	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	@Test
	public void test() throws IOException {
		// 1、获取sqlSessionFactory
				SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
				// 2、获取sqlSession
				SqlSession openSession = sqlSessionFactory.openSession();
				//插件的分页方法,在此处 传入 当前页 和 页容量 两个参数
				  Page page=PageHelper.startPage(1, 5);
				  
				  try{
					  EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
						
					 
						List emps = mapper.getEmps();
						
						PageInfo info=new  PageInfo(emps);
						for (Employee employee : emps) {
							System.out.println(employee);
						}
						System.out.println("首页"+info.getFirstPage());
						System.out.println("上一页"+info.getPrePage());
						System.out.println("下一页"+info.getNextPage());
						System.out.println("最后一页"+info.getLastPage());
						System.out.println("当前页码"+info.getPageNum());
						System.out.println("总记录数"+info.getTotal());
						System.out.println("每页的记录数"+info.getPageSize());
						System.out.println("总页码"+info.getPages());
						System.out.println("是否是第一页"+info.isIsFirstPage());
						
				  }finally{
					  openSession.close();
				  }
					
					
					
					
					
				
	}

	
} 
  

使用分页插件的代码步骤

dao层(sql映射):
    
	
	service层:
	   public List getUserList(){
	       return userDao.getUserList()
	   }
	   
	  
	  
	controller层:
	@RequestMapping("/userlist")    
	public String userList(@RequestParam(required=true,defaultValue="1") Integer page,  HttpServletRequest re,Model model){
	           List userList=userService.getUserList();
	           
	           //如何使用分页jar包? 主要通过 PagerHelper和PageInfo两个类
	          PageHelper.startPage(page,3);
	          PageInfo pageInfo=new PageInfo(userList);
	          model.addAttribute("userList",userList);	          
	          model.addAttribute("page",pageInfo);
	}
	
	jsp层:
	   一共${page.pages}页
	   第一页
	   下一页
	   上一页
	   最后一页

你可能感兴趣的:(课堂)