一封装的参考
程序员文章站
2022-06-18 08:50:42
...
1. Page.java
package cn.loen.platform.util.page;
import java.util.List;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: loen</p>
*
* @author bright
* @version 1.0
*/
public interface Page {
public static int PAGE_SIZE = 15;
/**
* 是否是首页(第一页),第一页页码为1
*
* @return 首页标识
*/
public boolean isFirstPage();
/**
* 是否是最后一页
*
* @return 末页标识
*/
public boolean isLastPage();
/**
* 是否有下一页
*
* @return 下一页标识
*/
public boolean hasNextPage();
/**
* 是否有上一页
*
* @return 上一页标识
*/
public boolean hasPreviousPage();
/**
* 获取最后一页页码,也就是总页数
*
* @return 最后一页页码
*/
public int getLastPageNumber();
/**
* 当前页包含的数据
*
* @return 当前页数据源
*/
public List getThisPageElements();
public void setThisPageElements(List ls);
/**
* 总的数据条目数量,0表示没有数据
*
* @return 总数量
*/
public int getTotalNumberOfElements();
/**
* 获取当前页的首条数据的行编码
*
* @return 当前页的首条数据的行编码
*/
public int getThisPageFirstElementNumber();
/**
* 获取当前页的末条数据的行编码
*
* @return 当前页的末条数据的行编码
*/
public int getThisPageLastElementNumber();
/**
* 获取下一页编码
*
* @return 下一页编码
*/
public int getNextPageNumber();
/**
* 获取上一页编码
*
* @return 上一页编码
*/
public int getPreviousPageNumber();
/**
* 每一页显示的条目数
*
* @return 每一页显示的条目数
*/
public int getPageSize();
/**
* 当前页的页码
*
* @return 当前页的页码
*/
public int getThisPageNumber();
}
2.PageImp.java
package cn.loen.platform.util.page;
import java.util.List;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: loen</p>
*
* @author bright
* @version 1.0
*/
public class PageImp implements Page {
private List elements;
private int pageSize;
private int pageNumber;
private int totalElements;
/**
* 构建Page对象,完成数据的分页处理
*
* @param elements
* List数据源
* @param totalElements
* 记录总数
* @param pageNumber
* 当前页编码,从1开始,如果传的值为Integer.MAX_VALUE表示获取最后一页。
* 如果你不知道最后一页编码,传Integer.MAX_VALUE即可。如果当前页超过总页数,也表示最后一页。
* 这两种情况将重新更改当前页的页码为最后一页编码。
* @param pageSize
* 每一页显示的条目数
*/
public PageImp(List elements, int totalElements, int pageNumber,
int pageSize) {
this.elements = elements;
this.totalElements = totalElements;
this.pageNumber = pageNumber;
this.pageSize = pageSize;
if (this.pageNumber == Integer.MAX_VALUE ||
this.pageNumber > getLastPageNumber())
this.pageNumber = getLastPageNumber();
}
public boolean isFirstPage() {
return getThisPageNumber() == 1;
}
public boolean isLastPage() {
return getThisPageNumber() >= getLastPageNumber();
}
public boolean hasNextPage() {
return getLastPageNumber() > getThisPageNumber();
}
public boolean hasPreviousPage() {
return getThisPageNumber() > 1;
}
public int getLastPageNumber() {
return totalElements % this.pageSize == 0 ? totalElements
/ this.pageSize : totalElements / this.pageSize + 1;
}
public List getThisPageElements() {
return elements;
}
public int getTotalNumberOfElements() {
return totalElements;
}
public int getThisPageFirstElementNumber() {
return (getThisPageNumber() - 1) * getPageSize() + 1;
}
public int getThisPageLastElementNumber() {
int fullPage = getThisPageFirstElementNumber() + getPageSize() - 1;
return getTotalNumberOfElements() < fullPage ? getTotalNumberOfElements()
: fullPage;
}
public int getNextPageNumber() {
int nextPage = getThisPageNumber() + 1;
return nextPage < getLastPageNumber() ? nextPage : getLastPageNumber();
}
public int getPreviousPageNumber() {
int previousPage = getThisPageNumber() - 1;
return 1 < previousPage ? previousPage : 1;
}
public int getPageSize() {
return pageSize;
}
public int getThisPageNumber() {
return pageNumber;
}
public void setThisPageElements(List ls){
elements = ls;
}
}
3.QueryHandler .java For Hibernate HQL查询
package cn.loen.platform.util.query;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import cn.loen.platform.util.page.PageImp;
import cn.loen.platform.util.page.Page;
import cn.loen.platform.common.BaseDAO;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: loen</p>
*
* @author bright
* @version 1.0
*/
public class QueryHandler {
private static QueryHandler instance = new QueryHandler();
public static QueryHandler instance() {
return instance;
}
private QueryHandler() {
}
/**
* 得到记录总数
* @param hql String
* @param values Object[]
* @return int
* @throws HibernateException
*/
public int getTotalCount(String hql, Object[] values) throws
HibernateException {
Integer count = new Integer(0);
/**
* 去掉排序
*/
int sql_orderby = hql.indexOf("order by");
if(sql_orderby>0)
hql = hql.substring(0,sql_orderby);
/**
* 去掉条件
*/
hql=(hql.split("from"))[1];
StringBuffer countStr = new StringBuffer("select count(*) from");
countStr.append(hql);
Session session = null;
List list = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(countStr.toString());
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
list = query.list();
if (!list.isEmpty())
count = (Integer) list.get(0);
return count.intValue();
} finally {
session.close();
}
}
/**
* 按页数得到需要记录数
* @param hql String
* @param values Object[]
* @param pageNo int
* @param pageSize int
* @return List
* @throws HibernateException
*/
public List query(String hql, Object[] values, int pageNo, int pageSize) throws
HibernateException {
List list = null;
Session session = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(hql);
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
query.setFirstResult((pageNo - 1) * pageSize);
query.setMaxResults(pageSize);
return query.list();
} finally {
session.close();
}
}
/**
* 取得全部记录
* @param hql String
* @param values Object[]
* @return List
* @throws HibernateException
*/
public List queryAll(String hql, Object[] values) throws HibernateException {
List list = null;
Session session = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(hql);
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
return query.list();
} finally {
session.close();
}
}
public Page queryByPage(int pageNumber, int pageSize, Object[] values,
String hql) {
Page page = null;
try {
int total = QueryHandler.instance().getTotalCount(hql, values);
List querylist = QueryHandler.instance().query(hql, values,
pageNumber, pageSize);
page = new PageImp(querylist, total, pageNumber, pageSize);
} catch (Exception e) {
e.printStackTrace();
}
return page;
}
}
4.1 SQLQueryHandler .java sql语法查询处理
package cn.loen.platform.util.query;
import org.hibernate.Session;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import cn.loen.platform.common.BaseDAO;
import cn.loen.platform.util.page.Page;
import cn.loen.platform.util.page.PageImp;
import cn.loen.platform.util.DateUtil;
import cn.loen.golf.course.po.Course;
import cn.loen.golf.course.action.CourseSearchActionForm;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: loen</p>
*
* @author bright
* @version 1.0
*/
public class SQLQueryHandler {
private static SQLQueryHandler handler = new SQLQueryHandler();
public static SQLQueryHandler instance() {
return handler;
}
private SQLQueryHandler() {
}
/**
* 分页查询
* @param pageNumber int
* @param pageSize int
* @param values Object[]
* @param sql String
* @param helper IResultSetHelper
* @return Page
*/
public Page queryByPage(int pageNumber, int pageSize, Object[] values,
String sql, IResultSetHelper helper) {
Page page = null;
Session session = null;
Connection con = null;
try {
session = BaseDAO.getSession();
con = session.connection();//通过Hibernate获得Connection jdbc自己写
int total = getTotalCount(con, sql, values);
List querylist = query(con, sql, values, pageNumber, pageSize,
helper);
page = new PageImp(querylist, total, pageNumber, pageSize);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return page;
}
/**
* 取记录总数
* @param con Connection
* @param sql String
* @param values Object[]
* @return int
* @throws SQLException
*/
private int getTotalCount(Connection con, String sql, Object[] values) throws
SQLException {
System.out.println(sql);
int count = 0;
String[] sql1 = sql.split("from");//Mysql不支持count子查询 故重新构造
sql = sql1[1];
StringBuffer countStr = new StringBuffer(
"select count(*) as rowcount from");
// StringBuffer countStr = new StringBuffer(
// "select count(*) as rowcount from (");
int sql_orderby = sql.indexOf("order by");
if (sql_orderby > 0) {
countStr.append(sql.substring(0, sql_orderby));
} else {
countStr.append(sql);
}
// countStr.append(")");
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(countStr.toString());
System.out.println(countStr);
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof java.util.Date) {
values[i] = DateUtil.getSqlDate((java.util.Date) values[i]);
}
//ps.setObject(i + 1, values[i]);
ps.setObject(2 * (i + 1) - 1, values[i]);
ps.setObject(2 * (i + 1), values[i]);
}
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt("rowcount");
}
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
}
return count;
}
/**
* Oracle的查询记录集方法
* @param con Connection
* @param sql String
* @param values Object[]
* @param pageNo int
* @param pageSize int
* @param helper IResultSetHelper
* @return List
* @throws SQLException
*/
private List oracleQuery(Connection con, String sql, Object[] values,
int pageNo,
int pageSize, IResultSetHelper helper) throws
SQLException {
List list = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
StringBuffer pageStr = new StringBuffer();
pageStr.append(
"select * from ( select row_.*, rownum rownum_ from ( ");
pageStr.append(sql);
pageStr.append(" ) row_ where rownum <= ");
pageStr.append(pageSize * pageNo);
pageStr.append(" ) where rownum_ > ");
pageStr.append(pageSize * (pageNo - 1));
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof java.util.Date) {//把java日期转为sql日期类型
values[i] = DateUtil.getSqlDate((java.util.Date) values[i]);
}
//ps.setObject(i + 1, values[i]);
ps.setObject(2 * (i + 1) - 1, values[i]);
ps.setObject(2 * (i + 1), values[i]);
}
rs = ps.executeQuery();
list = helper.prepareListFromResultSet(rs);
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
}
return list;
}
/**
* 按取得查询结果记录Mysql方法 其它数据库方法另外写
* @param con Connection
* @param sql String
* @param values Object[]
* @param pageNo int
* @param pageSize int
* @param helper IResultSetHelper
* @return List
* @throws SQLException
*/
private List query(Connection con, String sql, Object[] values, int pageNo,
int pageSize, IResultSetHelper helper) throws
SQLException {
List list = null;
String myPageSQL = sql + " limit " + pageSize * (pageNo - 1) + "," +
pageSize * pageNo; //关键代码
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(myPageSQL);
System.out.println(myPageSQL);
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof java.util.Date) {
values[i] = DateUtil.getSqlDate((java.util.Date) values[i]);
}
//ps.setObject(i + 1, values[i]); 此中方法在servlet里面控制查询参数调用
ps.setObject(2 * (i + 1) - 1, values[i]); //利用sql语句控制查询条件调用
ps.setObject(2 * (i + 1), values[i]);
}
rs = ps.executeQuery();
list = helper.prepareListFromResultSet(rs);
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
}
return list;
}
/**
* 测试
* @param args String[]
*/
public static void main(String[] args) {
BaseDAO.initialize();
SQLQueryHandler handler = SQLQueryHandler.handler;
int pageNumber = 1;
int pageSize = 5;
Object[] values = {"", "434", ""};
String hql = "select c.courseid,c.coursename,c.provincecode,c.citycode from gf_course as c where c.isdisable='" +
Course.DISABLE + "' and (?='' or coursename like CONCAT('%',?,'%')) and (?='' or provincecode=?) and (?='' or citycode=?)";
Page p = handler.queryCourseByPage(pageNumber, pageSize, values, hql);
System.out.println(p.getPageSize());
}
/**
* Service调用方法测试
* @param pageNumber int
* @param pageSize int
* @param values Object[]
* @param hql String
* @return Page
*/
private Page queryCourseByPage(int pageNumber, int pageSize,
Object[] values, String hql) {
final List items = new ArrayList();
return SQLQueryHandler.instance().queryByPage(pageNumber, pageSize,
values, hql, new IResultSetHelper() {
//2.把List封装到Page
public List prepareListFromResultSet(ResultSet rs) throws
SQLException {
//1.把rs封装到List
while (rs.next()) {
List list = new ArrayList();
list.add("1111");
list.add("222");
CourseSearchActionForm cs = new CourseSearchActionForm();
cs.setCoursename(rs.getString("coursename"));
cs.setProvincecode(rs.getString("provincecode"));
cs.setCitycode(rs.getString("citycode"));
cs.setCourseid(rs.getString("courseid"));
cs.setPriceList(list);
items.add(cs);
}
return items;
}
});
}
}
4.2 IResultSetHelper.java 具体实现见上个类的测试调用代码
package cn.loen.platform.util.query;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface IResultSetHelper {
/**
* SQL查询的结果集转化成LIST
* @param rs ResultSet
* @return List
* @throws SQLException
*/
public List prepareListFromResultSet(ResultSet rs) throws SQLException;
}
5.Serivce调用
public class CourseService implements ICourseService {
public CourseService() {
}
/**
* 根据模糊球场名,球洞,省份,城市代码来查询球场以及价格信息
* @return Page
*/
public Page findCoursesPricesByuser(int pageNumber, int pageSize,
Object[] values) throws
BusinessException {
String hql = "select c.courseid,c.coursename,c.provincecode,c.citycode from gf_course as c where c.isdisable='" +
Course.DISABLE + "' and (?='' or coursename like CONCAT('%',?,'%')) and (?='' or provincecode=?) and (?='' or citycode=?)";
final List items = new ArrayList();
try {
return SQLQueryHandler.instance().queryByPage(pageNumber,
pageSize,
values, hql, new IResultSetHelper() {
public List prepareListFromResultSet(ResultSet rs) throws
SQLException {
CourseService service = new CourseService();
while (rs.next()) {
List list = service.findPricesByCourseid(rs.
getString("courseid"));
CourseSearchActionForm cs = new
CourseSearchActionForm();
cs.setCoursename(rs.getString("coursename"));
cs.setProvincecode(rs.getString("provincecode"));
cs.setCitycode(rs.getString("citycode"));
cs.setCourseid(rs.getString("courseid"));
cs.setPriceList(list);
items.add(cs);
}
return items;
}
});
} catch (SQLException ex) {
throw new BusinessException("数据库异常!!");
}
}
/**
* jdbc查询 通过球场id查询详细价格列表
* @param courseid String
* @return List
*/
private List findPricesByCourseid(String courseid) throws SQLException {
ResultSet rs = getICourseDAO().findPricesByCourseid(courseid);
List li = new ArrayList();
while (rs.next()) {
CoursePrice cp = new CoursePrice();
cp.setWkpriceid(rs.getString("wkpriceid"));
cp.setDaterule(rs.getString("daterule"));
cp.setSaleprice(rs.getLong("saleprice"));
cp.setLoenprice(rs.getLong("loenprice"));
cp.setPricememo(rs.getString("pricememo"));
cp.setHoles(rs.getInt("holes"));
li.add(cp);
}
return li;
}
}
6.Servlet调用
package cn.loen.golf.course.action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import cn.loen.platform.security.ProxyService;
import cn.loen.golf.course.ICourseService;
import java.util.List;
import cn.loen.platform.common.BusinessException;
import cn.loen.platform.util.page.Page;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;
public class CourseSearchAction extends Action {
private int pageNumber = 1;
private int pageSize = 5;
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
BusinessException, Exception {
CourseSearchActionForm courseSearchForm = (CourseSearchActionForm)
form;
HttpSession session = request.getSession(true);
String pageNumStr = request.getParameter("pageNumber");
if (pageNumStr == null) {//用户查询 没分页请求 默认显示第一页
pageNumStr = "1";
session.setAttribute("courseSearchForm",courseSearchForm); //把用户的查询条件封装到Session
}
else{
//用户分页请求
if(session.getAttribute("courseSearchForm")!=null)//防止用户乱添加参数
courseSearchForm = (CourseSearchActionForm)session.getAttribute("courseSearchForm"); //取得查询条件
}
pageNumber = Integer.parseInt(pageNumStr);
List list = new ArrayList();
list.add(courseSearchForm.getCoursename());
list.add(courseSearchForm.getProvincecode());
list.add(courseSearchForm.getCitycode());
Object[] object = list.toArray();//添加查询条件 注意Form需要重写reset()方法 把所有null转为"";
Page page = getICourseService().findCoursesPricesByuser(pageNumber,
pageSize, object);
request.setAttribute("Page", page);
String path = request.getRequestURI();//取得Action路径
request.setAttribute("myPageURL", path + "?");
return mapping.findForward("success");
}
private ICourseService getICourseService() {
return (ICourseService) ProxyService.
getBusinessService(
"CourseService");
}
}
7.Jsp页面
<%@page contentType="text/html;charset=gb2312" language="java" import="java.util.*,cn.loen.golf.course.po.*,cn.loen.golf.course.action.*"%>
<%@ page import="cn.loen.platform.util.page.Page"%>
<%@ include file="/common/taglibs.jsp" %>
<html:html lang="true">
<head>
<%@ include file="/common/meta.jsp" %>
<link href="/css/admin.css" type="text/css" rel=stylesheet>
</head>
<body>
<center>
<%@ include file="/common/message.jsp" %>
<br>
<html:form action="/golf/courseSearchAction.do">
<table width="394" border="1" align="center">
<tr>
<td width="65">球场名:</td>
<td width="181"><html:text property="coursename"/></td>
<td width="43">省份</td>
<td width="77"><html:text property="provincecode"/></td>
</tr>
<tr>
<td>xx:</td>
<td></td>
<td>城市</td>
<td><html:text property="citycode"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="提交" /></td>
<td> </td>
<td> </td>
</tr>
</table>
</html:form>
<br>
<table width="745" border="1" align="center">
${Page}
<%
Page datapage = (Page)request.getAttribute("Page");
List dataList = new ArrayList();//数据
int dataNum = 0;
if(datapage!=null){
dataList = datapage.getThisPageElements();
dataNum = dataList.size();
}
for(int i= 0;i < dataNum;i++){
CourseSearchActionForm cform = (CourseSearchActionForm)dataList.get(i);
List list = cform.getPriceList();
int size = list.size();
%>
<tr>
<td width="39" rowspan="<%=size+2%>">名称:<a href="/golf/admin/course/detailCourse.do?courseid=<%=cform.getCourseid()%>"><%=cform.getCoursename()%></a></td>
<td height="24" colspan="5" bgcolor="#FFCCCC">省份:<%=cform.getProvincecode()%></td>
</tr>
<tr>
<td width="54">价格类型</td>
<td width="61">市场价</td>
<td width="39">罗恩价</td>
<td width="54">球洞</td>
<td width="54">说明</td>
</tr>
<%for(int n=0;n<list.size();n++){
CoursePrice cp = (CoursePrice)list.get(n);
%>
<tr>
<td><%=cp.getDaterule()%></td>
<td><%=cp.getSaleprice()%></td>
<td><%=cp.getLoenprice()%></td>
<td><%=cp.getHoles()%></td>
<td><%=cp.getPricememo()%></td>
</tr>
<%}}%>
</table>
<jsp:include page="/platform/common/pageBar.jsp" flush="false" />
</body>
</html:html>
7.pageBar.jsp 控制条
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.util.*"%>
<%@ page import="cn.loen.platform.util.page.Page"%>
<%
Page myPage = (Page)request.getAttribute("Page");
int lastPageNumber = 0;//总页数
int nextPageNumber = 0;//下页
int pageSize = 0;//每页记录数
int previoutPageNumber = 0;//上页
List orderlist = new ArrayList();//数据
int firstElement = 0;//当前第一条
int lastElement = 0;//当前最后一条
int pageNum = 0;//当前第几页
int totalElement = 0;//总记录数
if (myPage != null){
lastPageNumber = myPage.getLastPageNumber();//总页数
nextPageNumber = myPage.getNextPageNumber();//下页
pageSize = myPage.getPageSize();//每页记录数
previoutPageNumber = myPage.getPreviousPageNumber();//上页
orderlist = myPage.getThisPageElements();//数据
firstElement = myPage.getThisPageFirstElementNumber();//当前第一条
lastElement = myPage.getThisPageLastElementNumber();//当前最后一条
pageNum = myPage.getThisPageNumber();//当前第几页
totalElement = myPage.getTotalNumberOfElements();//总记录数
}
String pageURL = (String)request.getAttribute("myPageURL");
%>
<table width="100%" border="0" align="center">
<tr>
<td><span class="font">共<%=totalElement%>条/每页<%=pageSize%>条 第<%=pageNum%>页/共<%=lastPageNumber%>页</span></td>
<td>
<div align="right" class="font">[<a href="javascript:gotoPage(1)">首页</a>][<a href="javascript:gotoPage(<%=previoutPageNumber%>)">上一页</a>][<a href="javascript:gotoPage(<%=nextPageNumber%>)">下一页</a>][<a href="javascript:gotoPage(<%=lastPageNumber%>)">末页</a>]
转第
<select name="jump" onchange="jumpPage(this)">
<%for (int i = 1; i <= lastPageNumber; i++) {
if (i == pageNum) {%>
<option selected value="<%=i%>"><%=i%></option>
<%}
else{%>
<option value="<%=i%>"><%=i%></option>
<%}
}%>
</select>
页
</div></td>
</tr>
</table>
<SCRIPT LANGUAGE="JavaScript" type="">
function jumpPage(selObj){
window.location.href="<%=pageURL%>&pageNumber="+selObj.options[selObj.selectedIndex].value;
}
function gotoPage(pageNumber){
window.location.href="<%=pageURL%>&pageNumber="+pageNumber;
}
</SCRIPT>
上一篇: 大写金额转换成阿拉伯数字金额
下一篇: 一个程序员的爱情表白书