1.增强PageBean属性
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
//上一次查询的url
private String url;
//上一次查询所携带的查询条件map
private Map<String, String[]> parameter = new HashMap<String, String[]>();
public void setRequest(HttpServletRequest req) {
//初始化jsp页面传递过来的当前页
this.setPage(req.getParameter("page"));
//初始化jsp页面传递过来的页大小
this.setRows(req.getParameter("rows"));
//初始化jsp页面传递过来是否分页
this.setPagination(req.getParameter("pagination"));
//保留上一次的查询请求
this.setUrl(req.getRequestURL().toString());
//保留上一次的查询条件
this.setParameter(req.getParameterMap());
}
//重载setpagination
private void setPagination(String pagination) {
//只有填写了false才会不分页 ,其他的字符串无效
this.setPagination(!"false".equals(pagination));
}
//重载setRows
private void setRows(String rows) {
if(StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));
}
//重载setpage
private void setPage(String page) {
if(StringUtils.isNotBlank(page))
this.setPage(Integer.valueOf(page));
}
//上一页
public int getPrevPage() {
return this.page > 1 ? this.page-1 : this.page;
}
//下一页
public int getNextPage() {
return this.page < this.getMaxPage() ? this.page+1 : this.page;
}
//最大页
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total / this.rows : (this.total / this.rows) + 1;
}
6.PageBean
实体类改造好了
package com.houzhihong.pagebean.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
//上一次查询的url
private String url;
//上一次查询所携带的查询条件map
private Map<String, String[]> parameter = new HashMap<String, String[]>();
//对pagebean进行初始化
public void setRequest(HttpServletRequest req) {
//初始化jsp页面传递过来的当前页
this.setPage(req.getParameter("page"));
//初始化jsp页面传递过来的页大小
this.setRows(req.getParameter("rows"));
//初始化jsp页面传递过来是否分页
this.setPagination(req.getParameter("pagination"));
//保留上一次的查询请求
this.setUrl(req.getRequestURL().toString());
//保留上一次的查询条件
this.setParameter(req.getParameterMap());
}
//重载setpagination
private void setPagination(String pagination) {
//只有填写了false才会不分页 ,其他的字符串无效
this.setPagination(!"false".equals(pagination));
}
//重载setRows
private void setRows(String rows) {
if(StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));
}
//重载setpage
private void setPage(String page) {
if(StringUtils.isNotBlank(page))
this.setPage(Integer.valueOf(page));
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameter() {
return parameter;
}
public void setParameter(Map<String, String[]> parameter) {
this.parameter = parameter;
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
//上一页
public int getPrevPage() {
return this.page > 1 ? this.page-1 : this.page;
}
//下一页
public int getNextPage() {
return this.page < this.getMaxPage() ? this.page+1 : this.page;
}
//最大页
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total / this.rows : (this.total / this.rows) + 1;
}
}
1.使用泛型定义好方法方便子类调用达成通用性
package com.houzhihong.pagebean.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BaseDao<T> {
public List<T> executeQuery(String sql, Class clz, PageBean pagebean)
throws SQLException, InstantiationException, IllegalAccessException {
List<T> list = new ArrayList<>();
// 获取连接
Connection con = DBAccess.getConnection();
// 执行sql
PreparedStatement ps = null;
ResultSet rs = null;
if(pagebean !=null && pagebean.isPagination()) {
//分页---> 列表需求
//查询出符合条件的总记录数
String countSql = getCountSql(sql);
ps = con.prepareStatement(countSql);
rs = ps.executeQuery();
if(rs.next()) {
//把数据放入pageBean
pagebean.setTotal(rs.getObject(1).toString());
}
//展示想要看到的数据 ,比如3页的十条数据
String pageSql = getPageSql(sql,pagebean);
ps = con.prepareStatement(pageSql);
rs = ps.executeQuery();
}else {
//不分页 ---> 下拉框需求
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
while (rs.next()) {
// *实例化对象
T t = (T) clz.newInstance();
for (Field f : clz.getDeclaredFields()) {
f.setAccessible(true);
// 给这一个空对象的每一个属性赋值
f.set(t, rs.getObject(f.getName()));
}
// 将赋值完的对象添加到list集合中返回
list.add(t);
}
DBAccess.close(con, ps, rs);
return list;
}
private String getPageSql(String sql, PageBean pagebean) {
return sql + " limit "+pagebean.getStartIndex()+","+pagebean.getRows();
}
/**
* --原生的带条件的查询语句
* sql =SELECT * FROM t_mvc_book WHERE true and bname like '%斗破%'
*
*
*--符合条件的记录数有多少条
* countsql= SELECT COUNT(1) from (SELECT * FROM t_mvc_book WHERE TRUE AND bname LIKE '%圣墟%') t;
*
*--查询第几页的数据 LIMIT 起始下标,偏移量 展示的记录数
* pagesql= SELECT * FROM t_mvc_book WHERE TRUE AND bname LIKE '%圣墟%' LIMIT 10,10
*
*
*/
private String getCountSql(String sql) {
return "select count(1) from ("+sql+") t";
}
}
2.bookDao直接继承BaseDao的方法executeQuery,直接反射一波
return super.executeQuery(sql, Book.class, pagebean);
while (rs.next()) {
// *实例化对象
T t = (T) clz.newInstance();
for (Field f : clz.getDeclaredFields()) {
f.setAccessible(true);
// 给这一个空对象的每一个属性赋值
f.set(t, rs.getObject(f.getName()));
}
// 将赋值完的对象添加到list集合中返回
list.add(t);
}
1.action业务层
2.注意初始化PageBean不要写到异常里面去了
package com.houzhihong.pagebean.web;
import java.io.IOException;
import java.sql.SQLException;
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 com.houzhihong.pagebean.dao.BookDao;
import com.houzhihong.pagebean.entity.Book;
import com.houzhihong.pagebean.util.PageBean;
@WebServlet(name = "book", urlPatterns = "/book.action")
public class BookAction extends HttpServlet {
private static final long serialVersionUID = 4591437219474314661L;
private BookDao bookDao = new BookDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 实例化对象
Book book = new Book();
// 获取表单值
book.setBname(req.getParameter("bname"));
// 初始化PageBean
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
try {
List<Book> list = this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pageBean", pageBean);
req.getRequestDispatcher("booklist.jsp").forward(req, resp);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.PageTag助手类,将页面的表单,分页条,js拼接代码
package com.houzhihong.pagebean.tag;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.houzhihong.pagebean.util.PageBean;
public class PageTag extends BodyTagSupport {
private static final long serialVersionUID = 6584001758518399660L;
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
// 输出分页条
JspWriter out = pageContext.getOut();
try {
out.println(toHTML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuilder sb = new StringBuilder();
// 上一次查询的form表单的html拼接
sb.append(");
// 查第几页
sb.append("");
// 拼接带条件查询
Map<String, String[]> parameter = pageBean.getParameter();
if (parameter.size() > 0) {
Set<Entry<String, String[]>> entrySet = parameter.entrySet();
for (Entry<String, String[]> entry : entrySet) {
if (!"page".equals(entry.getKey())) {
for (String val : entry.getValue()) {
sb.append("");
}
}
}
}
sb.append("");
// 默认展示前面4页 , 当前页 , 后面5页
int page = pageBean.getPage();
int max = pageBean.getMaxPage();
int before = page > 4 ? 4 : page - 1;
int after = 10 - 1 - before;
after = max - page > after ? after : max - page;
// 用来控制上一页的点击按钮特效的
boolean startFlag = page == 1;
// 用来控制下一页的点击按钮特效的
boolean endFlag = max == page;
// 拼接分页条
sb.append(""
);
sb.append("首页 ");
sb.append("< ");
// 代表了当前页的前4页
for (int i = before; i > 0; i--) {
sb.append(""
+ (page - i) + "");
}
sb.append("" + pageBean.getPage() + "");
// 代表了当前页的后5页
for (int i = 1; i <= after; i++) {
sb.append(""
+ (page + i) + "");
}
sb.append("> ");
sb.append("尾页 ");
sb.append(
"到第页 ");
sb.append("确定 ");
sb.append("共" + pageBean.getTotal() + "条");
sb.append("");
// 拼接分页的js代码
sb.append("");
return sb.toString();
}
}
2.配置好自己定义tld标签库
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>JSTL 1.1 core library</description>
<display-name>JSTL core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>h</short-name>
<uri>/houzhihong</uri>
<tag>
<name>page</name>
<tag-class>com.houzhihong.pagebean.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3.代码贴的差不多了还有些之前有贴,上效果了