javaee導測(ssh框架)分頁 mysql資料庫(帶條件查詢)

航天飛哥發表於2017-02-07

原理圖


jsp原理圖


一,工具類 com.itheima.crm.page

PageBean.java + PageHibernateCallback.java

PageBean.java
package com.itheima.crm.page;

import java.util.List;

public class PageBean<T> {
	
	//必選項
	private int pageNum;		//第幾頁(當前頁)
	private int pageSize;		//每頁顯示個數(固定值)
	private int totalRecord;	//總記錄數(查詢資料庫)--注意條件
	
	//計算項
	private int startIndex;		//開始索引(計算)
	private int totalPage;		//總分頁數(計算)
	
	//資料
	private List<T> data;		//分頁資料
	
	//動態顯示條
	private int start ;
	private int end ;
	
	
	public PageBean(int pageNum, int pageSize, int totalRecord) {
		super();
		this.pageNum = pageNum;
		this.pageSize = pageSize;
		this.totalRecord = totalRecord;
		
		// 計算
		//1 開始索引
		this.startIndex = (this.pageNum - 1) * this.pageSize;
		
		//2 總分頁數
		this.totalPage = (this.totalRecord + this.pageSize - 1) / this.pageSize;
		
		
		//3 動態顯示條
		//3.1 初始化資料 -- 顯示10個分頁
		this.start = 1;
		this.end = 10;
		
		//3.2 初始資料  , totalPage = 4
		if(this.totalPage <= 10){
			this.end = this.totalPage;
		} else {
			// totalPage =  22 
			
			//3.3 當前頁 前4後5
			this.start = this.pageNum - 4;
			this.end = this.pageNum + 5;
			
			// *  pageNum = 1
			if(this.start < 1){
				this.start = 1;
				this.end = 10;
			}
			
			// * pageNum = 22
			if(this.end > this.totalPage){
				this.end = this.totalPage;
				this.start = this.totalPage - 9;
			}
			
			
		}
		
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalRecord() {
		return totalRecord;
	}

	public void setTotalRecord(int totalRecord) {
		this.totalRecord = totalRecord;
	}

	public int getStartIndex() {
		return startIndex;
	}

	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public List<T> getData() {
		return data;
	}

	public void setData(List<T> data) {
		this.data = data;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}
	
	

}

package com.itheima.crm.page;

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

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

public class PageHibernateCallback<T> implements HibernateCallback<List<T>> {

	private String hql;
	private Object[] params;
	private int startIndex;
	private int pageSize;
	
	public PageHibernateCallback<T> setHql(String hql) {
		this.hql = hql;
		return this;
	}

	public  PageHibernateCallback<T> setParams(Object[] params) {
		this.params = params;
		return this;
	}

	public  PageHibernateCallback<T> setStartIndex(int startIndex) {
		this.startIndex = startIndex;
		return this;
	}
	public  PageHibernateCallback<T> setPageSize(int pageSize) {
		this.pageSize = pageSize;
		return this;
	}



	public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
		//1 通過hql語句,獲得Query物件
		Query queryObject = session.createQuery(hql);
		//2 條件設定
		for (int i = 0; i < params.length; i++) {
			queryObject.setParameter(i, params[i]);
		}
		//3 分頁
		queryObject.setFirstResult(startIndex);
		queryObject.setMaxResults(pageSize);
		//4 查詢所有
		return queryObject.list();
	}

}


二, dao層 介面 com.itheima.crm.coursetype.dao

/**
	 * 分頁,查詢總記錄數
	 * 
	 * @param condition
	 * @param params
	 * @return
	 */
	public int getTotalRecord(String condition, Object[] params);

	/**
	 * 分頁,查詢結果
	 * 
	 * @param condition
	 *            條件
	 * @param params
	 *            條件實際引數
	 * @param startIndex
	 *            開始索引
	 * @param pageSize
	 *            每頁顯示個數
	 * @return
	 */
	public List<CrmCourseType> findAll(String condition, Object[] params,
			int startIndex, int pageSize);

,dao層實現類

com.itheima.crm.coursetype.dao.impl

	public int getTotalRecord(String condition, Object[] params) {
		String hql = "select count(c) from CrmCourseType c where 1=1 "
				+ condition;
		List<Long> list = this.getHibernateTemplate().find(hql, params);
		return list.get(0).intValue();
	}

	public List<CrmCourseType> findAll(String condition, Object[] params,
			int startIndex, int pageSize) {
		String hql = "from CrmCourseType where 1=1 " + condition;
		return this.getHibernateTemplate().execute(
				new PageHibernateCallback<CrmCourseType>().setHql(hql)
						.setParams(params).setPageSize(pageSize)
						.setStartIndex(startIndex));
	}

四,service層介面

com.itheima.crm.coursetype.service

