用Java实现通用分页(2)

通用分页

1,写好web层
2, jsp展示
3, 在PageBean写好分页所需要的参数
4, 自定义好标签在jsp页面调用

我们先导入实体类

package com.entity;

public class Book {
	private int bid;
	private String bname;
	private float price;

	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
	}

	public int getBid() {
		return bid;
	}

	public void setBid(int bid) {
		this.bid = bid;
	}

	public String getBname() {
		return bname;
	}

	public void setBname(String bname) {
		this.bname = bname;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public Book(int bid, String bname, float price) {
		super();
		this.bid = bid;
		this.bname = bname;
		this.price = price;
	}

	public Book() {
		super();
	}
	
	

}

导入判空等下需要用到

package com.zking.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

导入防中文乱码工具

package com.zking.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 中文乱码处理
 * 
 */
public class EncodingFiter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

然后我们开始写PageBean,代码如下

package com.zking.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;// 是否分页
	
	private String url;
	private Map paramMap = new HashMap<>();

	//提供一个初始化的方法
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		//getRequestURI()获取全路径
		this.setUrl(req.getRequestURI().toString());
		//getParameterMap获取到一次url请求所携带的所有参数
		this.setParamMap(req.getParameterMap());
	}
	
	
	
	public void setPagination(String pagination) {
		if(StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
		
	}



	//重载rows
	public void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setPage(Integer.valueOf(rows));
		}
		
	}



	//重载
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
			this.setPage(Integer.valueOf(page));
		}
		
	}


	public PageBean() {
		super();
	}
	

	public String getUrl() {
		return url;
	}


	public void setUrl(String url) {
		this.url = url;
	}


	public Map getParamMap() {
		return paramMap;
	}


	public void setParamMap(Map paramMap) {
		this.paramMap = paramMap;
	}


	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return 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 getMaxPage() {
		return this.total % this.rows ==0 ? 
				this.total / this.rows :
					(this.total / this.rows) +1;
	}
	
	//获取下一页
	public int getNextPage() {
		return this.page < this.getMaxPage() ? this.page+1 : this.getMaxPage();
	}
	
	//获取上一页
	public int getPreviousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}
	
	

}

注:
这里有一个重要的核心
这三个方法一定要写,因为我们等下在自定义标签里面需要用到

	//获取到总页数
	public int getMaxPage() {
		return this.total % this.rows ==0 ? 
				this.total / this.rows :
					(this.total / this.rows) +1;
	}
	
	//获取下一页
	public int getNextPage() {
		return this.page < this.getMaxPage() ? this.page+1 : this.getMaxPage();
	}
	
	//获取上一页
	public int getPreviousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}

然后我们开始编写通用分页方法

package com.zking.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;

import com.entity.Book;



public class BaseDao {
	
	//通用查询
	/**
	 * 
	 * @param sql 决定查询那张表的数据
	 * @param clz 查询出来的数据封装到哪里实体类中
	 * @param pageBean 决定是否分页
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws SQLException 
	 */
	@SuppressWarnings("resource")
	public List executeQuery(String sql,Class clz,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		List list = new ArrayList<>();
		Connection con = DBAccess.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			if (pageBean != null && pageBean.isPagination()) {
				//该分页了
				String countSql = getCountsql(sql);
				ps = con.prepareStatement(countSql);
				rs = ps.executeQuery();
				if(rs.next()) {
					pageBean.setTotal(rs.getLong(1)+"");
				}
				
				String pageSql = getPageSql(sql,pageBean);
				ps = con.prepareStatement(pageSql);
				rs = ps.executeQuery();
				
			} else {
				ps = con.prepareStatement(sql);
				rs = ps.executeQuery();
			}
			while (rs.next()) {
				//			list.add(new Book(rs.getInt("bid"),
				//					rs.getString("bname"),
				//					rs.getFloat("price")));
				/*
				 * 1.创建了一个Book对象
				 * 2.从ResultSet结果集中获取值放入Book对象属性中
				 *   2.1 获取到book属性对象
				 *   2.2 给属性对象赋值 
				 * 3.将已经有值的Book对象放入list集合中
				 * */
				//1
				T t = (T) clz.newInstance();
				//2
				Field[] fields = clz.getDeclaredFields();
				for (Field field : fields) {
					field.setAccessible(true);
					field.set(t, rs.getObject(field.getName()));
				}
				list.add(t);
			} 
		} finally {
			//shift + alt + z
			DBAccess.close(con,ps,rs);
		}
		return list;
	}
	
	/**
	 * 将原生sql拼接出符合条件的某一页的数据查询sql
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSql(String sql, PageBean pageBean) {
		return sql  + " limit "+pageBean.getStartIndex()+ "," +pageBean.getRows();
	}
	/**
	 * 用原生sql拼接出查询符合条件的记录数
	 * @param sql
	 * @return
	 */
	private String getCountsql(String sql) {
//		t为别名随便取
		return "select count(1) from ("+sql+") t";
	}
	
	
}

