通用分页
一、导入jar
二、导入工具类
三、写实体类和dao类、uitl包中的BeasDao类
BeasTag类是用来写共性部分的
如:
Connection con=null;
PreparedStatement ps=null;
ResultSet rs = null;
为共性部分,如果有人和自己做的项目一样只是内容不一样,我们就可以用这种通用的方法
如:
BeasDao中的查询的通用
public List<T> executeQuery(String sql,Class las,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
List<T> ls=new ArrayList<T>();
Connection con=DBAccess.getConnection();
PreparedStatement ps=null;
ResultSet rs = null;
if(pageBean!=null&&pageBean.isPagination()) {//分页
//查询出符合条件的总记录数
String countSql=getcountSql(sql);
ps=con.prepareStatement(countSql);
ps.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getObject(1).toString());
}
//展示想要看到的数据
String pageSql=getpageSql(sql,pageBean);
ps=con.prepareStatement(pageSql);
ps.executeQuery();
}else {
ps=con.prepareStatement(sql);
ps.executeQuery();
}
while(rs.next()) {
//ls.add(new Book(rs.getInt("bid"),rs.getString("bname"), rs.getFloat("price")));
/**
* 实例化一个对象
* 给这一个空对象的每一个属性赋值
* 将赋值完的对象添加到list集合中返回
*/
//相当于new了一个对象
T t=(T) las.newInstance();
//Field[] decfie = las.getDeclaredFields();
for (Field f : las.getDeclaredFields()) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
ls.add(t);
}
DBAccess.close(con, ps, rs);
return ls;
}
private String getpageSql(String sql, PageBean pageBean) {
// TODO Auto-generated method stub
return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getcountSql(String sql) {
// TODO Auto-generated method stub
return "select count(1) form ("+sql+") t";
}
sql语句为特性部分
如:
bookDao中的查询语句
/**
* 通过反射改装后的通用查询
* @param book
* @param pageBean
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public List<Book> list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
String sql="select *from t_mvc_book where true";
String bname=book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +=" and bname like '%"+bname+"%'";
}
return super.executeQuery(sql, Book.class, pageBean);
}
public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException {
BookDao bookDao=new BookDao();
Book book=new Book();
// 想要查看的内容
// book.setBname("圣墟");
PageBean pageBean=new PageBean();
// 想要查看的页码
// pageBean.setPage(5);
// 是否想要分页
// pageBean.setPagination(false);
List<Book> ls=bookDao.list(book, pageBean);
for (Book b : ls) {
System.out.println(b);
}
}
四、写一个PageTag用来分页
在写PageTag类之前,我们要在工具类中找到PageBean,在PageBean中写
一些我考虑到分页所需要的功能
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
//上一次查询的url
private String url;
//上一次查询所带的查询条件
private Map<String, String[]> parameterMap=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.getRequestURI().toString());
//保留上一次查询条件
this.setParameterMap(req.getParameterMap());
}
private void setPagination(String pagination) {
// TODO Auto-generated method stub
//填写false表示不分页
this.setPagination(!"false".equals(pagination));
}
private void setPage(String page) {
// TODO Auto-generated method stub
if(StringUtils.isNotBlank(page)) {
this.setPage(Integer.valueOf(page));
}
}
private void setRows(String roes) {
// TODO Auto-generated method stub
if(StringUtils.isNotBlank(roes)) {
this.setRows(Integer.valueOf(rows));
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public void setPage(int page) {
this.page = page;
}
private boolean pagination = true;// 是否分页
public PageBean() {
super();
}
public int getPage() {
return 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;
}
}
然后在PageTag类中拼接我们的表单
public class PageTag extends BodyTagSupport{
private static final long serialVersionUID = -8012081268314346782L;
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.print(toHTML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuilder sb = new StringBuilder();
// 上一次查询的from表单的html拼接
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
// 查第几页的数据
sb.append("<input type='hidden' name='page'>");
// 重要设置拼接操作,将上一次请求参数携带到下一次
Map<String, String[]> parameterMap = pageBean.getParameterMap();
if(parameterMap.size()>0){
Set<Entry<String,String[]>> entrySet = parameterMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
if(!"page".equals(entry.getKey())){
for (String val : entry.getValue()) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>");
}
}
}
}
sb.append("</form>");
// 默认展示前面4页,当前页,后面5页
int page = pageBean.getPage();
int max = pageBean.getMaxPage();
int before = page > 4 ? 4 : page-1;
int after = 10 - 1 - before;//5
after = max - page > after ? after : max-page;
// 用来控制上一页的点击按钮特效的
boolean startFlag = page > 1;
// 用来控制下一页的点击按钮特效的
boolean endFlag = page < max;
// 拼接分页条
sb.append("<ul class='pagination'>");
sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage(1)'>首页</a></li>");
sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getPrevPage()+")'><</a></li>");
// 代表了当前页的前4页
for (int i = before; i > 0 ; i--) {
sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page-i)+")'>"+(page-i)+"</a></li>");
}
sb.append("<li class='page-item active'><a class='page-link' href='javascript:gotoPage("+pageBean.getPage()+")'>"+pageBean.getPage()+"</a></li>");
// 代表了当前页的后5页
for (int i = 1; i <= after; i++) {
sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page+i)+")'>"+(page+i)+"</a></li>");
}
sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getNextPage()+")'>></a></li>");
sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a></li>");
sb.append("<li class='page-item go-input'><b>到第</b><input class='page-link' type='text' id='skipPage' name='' /><b>页</b></li>");
sb.append("<li class='page-item go'><a class='page-link' href='javascript:skipPage()'>确定</a></li>");
sb.append("<li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
sb.append("</ul>");
// 拼接分页的js代码
sb.append("<script type='text/javascript'>");
sb.append("function gotoPage(page) {");
sb.append("document.getElementById('pageBeanForm').page.value = page;");
sb.append("document.getElementById('pageBeanForm').submit();");
sb.append("}");
sb.append("function skipPage() {");
sb.append("var page = document.getElementById('skipPage').value;");
sb.append("if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+max+") {");
sb.append("alert('请输入1~N的数字');");
sb.append("return;");
sb.append("}");
sb.append("gotoPage(page);");
sb.append("}");
sb.append("</script>");
return sb.toString();
}
}
五、在写jsp界面前我们写一个自定义标签
六、开始写jsp界面和BookAction
BookAction使用来实现jsp界面中的查询功能的
@WebServlet(name="book",urlPatterns="/book.action")
public class BookAction extends HttpServlet{
private static final long serialVersionUID = -8000602503008331264L;
private BookDao bookDao = new BookDao();
@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 {
Book book = new Book();
book.setBname(req.getParameter("bname"));
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();
}
}
七、实现的效果图
总结:少壮不努力老大徒伤悲