/**
	 * 分頁 + 條件查詢
	 * 
	 * @param courseType
	 *            條件
	 * @param pageNum
	 *            當前頁
	 * @param pageSize
	 *            每頁顯示個數
	 * @return
	 */
	public PageBean<CrmCourseType> findAll(CrmCourseType courseType,
			int pageNum, int pageSize);

五,service層實現類

com.itheima.crm.coursetype.service.impl

public PageBean<CrmCourseType> findAll(CrmCourseType courseType,
			int pageNum, int pageSize) {
		// 1 條件查詢
		// 1.1 拼湊查詢條件
		StringBuilder builder = new StringBuilder();
		// 1.2 拼湊實際引數 , 可以重複,順序 --> List
		List<Object> paramsList = new ArrayList<Object>();

		// 2 過濾條件
		// 2.1 課程類別
		if (StringUtils.isNotBlank(courseType.getCourseName())) {
			builder.append(" and courseName like ?");
			paramsList.add("%" + courseType.getCourseName() + "%");
		}
		// 2.2 課程簡介
		if (StringUtils.isNotBlank(courseType.getRemark())) {
			builder.append(" and remark like ?");
			paramsList.add("%" + courseType.getRemark() + "%");
		}
		// 2.3 總學時:
		if (StringUtils.isNotBlank(courseType.getTotalStart())) {
			builder.append(" and total >= ?");
			paramsList.add(Integer.parseInt(courseType.getTotalStart()));
		}
		if (StringUtils.isNotBlank(courseType.getTotalEnd())) {
			builder.append(" and total <= ?");
			paramsList.add(Integer.parseInt(courseType.getTotalEnd()));
		}
		// 2.4課程費用
		if (StringUtils.isNotBlank(courseType.getCourseCostStart())) {
			builder.append(" and courseCost >= ?");
			paramsList.add(Double.parseDouble(courseType.getCourseCostStart()));
		}
		if (StringUtils.isNotBlank(courseType.getCourseCostEnd())) {
			builder.append(" and courseCost <= ?");
			paramsList.add(Double.parseDouble(courseType.getCourseCostEnd()));
		}

		// 3 使用
		// 條件 , 格式:" and ..? and ..."
		String condition = builder.toString();
		// 實際引數
		Object[] params = paramsList.toArray();

		// //
		// 2分頁
		// 2.1 總記錄數
		int totalRecord = this.courseTypeDao.getTotalRecord(condition, params);
		// 2.2 建立物件
		PageBean<CrmCourseType> pageBean = new PageBean<CrmCourseType>(pageNum,
				pageSize, totalRecord);
		// 2.3 分頁資料
		List<CrmCourseType> data = this.courseTypeDao.findAll(condition,
				params, pageBean.getStartIndex(), pageBean.getPageSize());
		pageBean.setData(data);

		return pageBean;
	}

六,action層

com.itheima.crm.coursetype.web.action

// 分頁資料
	private int pageNum = 1;

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	private int pageSize = 2; // 固定值

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	// 
	/**
	 * 查詢所有
	 * 
	 * @return
	 */
	public String findAll() {
		/*
		 * 1簡單查詢 List<CrmCourseType> allCourseType =
		 * this.courseTypeService.findAll(); // * 查詢結果存在值棧 , jsp 通過“#key”獲得
		 * ActionContext.getContext().put("allCourseType", allCourseType);
		 */

		/*
		 * 2 條件查詢 List<CrmCourseType> allCourseType =
		 * this.courseTypeService.findAll(courseType);
		 * ActionContext.getContext().put("allCourseType", allCourseType);
		 */

		// 3 分頁 + 條件
		PageBean<CrmCourseType> pageBean = this.courseTypeService.findAll(
				courseType, pageNum, pageSize);
		ActionContext.getContext().put("pageBean", pageBean);

		return "findAll";
	}

七,struts.xml檔案的配置

<package name="cou" namespace="/" extends="common">
		<action name="courseTypeAction_*"
			class="com.itheima.crm.coursetype.web.action.CourseTypeAction"
			method="{1}">
			<result name="findAll">/WEB-INF/pages/coursetype/listCourse.jsp</result>
		</action>
</package>


八,spring檔案的配置

	<bean id="courseTypeDao" class="com.itheima.crm.coursetype.dao.impl.CourseTypeDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="courseTypeService" class="com.itheima.crm.coursetype.service.impl.CourseTypeServiceImpl">
		<property name="courseTypeDao" ref="courseTypeDao"></property>
	</bean>

九,jsp檔案

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>

<link href="${pageContext.request.contextPath}/css/sys.css" type="text/css" rel="stylesheet" />

</head>

<body >
 <table border="0" cellspacing="0" cellpadding="0" width="100%">
  <tr>
    <td class="topg"></td>
  </tr>
</table>