写完之后我们就建立一个dao方法,
dao继承通用方法

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.entity.Book;
import com.zking.util.BaseDao;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

/**
 * 操作数据库中的t_mvc_book表
 * 1.加载驱动
 * 2.建立链接
 * 3.获取预定义处理对象
 * 4.执行sql语句
 * 5.处理结果集
 * 6.关闭连接
 * @author lqx
 *
 */
public class BookDao extends BaseDao{
	/**
	 * 
	 * @param book 是从jsp传递过来的参数封装成对象的作为参数查询并执行sql
	 * @param pageBean 决定是否分页
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public List list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		String sql = "select * from t_mvc_book where 1=1";
		if(StringUtils.isNotBlank(book.getBname())) {
			sql += " and bname like '%"+book.getBname()+"%'";
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}
	
	public static void main(String[] args) {
		BookDao bookDao = new BookDao();
		try {
			Book b = new Book();
			PageBean pageBean = new PageBean();
			//false代表不想分页 反之
//			pageBean.setPagination(false);
			//代表想从第几页开始查 默认第一页
//			pageBean.setPage(2);
			//代表想要查询的内容 如果去掉就是查看所有
//			b.setBname("圣墟");
			List list = bookDao.list(b, pageBean);
			for (Book book : list) {
				System.out.println(book);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
			
	}
	
}

然后后我们就可以开始写自定义标签

package com.tags;

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.zking.util.PageBean;

public class PageTag extends BodyTagSupport {

	private static final long serialVersionUID = 5701619331560886989L;
	private PageBean pageBean;
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.write(toHTML());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	
	
	
	
	private String toHTML() {
		StringBuffer sb = new StringBuffer();
		//下一次请求提交到后台的表单html代码拼接
		sb.append("
"); Map paramMap = pageBean.getParamMap(); if(paramMap != null && paramMap.size() > 0) { for(Entry entry : paramMap.entrySet()) { if(!"page".equals(entry.getKey())) { for(String val : entry.getValue()) { sb.append(""); } } } } sb.append(""); sb.append(""); //分页条html代码拼接 //注意一定要空格不然会跟其他标签在一起 sb.append("
"); sb.append(" 每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页  首页  上一页  下一页  尾页    "); sb.append(" href='javascript:skipPage()'>Go"); sb.append("
"); //分页所需要调用的js代码 sb.append(" "); return sb.toString(); } public PageBean getPageBean() { return pageBean; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } }

然后我们建立一个自定义标签库然后进行配置




    
  aaa1.1 core library
  aaacore
  1.1
  c
  /aaa


  

    page

    com.tags.PageTag

    JSP
    

        pageBean

        true

        true
    
  
  





然后我们写web层

package com.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.BookDao;
import com.entity.Book;
import com.zking.util.PageBean;

//controler web
public class BookServlet extends HttpServlet{
	private BookDao bookDao = new BookDao();
	
	
	private static final long serialVersionUID = 2447438096754154253L;


	@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 {
		String bname = req.getParameter("bname");
//		String page = req.getParameter("page");
		Book book = new Book();
		book.setBname(bname);
		PageBean  pageBean = new PageBean();
		pageBean.setRequest(req);
		try {
			//查询出符合条件的某一页的记录数 默认为第一页
			List list = bookDao.list(book, pageBean);
			req.setAttribute("bookList", list);
			req.setAttribute("pagebean", pageBean );
			req.getRequestDispatcher("bookList.jsp").forward(req, resp);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	
}

然后我们进行配置
其中有过滤器的配置
过滤器用于防止中文乱码,然后就是servlet的配置



  Pagebean
  
  
  	bookServlet
  	com.web.BookServlet
  
  
  
  	bookServlet
  	/bookServlet
  
  
  
  
  	encodingFiter
  	com.zking.util.EncodingFiter
  
  
  	encodingFiter
  	/*
  
  
  

这些配置完成后我们就可以在jsp页面进行展示,我们需要调用自己的自定义标签库

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
	
	<%@ taglib prefix="z" uri="/aaa" %>




Insert title here


	

小说目录


书名:
编号 名称 价格
${b.bid} ${b.bname} ${b.price}

需要用到的jar包为:
反射所需要的jar包
commons-beanutils-1.8.0
commons-logging

标签库的jar包
jstl-1.2
standard-1.1.2
mysql 连接mysql的jar包
mysql-connector-java-5.1.44-bin

思路总结:
1.需要分页的实体类
2.PageBean
1.1需要初始化
1.2重载
1.3重要的参数方法
3.通用分页方法
3.1要编写总条数sql
3.2要编写分页sql
4.dao方法继承通用方法
4.1定义sql语句,用上面的判空进行拼接
5.web层
6.自定义标签
6.1编译属性
6.2 自定标签的doStartTag()方法,
7.配置自定义标签
8.配置web层
9.jsp页面展示

你可能感兴趣的:(Java,JSP)