SSH框架下的條件查詢及查詢結果分頁
之前看過許多別人BLOG中寫的方案,但是沒有自己動手從資料庫、後端、前端全過程實現的話,難以發現自己存在問題。一是沒有形成自己獨有的解決方案,二是不知道理論和現實之間的差異。
本文例子的使用場景:資料庫中儲存了一系列商品資訊,欄位包括商品名字和商品價格。
需要實現功能:商品名字支援 模糊查詢,商品價格 支援精確查詢。查詢結果分頁顯示。
一、資料準備
二、專案結構
按照慣例,建立的是Maven專案,方便依賴Jar包的匯入。vo包存放的是封裝好的分頁資料類,提供前端進行資料展示。
三、配置檔案的編寫
省略web.xml和兩個peoperties,因為沒有特別需要注意的點。
實際在寫程式時,我生成了配置檔案後不會直接去寫。我習慣先寫一部分通用的配置,例如資料庫連線池和通用事務管理器等。其他的會留到寫完類檔案之後,需要進行單元測試時才配置到Spring容器中。
1、Spring配置檔案。因為Bean的數量少,我偷懶採用直接寫的方式。沒有用到包掃描。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<!-- 1:配置資料庫相關引數 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 2:資料庫連線池Druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 配置連線池屬性 -->
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
</bean>
<!-- 配置Hibernate相關屬性 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 配置Hibernate屬性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialet">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 載入對映檔案 -->
<property name="mappingResources">
<list>
<value>org/lzx/sshm/domain/Product.hbm.xml</value>
<value>org/lzx/sshm/domain/Department.hbm.xml</value>
<value>org/lzx/sshm/domain/Employee.hbm.xml</value>
</list>
</property>
</bean>
<!-- 配置Action的類 多例 -->
<bean id="productAction" class="org.lzx.sshm.action.ProductAction"
scope="prototype">
<!-- 手動注入Service -->
<property name="productService" ref="productService"></property>
</bean>
<!-- 配置業務層的類 -->
<bean id="productService" class="org.lzx.sshm.service.impl.ProductServiceImpl">
<property name="productDao" ref="productDao" />
</bean>
<!-- 配置DAO層的類 -->
<bean id="productDao" class="org.lzx.sshm.dao.impl.ProductDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 開啟註解事務 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
2、Struts的配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="ssh" extends="struts-default" namespace="/">
<!-- 由Spring負責建立action實體 -->
<!-- struts配置中的class直接寫spring中的bean id,這種方式建立的Action可以使用aop進行管理 -->
<action name="product_*" class="productAction" method="{1}">
<!-- 這個是使用直接提交表單形式 -->
<result name="findAll">/jsp/show2.jsp</result>
</action>
<!-- 單純用於跳轉到顯示頁面,這個是使用Ajax -->
<action name="viewProduct">
<result>/jsp/show4.jsp</result>
</action>
</package>
</struts>
3、Hibernate交給Spring容器管理之後,就不需要寫cfg.xml檔案了。
右擊Product實體類,使用Hibernate Tools自動生成對應的hbm.xml檔案。
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.lzx.sshm.domain.Product" table="PRODUCT">
<id name="pid" type="java.lang.Integer">
<column name="PID" />
<generator class="native" />
</id>
<property name="pname" type="java.lang.String" length="20">
<column name="PNAME" />
</property>
<property name="price" type="java.lang.Double">
<column name="PRICE" />
</property>
</class>
</hibernate-mapping>
四、實體類編寫
商品實體類 Product.java
public class Product {
private Integer pid;
private String pname;
private Double price;
//省略建構函式和get/set方法
}
分頁物件VO Pager.java
public class Pager<T> implements Serializable {
private static final long serialVersionUID = -8741766802354222579L;
private int pageSize; // 每頁顯示多少條記錄
private int currentPage; //當前第幾頁資料
private int totalRecord; // 一共多少條記錄
private int totalPage; // 一共多少頁記錄
private List<T> dataList; //要顯示的資料
public Pager(int pageNum, int pageSize, List<T> sourceList){
if(sourceList == null || sourceList.isEmpty()){
return;
}
// 總記錄條數
this.totalRecord = sourceList.size();
// 每頁顯示多少條記錄
this.pageSize = pageSize;
//獲取總頁數
this.totalPage = this.totalRecord / this.pageSize;
if(this.totalRecord % this.pageSize !=0){
this.totalPage = this.totalPage + 1;
}
// 當前第幾頁資料
this.currentPage = this.totalPage < pageNum ? this.totalPage : pageNum;
// 起始索引
int fromIndex = this.pageSize * (this.currentPage -1);
// 結束索引
int toIndex = this.pageSize * this.currentPage > this.totalRecord ? this.totalRecord : this.pageSize * this.currentPage;
this.dataList = sourceList.subList(fromIndex, toIndex);
}
public Pager(){
}
public Pager(int pageSize, int currentPage, int totalRecord, int totalPage,
List<T> dataList) {
super();
this.pageSize = pageSize;
this.currentPage = currentPage;
this.totalRecord = totalRecord;
this.totalPage = totalPage;
this.dataList = dataList;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getDataList() {
return dataList;
}
public void setDataList(List<T> dataList) {
this.dataList = dataList;
}
@Override
public String toString() {
return "Pager [pageSize=" + pageSize + ", currentPage=" + currentPage + ", totalRecord=" + totalRecord
+ ", totalPage=" + totalPage + ", dataList=" + dataList + "]";
}
}
五、DAO層編寫
DAO介面:ProductDao.java
/**
* 商品管理的Dao
*
* @author Skye
*
*/
public interface ProductDao {
/**
* 根據查詢條件,查詢商品分頁資訊
*
* @param searchModel
* 封裝查詢條件
* @param pageNum
* 查詢第幾頁資料
* @param pageSize
* 每頁顯示多少條記錄
* @return 查詢結果
*/
Pager<Product> findByPage(Product searchModel, int pageNum,
int pageSize);
}
DAO實現類:ProductDaoImpl.java
public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao {
public Pager<Product> findByPage(Product searchModel, int pageNum, int pageSize) {
// 宣告結果集
Pager<Product> result = null;
// 存放查詢引數
Map<String, Object> paramMap = new HashMap<String, Object>();
String proName = searchModel.getPname();
Double price = searchModel.getPrice();
StringBuilder hql = new StringBuilder("from Product where 1=1");
StringBuilder countHql = new StringBuilder("select count(pid) from Product where 1=1 ");
if (proName != null && !proName.equals("")) {
hql.append(" and pname like :proName ");
countHql.append(" and pname like :proName ");
paramMap.put("proName", "%" + proName + "%");
}
if (price != null && !price.equals("")) {
hql.append(" and price = :price ");
countHql.append(" and price = :price ");
paramMap.put("price", price);
}
// 起始索引
int fromIndex = pageSize * (pageNum - 1);
// 存放所有查詢出的商品物件
List<Product> productList = new ArrayList<Product>();
Session session = null;
// 獲取被Spring託管的session
session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
// 獲取query物件
Query hqlQuery = session.createQuery(hql.toString());
Query countHqlQuery = session.createQuery(countHql.toString());
// 設定查詢引數
setQueryParams(hqlQuery, paramMap);
setQueryParams(countHqlQuery, paramMap);
// 從第幾條記錄開始查詢
hqlQuery.setFirstResult(fromIndex);
// 一共查詢多少條記錄
hqlQuery.setMaxResults(pageSize);
// 獲取查詢的結果
productList = hqlQuery.list();
// 獲取總記錄數
List<?> countResult = countHqlQuery.list();
int totalRecord = ((Number) countResult.get(0)).intValue();
// 獲取總頁數
int totalPage = totalRecord / pageSize;
if (totalRecord % pageSize != 0) {
totalPage++;
}
// 組裝pager物件
result = new Pager<Product>(pageSize, pageNum, totalRecord, totalPage, productList);
return result;
}
/**
* 設定查詢的引數
*
* @param query
* @param paramMap
* @return
*/
private Query setQueryParams(Query query, Map<String, Object> paramMap) {
if (paramMap != null && !paramMap.isEmpty()) {
for (Map.Entry<String, Object> param : paramMap.entrySet()) {
query.setParameter(param.getKey(), param.getValue());
}
}
return query;
}
}
六、Service層編寫
介面: ProductService.java
public interface ProductService {
/**
* 根據查詢條件,查詢商品分頁資訊
*
* @param searchModel
* 封裝查詢條件
* @param pageNum
* 查詢第幾頁資料
* @param pageSize
* 每頁顯示多少條記錄
* @return 查詢結果
*/
Pager<Product> findByPage(Product searchModel, int pageNum, int pageSize);
}
實現類: ProductServiceImpl.java
public class ProductServiceImpl implements ProductService {
private ProductDao productDao;
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
public Pager<Product> findByPage(Product searchModel, int pageNum, int pageSize) {
Pager<Product> result = productDao.findByPage(searchModel, pageNum, pageSize);
return result;
}
}
七、控制層Action編寫
這個Action採用了兩套不同的方法。
方式一: findAll方法是支援前端使用Form表單直接提交查詢資料,然後將分頁物件壓入值棧(方式很多,存入Servlet 物件中也是可行的);
方式二: findAllJSON方法是支援前端AJAX提交資料然後返回JSON格式資料的。詳情見註釋。
public class ProductAction extends ActionSupport implements ModelDriven<Product> {
// 模型驅動需要使用的實體類
private Product product = new Product();
//該例子實際沒有用到自動繫結,資料從request物件中取了
public Product getModel() {
return product;
}
//返回前端的JSON字串,需要提供get/set方法
private String responseStr;
public String getResponseStr() {
return responseStr;
}
public void setResponseStr(String responseStr) {
this.responseStr = responseStr;
}
// Struts和Spring整合過程中按名稱自動注入的業務層類
private ProductService productService;
public void setProductService(ProductService productService) {
this.productService = productService;
}
// 方式一
public String findAll() {
System.out.println("控制器方法啟動");
// 使用struts2的servlet介面,接收request裡的引數
// 商品名字引數
HttpServletRequest request = ServletActionContext.getRequest();
String proName = request.getParameter("proName");
// 獲取價格
Double price = null;
String priceStr = request.getParameter("price");
if (priceStr != null && !"".equals(priceStr.trim())) {
price = Double.parseDouble(priceStr);
}
// 校驗pageNum引數輸入合法性
String pageNumStr = request.getParameter("pageNum");
System.out.println("前端給的pageNum是:"+pageNumStr);
int pageNum = 1; // 預設顯示第幾頁資料
if (pageNumStr != null && !"".equals(pageNumStr.trim())) {
pageNum = Integer.parseInt(pageNumStr);
}
int pageSize = 5; // 預設每頁顯示多少條記錄
String pageSizeStr = request.getParameter("pageSize");
if (pageSizeStr != null && !"".equals(pageSizeStr.trim())) {
pageSize = Integer.parseInt(pageSizeStr);
}
// 組裝模糊查詢條件
Product searchModel = new Product();
searchModel.setPname(proName);
searchModel.setPrice(price);
System.out.println("==============Product物件==============");
System.out.println(searchModel);
// 呼叫service 獲取查詢結果
Pager<Product> result = productService.findByPage(searchModel, pageNum, pageSize);
// 將pageBean存入值棧,供前端頁面讀取
ActionContext.getContext().getValueStack().push(result);
// 將查詢條件也壓回值棧,在初始化函式中為其初始化
ActionContext.getContext().getValueStack().push(searchModel);
System.out.println("==============Pager物件==============");
System.out.println(result);
System.out.println("控制器方法完成");
return "findAll";
}
//方式二:Ajax+JSON
public String findAllJSON() {
// 使用struts2的servlet介面,接收request裡的引數
// 商品名字引數
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String proName = request.getParameter("proName");
// 獲取價格
Double price = null;
String priceStr = request.getParameter("price");
if (priceStr != null && !"".equals(priceStr.trim())) {
price = Double.parseDouble(priceStr);
}
// 取得頁面索引
String pageNumStr = request.getParameter("pageNum");
int pageNum = 1; // 預設顯示第幾頁資料
if (pageNumStr != null && !"".equals(pageNumStr.trim())) {
pageNum = Integer.parseInt(pageNumStr);
}
int pageSize = 5; // 預設每頁顯示多少條記錄
String pageSizeStr = request.getParameter("pageSize");
if (pageSizeStr != null && !"".equals(pageSizeStr.trim())) {
pageSize = Integer.parseInt(pageSizeStr);
}
// 組裝模糊查詢條件
Product searchModel = new Product();
searchModel.setPname(proName);
searchModel.setPrice(price);
// 呼叫service 獲取查詢結果
Pager<Product> result = productService.findByPage(searchModel, pageNum, pageSize);
// 將查詢結果封裝成JSON字串格式
responseStr = JSONObject.toJSONString(result);
System.out.println(responseStr);
// 利用response物件傳回前端
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html;charset=utf-8");
try {
Writer writer = response.getWriter();
writer.write(responseStr);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}
}
八、前端的實現方式
都採用了JQuery-Pagination外掛。
方式一:
注意:在Struts值棧中的物件,可以直接用屬性名拿到他的值。比如說,我們之前往值棧中push了一個Pager物件,他有一個屬性是dataList,那麼我們就能夠直接在c:forEach items=”${dataList}”;為了保留上一頁的查詢條件,我們需要從後臺把查詢條件再次傳回前臺,所以往值棧push了一個Product類物件,因此在使用JavaScript初始化函式時,就可以為$(“#pro_name”).val(“${pname}”); $(“#pro_price”).val(“${price}”);設定分頁查詢的屬性值。這麼做的原因是,直接使用Form的Submit提交是同步的,會直接重新整理整個頁面,那麼之前文字框裡的查詢條件就會丟失。可以採用Chrome的F12開發者工具進行分析。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.table1 {
border: 1px solid #ddd;
width: 900px;
}
thead {
background-color: lightblue;
}
</style>
</head>
<%
// 獲取請求的上下文
String context = request.getContextPath();
%>
<link href="${pageContext.request.contextPath}/css/pagination.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.pagination.js"></script>
<script type="text/javascript">
// 點選分頁按鈕以後觸發的動作
function handlePaginationClick(new_page_index, pagination_container) {
$("#proForm").attr("action", "<%=context %>/product_findAll.action?pageNum=" + (new_page_index +1));
$("#proForm").submit();
return false;
}
//初始化函式
$(function(){
$("#News-Pagination").pagination(${totalRecord}, {
items_per_page:${pageSize}, // 每頁顯示多少條記錄
current_page:${currentPage} - 1, // 當前顯示第幾頁資料
num_display_entries:2, // 連續分頁主體顯示的條目數
next_text:"下一頁",
prev_text:"上一頁",
num_edge_entries:2, // 連線分頁主體,顯示的條目數
callback:handlePaginationClick, //執行的回撥函式,也就是去獲取新的分頁資料
load_first_page:false //防止頁面一直重新整理( 這條非常重要!)
});
// 初始化時就獲得後臺發過來的前一次的查詢引數
$("#pro_name").val("${pname}");
$("#pro_price").val("${price}");
});
</script>
<body>
<div>
<form action="<%=context %>/product_findAll.action" id="proForm" method="post">
商品名稱 <input type="text" name="proName" id="pro_name" style="width: 120px" >
商品價格 <input type="text" name="price" id="pro_price" style="width: 120px" >
<input type="submit" value="查詢">
</form>
</div>
<c:if test="${fn:length(dataList) gt 0 }">
<table border="1px" cellspacing="0px"
style="border-collapse: collapse">
<thead>
<tr height="30">
<td align="center">商品編號</td>
<td align="center">商品名稱</td>
<td align="center">商品價格</td>
</tr>
</thead>
<c:forEach items="${dataList}" var="p">
<tr>
<td><c:out value="${p.pid }"></c:out></td>
<td><c:out value="${p.pname }"></c:out></td>
<td><c:out value="${p.price }"></c:out></td>
</tr>
</c:forEach>
</table>
<br>
<div id="News-Pagination"></div>
</c:if>
<div>後臺傳來的當前頁:${currentPage}</div>
</body>
</html>
方式二:
這種方式採用了Ajax非同步提交資料。在沒有使用ajax-submit外掛的情況下,不能直接用JQuery繫結表單的submit事件了,它會像方式1一樣提交,那麼查詢資料就會丟失。採用Ajax的方式非同步提交,只重新整理頁面的一部分元素,那麼查詢條件是不會丟失的。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.table1 {
border: 1px solid #ddd;
width: 900px;
}
thead {
background-color: lightblue;
}
</style>
</head>
<%
// 獲取請求的上下文
String context = request.getContextPath();
%>
<link href="${pageContext.request.contextPath}/css/pagination.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/jquery-1.11.3.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/jquery.pagination.js"></script>
<script type="text/javascript">
$(function(){
Query();
});
// JQuery-Pagination的初始化
function JPagination(result){
$("#News-Pagination").pagination(result.totalRecord, {
items_per_page:result.pageSize, // 每頁顯示多少條記錄
current_page:result.currentPage - 1, // 當前顯示第幾頁資料
num_display_entries:2, // 連續分頁主體顯示的條目數
next_text:"下一頁",
prev_text:"上一頁",
num_edge_entries:2, // 連線分頁主體,顯示的條目數
callback:handlePaginationClick, //執行的回撥函式,也就是去獲取新的分頁資料
load_first_page:false //防止頁面一直重新整理( 這條非常重要!)
});
}
//點選分頁按鈕以後觸發的動作
function handlePaginationClick(new_page_index, pagination_container) {
//根據ID從表單中獲取查詢需要的引數
var pname = $("#pro_name").val();
var price = $("#pro_price").val();
var pageIndex = new_page_index + 1;
//非同步方式提交查詢
$.ajax({
type: "POST",
//返回結果轉換成json,方便用data.屬性的方式取值
dataType: "json",
url: "<%=context%>/product_findAllJSON.action" ,
data: "pageNum="+ pageIndex +"&proName=" + pname + "&price=" + price,
success: function(result) {
//載入結果的JSON字串
var totalRecord = result.totalRecord;
var currentPage = result.currentPage; // 獲取當前第幾頁資料
var productList = result.dataList; // 學生記錄資訊
//生成表格內容
showProductData(productList);
//不需要再進行分頁外掛初始化
}
});
return false;
}
//直接自定義一個button來發起查詢
function Query(){
$("#btn2").click(function(){
//根據ID從表單中獲取查詢需要的引數
var pname = $("#pro_name").val();
var price = $("#pro_price").val();
//非同步方式提交查詢