1.首先創建一個分頁實體類PageBean
public class PageBean<T>{
//總記錄數
private int totalCount;
//總頁碼
private int totalPage;
//每頁的數據
private List<T>list;
//當前頁碼
private int currentPage;
//每頁顯示的記錄數
private int rows;
//get and set方法
}
2.controller層
@Autowrid
private UserService userService;
public StringselectByPage(@RequestParam("currentPage")int currentPage,@RequestParam("rows")int rows,Model model){
//查詢
PageBean<User>pb=userservice.selectByPage(currentPage,rows);
//存入model中
model.setObject("list",list);
//轉發
return "user.jsp";
}
service層
public PageBean<User> selectByPage(int currentPage,int rows){
//創建空的pagebean對象
PageBean<User>pb=new PageBean<User>();
//設置參數
pb.setCurrentPage(currentPage);
pb.setRows(rows);
//調用dao查詢總記錄數
int totalCount=userMapper.findTotalCount();
pb.setTotalCount(totalCount);
//查詢list集合
//計算剛開始查詢的索引
int start=(currentPage-1)*rows;
List<User>list=userMapper.selectAll(start,rows);
pb.setList(list);
//計算總頁碼
int totalPage = totalCount % rows ==0 ? totalCount/rows : totalCount/rows + 1 ;
pb.setTotalPage(totalPage );
return pb;
}
mybatis及UserServiceImpl略去.