<table border="0" cellspacing="0" cellpadding="0"  class="wukuang"width="100%">
  <tr>
    <td width="1%"><img src="${pageContext.request.contextPath}/images/tleft.gif"/></td>
    <td width="39%" align="left">[課程類別]</td>
   
    <td width="57%"align="right">
		<a href="javascript:void(0)" οnclick="javascript:document.forms[0].submit();">
			<img src="${pageContext.request.contextPath}/images/button/gaojichaxun.gif" />
		</a>      
    	<%--編輯前:新增類別 --%>
    	<a href="${pageContext.request.contextPath}/courseTypeAction_addOrEditUI">
	       	<img src="${pageContext.request.contextPath}/images/button/tianjia.gif" />
    	</a>
    </td>
    <td width="3%" align="right"><img src="${pageContext.request.contextPath}/images/tright.gif"/></td>
  </tr>
</table>


<%--條件查詢 start --%>

<s:form namespace="/" action="courseTypeAction_findAll">
	<%--隱藏域,存放當前頁 --%>
	<s:hidden id="pageNum" name="pageNum" value="1"></s:hidden>
	<table width="88%" border="0" class="emp_table" style="width:80%;">
	  <tr>
	    <td width="10%">課程類別:</td>
	    <td><s:textfield name="courseName" size="30"></s:textfield></td>
	  </tr>
	  <tr>
	    <td >課程簡介:</td>
	    <td ><s:textfield name="remark" size="30" ></s:textfield></td>
	  </tr>
	  <tr>  
	    <td >總學時:</td>
	    <td >
	    	<s:textfield name="totalStart" size="12"></s:textfield>  
	    	至  
	    	<s:textfield name="totalEnd" size="12"></s:textfield>
	    </td>
	  </tr>
	  <tr>
	    <td>課程費用:</td>
	    <td >
	    	<s:textfield name="courseCostStart" size="12"></s:textfield> 
	    	至 
	    	<s:textfield name="courseCostEnd" size="12"></s:textfield> 
	    </td>
	  </tr>
	</table>
</s:form>

<%--條件查詢 end --%>

<table border="0" cellspacing="0" cellpadding="0" style="margin-top:5px;">
  <tr>
    <td ><img src="${pageContext.request.contextPath}/images/result.gif"/></td>
  </tr>
</table>
<table width="97%" border="1" >
  
  <tr class="henglan" style="font-weight:bold;">
    <td width="14%" align="center">名稱</td>
    <td width="33%" align="center">簡介</td>
    <td width="13%" align="center">總學時</td>
    <td width="18%" align="center">收費標準</td>
	<td width="11%" align="center">編輯</td>
  </tr>
  <%--資料展示,單行:tabtd1;雙行:tabtd2 --%>
  <s:iterator value="#pageBean.data" var="vs">
   <tr class="<s:property value="#vs.even ? tabtd1 : tabtd2" />">

	    <td align="center"><s:property value="#vs.courseName" /> </td>
	    <td align="center"> <s:property value="#vs.remark" /></td>
	    <td align="center"><s:property value="#vs.total" /></td>
	    <td align="center"><s:property value="#vs.courseCost" /></td>
	  	<td width="11%" align="center">
	  		
	  		<s:a action="courseTypeAction_addOrEditUI" namespace="/">
	  			<s:param name="courseTypeId"  value="courseTypeId"></s:param>
	  			<img src="${pageContext.request.contextPath}/images/button/modify.gif" class="img" />
	  		</s:a>
	  	</td>
	  </tr>
  
 </s:iterator>

 
</table>
<table border="0" cellspacing="0" cellpadding="0" align="center">
  <tr>
     <td align="right">
    	<span>第<s:property value="#pageBean.pageNum" />/<s:property value="#pageBean.totalPage" />頁</span>
        <span>
        	<s:if test="#pageBean.pageNum gt 1">
            	<a href="javascript:void(0)" οnclick="showPage(1)">[首頁]</a>  
            	<a href="javascript:void(0)" οnclick="showPage(<s:property value="#pageBean.pageNum - 1" />)">[上一頁]</a>  
        	</s:if>
        	
        	<%--動態顯示條 --%>
        	<s:iterator begin="#pageBean.start" end="#pageBean.end" var="num">
           		<a href="javascript:void(0)" οnclick="showPage(<s:property value="#num" />)"><s:property value="#num" /></a>  
        	</s:iterator>
        	
        	<s:if test="#pageBean.pageNum lt #pageBean.totalPage">
           		<a href="javascript:void(0)" οnclick="showPage(<s:property value="#pageBean.pageNum + 1" />)">[下一頁]</a>  
            	<a href="javascript:void(0)" οnclick="showPage(<s:property value="#pageBean.totalPage" />)">[尾頁]</a>  
            </s:if>
        </span>
    </td>
  </tr>
</table>
<script type="text/javascript">
		function showPage(num){
			//1 修改隱藏域的值
			document.getElementById("pageNum").value = num;
			//2 提交表單
			document.forms[0].submit();
		}
	</script>
</body>
</html>




相關文章