通用分页(上)

通用分页

  • 通用分页核心思路
  • 通用分页案例
  • 总结

通用分页核心思路

通用分页核心思路:将上一次查询请求再发一次,只不过页码变了

通用分页案例

1、先将需要的导入的jar包放到web-inf下面的lib文件中
通用分页(上)_第1张图片
config.properties配置文件:

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#pwd=tiger

#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#user=sa
#pwd=123

#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888

#mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/t243?useUnicode=true&characterEncoding=UTF-8
user=root
pwd=123

这里我用的是最后一个mysql的,用需要用别的数据库的可以将前面的#删除,就可以使用了。

接下来就可以解析配置文件的内容,链接数据库:

package com.zhangsiwen.test.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBAccess {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBAccess.class
					.getResourceAsStream("config.properties");

			Properties properties = new Properties();
			properties.load(is);

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");

			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Statement stmt) {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		close(rs);
		close(stmt);
		close(conn);
	}

	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}

	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.jdbc.Driver".equals(driver);
	}
}

连接之后可以写一个main方法用来测试:

	public static void main(String[] args) {
		Connection conn = DBAccess.getConnection();
		DBAccess.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}

运行结果:
通用分页(上)_第2张图片
处理中文乱码的工具类

package com.zhangsiwen.test.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();
		}
	}

}

判断字符串是否为空

package com.zhangsiwen.test.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.zhangsiwen.test.entity;

import java.io.Serializable;

import com.zhangsiwen.test.util.PinYinUtil;

public class Student implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private int sid;
	private String sname;
	private String sname_pinyin;
	private int age;
	private String remark;
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
		this.sname_pinyin=PinYinUtil.toPinyin(this.sname);
	}
	public String getSname_pinyin() {
		return sname_pinyin;
	}
	public void setSname_pinyin(String sname_pinyin) {
		this.sname_pinyin = sname_pinyin;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	
	public Student() {
		super();
	}
	
	public Student(int sid, String sname, String sname_pinyin, int age, String remark) {
		super();
		this.sid = sid;
		this.sname = sname;
		this.sname_pinyin = sname_pinyin;
		this.age = age;
		this.remark = remark;
	}
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", sname_pinyin=" + sname_pinyin + ", age=" + age
				+ ", remark=" + remark + "]";
	}
}

通用方法的实体类

package com.zhangsiwen.test.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 ParameterMap=new HashMap();

	//专门写一个方法,用来做pageBean的初始化
	public void setRequest(HttpServletRequest request) {
		//page rows  pagination 公开参数  只能做分页
		//从界面获取到分页的参数
		String page=request.getParameter("page");
		String rows=request.getParameter("rows");
		String pagination=request.getParameter("pagination");
		//给参数赋值
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		//获取请求路径
		this.url=request.getContextPath()+request.getServletPath();
		//获取界面传递的参数
		this.ParameterMap=request.getParameterMap();
		
	}
	
	//上一页
	public int getPreviousPage() {
		int previousPage=this.page-1;
		if(0==previousPage) {
			previousPage=1;
		}
		return previousPage;
	}
	
	
	//下一页
	public int getNextPage() {
		int nextPage=this.page+1;
		if(nextPage>getMaxPage()) {
			nextPage=getMaxPage();
		}
		return nextPage;
	}
	
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim())) {
			this.page=Integer.parseInt(page);
		}
	}
	
	
	public String getUrl() {
		return url;
	}


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


	public Map getParameterMap() {
		return ParameterMap;
	}


	public void setParameterMap(Map parameterMap) {
		ParameterMap = parameterMap;
	}


	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim())) {
			this.rows=Integer.parseInt(rows);
		}
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	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);
		}
	}
	
	public PageBean() {
		super();
	}

	public PageBean(int page, int rows, int total, boolean pagination) {
		super();
		this.page = page;
		this.rows = rows;
		this.total = total;
		this.pagination = pagination;
	}
	
	/**
	 * 获得起始记录的下标
	 * @return
	 */
	public int getStartsIndex() {
		
		return (this.page-1)*this.rows;
	}
	
	/**
	 * 获取最大页数
	 * @return
	 */
	public int getMaxPage() {
		int maxPage=this.total/this.rows;
		if(0!=this.total%this.rows) {
			maxPage=maxPage+1;
		}
		return maxPage;
	}
	
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}
}

写一个dao类

package com.zhangsiwen.test.dao;

import java.io.Serializable;
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.sun.javafx.css.Style;
import com.zhangsiwen.test.entity.Student;
import com.zhangsiwen.test.util.DBAccess;
import com.zhangsiwen.test.util.PageBean;
import com.zhangsiwen.test.util.StringUtils;

