下面定义了一些方法用来分页,和昨天的比多了很多,注意修改或添加
package com.rong.book.utils;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class PageBean {
private Integer page=1; //页码
private Integer rows=3; //页大小
private Integer total=0; //总记录数
private boolean pagination=true; //默认 true分页
private String url;//请求路径
private Map<String, String[]> map;//请求参数集合
public PageBean() {
super();
}
public Map<String, String[]> getMap() {
return map;
}
public void setMap(Map<String, String[]> map) {
this.map = map;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public void setPage(String page) {
if(page!=null&& ! "".equals(page)) {
this.page =Integer.parseInt(page);
}
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public void setRows(String rows) {
if(rows!=null&&!"".equals(rows)) {
this.rows =Integer.parseInt(rows);
}
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public void setPagination(String pagination) {
if("false".equals(pagination)) {
this.pagination =Boolean.parseBoolean(pagination);
}
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
public int getStartIndex() {
return (this.page-1)*this.rows;
}
public void SetRequest(HttpServletRequest req) {
String page=req.getParameter("page");
String rows=req.getParameter("rows");
String pagination=req.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPage(pagination);
this.setUrl(req.getRequestURI());
this.setMap(req.getParameterMap());
}
public int getMaxPage() {
int maxpage=this.total/this.rows;
if(this.total%this.rows!=0) {
maxpage++;
}
return maxpage;
}
/**
* 得到上一页
* @return
*/
public int getPerPage() {
int perpage=this.page-1;
if(perpage<1) {
perpage=1;
}
return perpage;
}
public int getNextPage() {
int nextpage=this.page+1;
if(nextpage>this.getMaxPage()) {
nextpage=this.getMaxPage();
}
return nextpage;
}
}
把这个替换昨天的dao最下面一个方法,基本就用这个一个方法实现分页
public List<Book> listBooks(Book book,PageBean pageBean) {
String sql = "SELECT bid,bname,price FROM book WHERE 1=1";
if(StringUtils.isNotBlank(book.getBname())) {
sql += " AND bname LIKE '%"+book.getBname()+"%'";
}
return this.exectueQuery(sql, pageBean, new CallBack<Book>() {
@Override
public List<Book> forEachRs(ResultSet rs) throws SQLException {
List<Book> ls= new ArrayList<Book>();
Book b = null;
while(rs.next()) {
b = new Book();
b.setBid(rs.getInt("bid"));
b.setBname(rs.getString("bname"));
b.setPrice(rs.getFloat("price"));
ls.add(b);
}
return ls;
}
});
}
package com.rong.book.base;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.rong.book.utils.DBHelper;
import com.rong.book.utils.PageBean;
public class BaseDao<K> {
public static interface CallBack<T> {
public List<T> forEachRs(ResultSet rs) throws SQLException;
}
public List<K> exectueQuery(String sql,PageBean pageBean,CallBack<K> callBack) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBHelper.getConnection();
//1.查询符合条件的总记录
if(null!=pageBean && pageBean.isPagination()) {
String countSql = this.getCountSql(sql);
ps = con.prepareStatement(countSql);
rs = ps.executeQuery();
if(rs.next()) {
Object obj = rs.getInt(1);
pageBean.setTotal(obj.toString());
}
DBHelper.close(null, ps, rs);
}
//2.查询符合条件的记录
if(null!=pageBean && pageBean.isPagination()) {
sql = this.pageSql(sql, pageBean);
}
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
return callBack.forEachRs(rs);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
DBHelper.close(con, ps, rs);
}
}
/**
* 得到查询总记录的sql语句
* @param sql
* @return
*/
private String getCountSql(String sql) {
String countSql = " SELECT COUNT(1) FROM ("+ sql +") t1 ";
return countSql;
}
/**
* 得到分页的sql语句
* @param sql
* @param pageBean
* @return
*/
private String pageSql(String sql,PageBean pageBean) {
String pageSql = sql+" LIMIT "+pageBean.getStartIndex()+","+pageBean.getRows()+"";
return pageSql;
}
}
package com.rong.book.action;
import java.io.IOException;
import java.util.List;
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 javax.servlet.http.HttpSession;
import com.rong.book.biz.BookBiz;
import com.rong.book.biz.IBookBiz;
import com.rong.book.entity.Book;
import com.rong.book.utils.PageBean;
@WebServlet("/listBook.action")
public class BookServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.设置编码
req.setCharacterEncoding("utf-8");
//2.获取页面传过来的值
String bookname=req.getParameter("bookname");
PageBean pageBean = new PageBean();
pageBean.SetRequest(req);
Book book = new Book();
book.setBname(bookname);
//3.调用biz层查询
IBookBiz bookBiz = new BookBiz();
List<Book> bookls=bookBiz.listBooks(book, pageBean);
//4.将查询出的集合放到作用域中
req.setAttribute("bookls", bookls);
req.setAttribute("pagebean", pageBean);
req.getRequestDispatcher("listBook.jsp").forward(req, resp);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="listBook.action">查询所有书本</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>小说城</title>
<script type="text/javascript">
function gotopage(page){
document.getElementById('pagebeanform').page.value=page;
document.getElementById('pagebeanform').submit();
}
function skippage(maxpage){
var page=document.getElementById('skipPage').value;
if(isNaN(page)||page<1||page>maxpage){
alert("请输入1-"+maxpage+"的数字")
}else{
gotopage(page);
}
}
</script>
</head>
<body>
<h2>小说城</h2>
<form action="listBook.action" method="post">
书名:<input type="text" name="bookname"/>
<input type="submit" value="查询"/>
</form>
<table border="1px" width="100%">
<tr>
<td>序号</td>
<td>书名</td>
<td>价格</td>
</tr>
<c:forEach items="${bookls }" var="b" varStatus="s">
<tr>
<td>${s.count }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
</tr>
</c:forEach>
</table>
<form action="${pagebean.url }" method="post" id="pagebeanform">
<input type="hidden" name="page" id="page"/>
<!-- 请求参数 -->
</form>
<div style="width:100%;text-align: right;">
<a href="javascript:gotopage(1)">首页</a>
<a href='javascript:gotopage("${pagebean.getPerPage() }")'>上一页</a>
<a href='javascript:gotopage("${pagebean.getNextPage() }")'>下一页</a>
<a href="javascript:gotopage(${pagebean.getMaxPage() })">尾页</a>
<input id="skipPage" style="width:30px"/>
<a href="javascript:skippage(${pagebean.getMaxPage() })">GO</a>
</div>
</body>
</html>
虽然效果出来了,但是我还是有些地方不是很明白的,也不知道怎么解释;
加油!六一快乐