J2ee通用分页一

通用分页(一)

  • util辅助文件
    • DBHelper
    • StringUtils
    • EncodingFilter
    • config.properties
  • Dao包和Biz层
    • Dao包文件
    • baseDao含内部接口
      • IBookDao接口
      • BookDao类
    • Biz层
      • IBookBiz接口
      • BookBiz类
  • 总结

util辅助文件

DBHelper

我这里有乱码,但是不影响,要设置一下字符编码(utf-8)

package com.rong.book.utils;

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 DBHelper {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 闈欐�佸潡鎵ц涓�娆★紝鍔犺浇 椹卞姩涓�娆�
		try {
			InputStream is = DBHelper.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);
	}

	public static void main(String[] args) {
		Connection conn = DBHelper.getConnection();
		DBHelper.close(conn);
		System.out.println("isOracle锛�" + isOracle());
		System.out.println("isSQLServer锛�" + isSQLServer());
		System.out.println("isMysql锛�" + isMysql());
		System.out.println("鏁版嵁搴撹繛鎺�(鍏抽棴)鎴愬姛");
	}
}

StringUtils

package com.rong.book.utils;

public class StringUtils {
	// 绉佹湁鐨勬瀯閫犳柟娉曪紝淇濇姢姝ょ被涓嶈兘鍦ㄥ閮ㄥ疄渚嬪寲
	private StringUtils() {
	}

	/**
	 * 濡傛灉瀛楃涓茬瓑浜巒ull鎴栧幓绌烘牸鍚庣瓑浜�""锛屽垯杩斿洖true锛屽惁鍒欒繑鍥瀎alse
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 濡傛灉瀛楃涓蹭笉绛変簬null鎴栧幓绌烘牸鍚庝笉绛変簬""锛屽垯杩斿洖true锛屽惁鍒欒繑鍥瀎alse
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

EncodingFilter

package com.rong.book.utils;

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 EncodingFilter implements Filter {

	private String encoding = "UTF-8";// 榛樿瀛楃闆�

	public EncodingFilter() {
		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();// 淇濆瓨鎵�鏈夊弬鏁板悕=鍙傛暟鍊�(鏁扮粍)鐨凪ap闆嗗悎
			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();
		}
	}

}

config.properties

用哪个数据库就把那个放出来,这里我用的是mysql,(注意改参数)

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

#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://47.100.191.44:3307/xiao?useUnicode=true&characterEncoding=UTF-8
user=root
pwd=123456

Dao包和Biz层

Dao包文件

baseDao含内部接口

最好用泛型

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> {
	
	/**
	 * 内部接口 专门用来遍历rs结果集
	 * @author Administrator
	 *
	 */
	public static interface CallBack<T> {
		public List<T> forEachRs(ResultSet rs) throws SQLException;
	}
	
	public List<K> exectueQuery(String sql,PageBean pageBean,CallBack 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(*) 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;
	}
}

IBookDao接口

package com.rong.book.dao;

import java.util.List;

import com.rong.book.entity.Book;

public interface IBookDao {

	public void addBook(Book  book);
	
	public List<Book> listBook(Book book);
	
}

BookDao类

一定要继承basedao不然下面方法用不了内部接口,我因为这个错误也是耗挺长时间

package com.rong.book.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.rong.book.base.BaseDao;
import com.rong.book.entity.Book;
import com.rong.book.utils.DBHelper;
import com.rong.book.utils.PageBean;
import com.rong.book.utils.StringUtils;

public class BookDao extends BaseDao<Book> implements IBookDao {

	Connection con=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	
	@Override
	public void addBook(Book book) {
		String sql="INSERT INTO book(bname,price)VALUES(?,?)";
		try {
			con=DBHelper.getConnection();
			ps=con.prepareStatement(sql);
			ps.setString(1, book.getBname());
			ps.setFloat(2, book.getPrice());
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHelper.close(con, ps, rs);
		}
	}

	@Override
	public List<Book> listBook(Book book) {
		List<Book> ls=new ArrayList<Book>();
		String sql="SELECT bid,bname,price FROM book WHERE 1=1";
		if(StringUtils.isNotBlank(book.getBname())) {
			sql += " AND bname LIKE '%"+book.getBname()+"%'";
		}
		try {
			con=DBHelper.getConnection();
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			Book b=null;
			while(rs.next()) {
				b=new Book();
				b.setBid(rs.getInt(1));
				b.setBname(rs.getString(2));
				b.setPrice(rs.getFloat(3));
				ls.add(b);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHelper.close(con, ps, rs);
		}
		return ls;
	}
	
	public List<Book> listBook1(Book book,PageBean pageBean)  {
		String sql = "SELECT bid,bname,price FROM book WHERE 1=1";
		if(StringUtils.isNotBlank(book.getBname())) {
			sql += " AND book_name 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;
			}
		});
	}
	
}

Biz层

biz层其实就是调用一下dao层其实差不多,在biz类里调用一下dao类

IBookBiz接口

package com.rong.book.biz;

import java.util.List;

import com.rong.book.entity.Book;
import com.rong.book.utils.PageBean;

public interface IBookBiz {

	public void addBook(Book book);
	
	public List<Book> listBook(Book book,PageBean pageBean);
	
}

BookBiz类

package com.rong.book.biz;

import java.util.List;

import com.rong.book.dao.BookDao;
import com.rong.book.dao.IBookDao;
import com.rong.book.entity.Book;
import com.rong.book.utils.PageBean;

public class BookBiz implements IBookBiz {
	
	private IBookDao bookdao = new BookDao();
	@Override
	public void addBook(Book book) {
		bookdao.addBook(book);
		

	}

	@Override
	public List<Book> listBook(Book book,PageBean pageBean) {
		return bookdao.listBook(book);
	}

}

总结

这里是为后面的jsp页面做底层准备工作,所以出错了页面是没有数据甚至报错的,要注意细节

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