public class StudentDao extends BaseDao implements Serializable{

	
	private static final long serialVersionUID = 1L;
	
	
	/**
	 * 增加方法
	 * @param student
	 */
	public void add(Student student) {
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="insert into t_student (sname,sname_pinyin,age,remark) value(?,?,?,?)";
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			ps.setString(1,student.getSname());
			ps.setString(2,student.getSname_pinyin());
			ps.setInt(3,student.getAge());
			ps.setString(4,student.getRemark());
			ps.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			DBAccess.close(con,ps, rs);
		}
	}
	
	
	/**
	 * 查询所有 模糊查询
	 * @param student
	 * @return
	 */
	public List find(Student student){
		List stuList=new ArrayList();
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select * from t_student where 1=1";
		if(StringUtils.isNotBlank(student.getSname())){
			//sql+=" and sname like '%"+student.getSname() +"%' ";
			sql+=" and (sname like '%"+student.getSname() +"%' or sname_pinyin like '%"+student.getSname()+"%' )";
		}
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			Student stu=null;
			while(rs.next()) {
				stu=new Student();
				stu.setSid(rs.getInt("sid"));
				stu.setSname(rs.getString("sname"));
				stu.setSname_pinyin(rs.getString("sname_pinyin"));
				stu.setAge(rs.getInt("age"));
				stu.setRemark(rs.getString("remark"));
				stuList.add(stu);
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			DBAccess.close(con,ps, rs);
		}
		return stuList;
	}
	
	public List find(Student student,PageBean pageBean){
		String sql="select * from t_student where 1=1 ";
		if(StringUtils.isNotBlank(student.getSname())){
			//sql+=" and sname like '%"+student.getSname() +"%' ";
			sql+=" and sname like '%"+student.getSname()+"%' or sname_pinyin like '%"+student.getSname()+"%'";
		}
			return this.executeQuery(sql, pageBean, new Callback() {
				@Override
				public List foreach(ResultSet rs) throws SQLException {
					List stuList=new ArrayList();
					Student stu=null;
					while(rs.next()) {
						stu=new Student();
						stu.setSid(rs.getInt("sid"));
						stu.setSname(rs.getString("sname"));
						stu.setSname_pinyin(rs.getString("sname_pinyin"));
						stu.setAge(rs.getInt("age"));
						stu.setRemark(rs.getString("remark"));
						stuList.add(stu);
					}
					return stuList;
				}
			});
	}
	
	
	/**
	 * 专门写一个方法用来拼接查询语句的 统计满足条件的总行数
	 * @param sql 满足条件的sql
	 * @return
	 */
	public String getCountSql(String sql) {
		
		return "select count(*) from ("+sql+")t1 ";
	}
	
	/**
	 * 专门写一个方法用来存储拼接分页的sql
	 * @param sql 查询指定页码并满足条件的sql语句
	 * @param pageBean 助手类
	 * @return
	 */
	public String getPageSql(String sql,PageBean pageBean) {
		
		return sql+"limit "+pageBean.getStartsIndex() +","+pageBean.getRows()+"";
	}
	
	
	
	
	
	
}

写一个junit单元测试测试一下

package com.zhangsiwen.test.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.zhangsiwen.test.entity.Student;
import com.zhangsiwen.test.util.PageBean;

public class StudentDaoTest {
	
	private StudentDao stuDao=new StudentDao();
	private Student stu=null;
	@Before
	public void setUp() throws Exception {
		System.out.println("执行测试方法之前调用,做初始化");
		stu =new Student();
	}

	@After
	public void tearDown() throws Exception {
		System.out.println("执行测试方法之后调用,要来做销毁");
	}

	@Test
	public void testAdd() {
		System.out.println("专门用来测试add的方法");
		for(int i=0;i<50;i++) {
			stu.setSname("张明明"+i);
			stu.setAge(18+i);
			stu.setRemark("abcd"+i);
			stuDao.add(stu);
		}
	}

	@Test
	public void testFind() {
		System.out.println("专门用来测试find的方法");
		stu.setSname("王");
		
		List student=stuDao.find(stu);
		for (Student s : student) {
			System.out.println(s);
		}
			
	}

	
	@Test
	public void testFind2() {
		
		
		PageBean pageBean =new PageBean();
		pageBean.setPage(1);
		pageBean.setRows(10);
		pageBean.setPagination(true);
		stu.setSname("张");
		
		List student=stuDao.find(stu,pageBean);

		System.out.println(pageBean);
		for (Student s : student) {
			System.out.println(s);
		}
			
	}
	
	
	
}

选择运行find2,运行结果
通用分页(上)_第3张图片

总结

这是通用分页的上半部分,下半部分将在下一篇博客,敬请期待!

你可能感兴趣的:(通用分页(上))