SSH框架整合、分頁查詢案例javascript
Spring、Hibernate、Struts2框架雖然如今已經不是很流行,可是在一寫公司的老項目中仍然在使用,多學一種技術總沒有壞處,因此若是你們剛學完了Spring、Struts、Hibernate框架,那麼這個項目將教會你如何對這三大框架進行整合。html
框架: 後端:spring + struts2 + hibernate5.x 前端:bootstrap + Fontawesome圖標集 環境:IDEA + maven + mysql5.7 + Tomcat8
1. 用戶登陸 2. 客戶信息的增、刪、改、查 3. 客戶信息的列表展現和分頁查詢功能
項目源碼請點擊SSH框架整合 進入個人GitHub。前端
由於本項目使用了maven,若是你對maven項目不瞭解,能夠查看我這篇博文:maven起步java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>customer</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>customer Maven Webapp</name> <url>http://maven.apache.org</url> <build> <finalName>customer</finalName> <resources> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>${basedir}/src/main/resources</directory> </resource> </resources> </build> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <!-- 1.日誌 --> <!-- 實現slf4j接口並整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <!-- 2.數據庫 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> <scope>runtime</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.12</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.10.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>5.2.10.Final</version> </dependency> <!-- 3.Servlet web --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.5.12</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> </dependencies> </project>
注:因爲使用hibernate,咱們已配置表結構由hibernate自動生成,這裏就不須要咱們建立了mysql
create database ssh_paging character set utf8; # 插入數據 # 如下代碼須要在啓動Tomcat運行項目後才能執行,否則尚未建立表結構,咱們怎麼插入數據呢。 insert into Admin values(a,'admin','admin'); insert into Customer values(1,'塗陌','123456789','你猜','不想寫備註'); insert into Customer values(2,'逗瓜','123456789','你猜','不想寫備註'); insert into Customer values(3,'憤青','123456789','你猜','不想寫備註'); insert into Customer values(4,'鹹魚','123456789','你猜','不想寫備註'); insert into Customer values(5,'小白','123456789','你猜','不想寫備註'); insert into Customer values(6,'菜雞','123456789','你猜','不想寫備註');
package com.cutton.pojo; import java.io.Serializable; import java.util.List; /** * @author huys * @date 18-3-10下午12:47 */ public class PageBean<T> implements Serializable { //當前頁 private int pageCode; //總頁數=總條數/每頁顯示的條數 //private int totalPage; //總記錄數 private int totalCount; //每頁顯示的記錄條數 private int pageSize; //每頁顯示的數據 private List<T> beanList; public int getPageCode() { return pageCode; } public void setPageCode(int pageCode) { this.pageCode = pageCode; } /** * 調用getTotalPage() 獲取到總頁數 * JavaBean屬性規定:totalPage是javaBean屬性 ${pageBean.totalPage} */ public int getTotalPage() { //計算 int totalPage = totalCount / pageSize; //說明整除 if(totalCount % pageSize == 0){ return totalPage; }else{ return totalPage + 1; } } /* public void setTotalPage(int totalPage) { this.totalPage = totalPage; }*/ public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<T> getBeanList() { return beanList; } public void setBeanList(List<T> beanList) { this.beanList = beanList; } }
處理前臺模態框的編輯功能部分git
/** * 爲模態框提供的查詢功能 * 處理ajax的請求 */ public String search() { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); customer = customerService.findById(customer.getC_id()); //將數據放到Map集合中,再轉換成json格式的數據 Map<String, Object> map = new HashMap<String, Object>(); map.put("c_id", customer.getC_id()); map.put("c_name", customer.getC_name()); map.put("c_telephone", customer.getC_telephone()); map.put("c_address", customer.getC_address()); map.put("c_remark", customer.getC_remark()); //將Map集合數據轉換成json格式的數據 JSONObject json = JSONObject.fromObject(map); result = json.toString(); System.out.println("這裏我要傳給前臺頁面的JSON數據是:"+result); } catch (Exception e) { e.printStackTrace(); } return SUCCESS; }
說明:github
這裏咱們就要說一下了,首先咱們要明白這個功能:其實就是普通的更新數據的功能,即當咱們點擊編輯按鈕的時候須要先ajax異步請求去後臺根據點擊的字段id去查詢對應的數據庫信息,而後將數據以JSON的格式返回給頁面,最後頁面解析JSON格式數據,回顯在編輯框中,實現編輯。web
那麼,在這裏是怎樣進行將這個JSON格式數據返回給頁面呢?咱們須要看一下struts2.xml中配置:ajax
<package name="struts2" namespace="/" extends="struts-default,json-default"> <action name="customer_*" class="customerAction" method="{1}"> <result type="json"> <param name="root">result</param> </result> <allowed-methods>search</allowed-methods> </action> </package>
注意一下這個<allowed-methods>
是爲咱們的通配符服務的,在struts2.3版本之後,若是咱們沒有寫這個而直接使用通配符就會報錯找不到映射,因此須要配置這個標籤,格式:<allowed-methods>方法名1,方法名2…</allowed-methods>
。詳情請參考這篇 博文算法
注意<result type="json">
在struts2中是用來作Ajax請求的,因此根本沒有跳轉頁面,寫這個標籤,會將你Action中的變量轉換成JSON格式數據返回到頁面, 那麼<param name="root">result</param>
就會將你要返回的數據result(JSON字符串)返回給頁面,在頁面使用var d = eval("("+data+")");
的方式將JSON字符串解析成JSON格式數據,而後咱們就能經過ognl表達式解析獲取數據,而後給指定的編輯框中賦值數據了。Ajax部分:
// 先去查詢數據 $.ajax({ url: '<%=basePath%>/customer_search.do?c_id='+c_id, type: 'POST', dataType: 'json', contentType: 'application/json;charset=UTF-8', data: {}, success: function(data){ var d = eval("("+data+")"); $("#c_id").val(d.c_id); $("#c_name").val(d.c_name); $("#c_telephone").val(d.c_telephone); $("#c_address").val(d.c_address); $("#c_remark").val(d.c_remark); $("#editModal").modal('show'); }, error: function(){ alert("錯誤"); } });
詳情參考這篇 博文
處理分頁邏輯功能部分
/** * 分頁查詢相關 */ //屬性驅動方式,當前頁,默認頁1 private Integer pageCode = 1; public void setPageCode(Integer pageCode) { if(pageCode == null){ pageCode = 1; } this.pageCode = pageCode; } //默認每頁顯示的數據條數 private Integer pageSize = 4; public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } //分頁查詢的方法 public String findByPage(){ //調用service層 DetachedCriteria criteria = DetachedCriteria.forClass(Cutton.class); //查詢 PageBean<Cutton> page = cuttonService.findByPage(pageCode,pageSize,criteria); //壓棧 ValueStack vs = ActionContext.getContext().getValueStack(); //頂棧是map<"page",page對象> vs.set("page",page); return "page"; }
處理分頁邏輯
/** * 分頁查詢的方法 * @param pageCode * @param pageSize * @param criteria * @return */ @Override public PageBean<Cutton> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria) { PageBean<Cutton> page = new PageBean<Cutton>(); page.setPageCode(pageCode); page.setPageSize(pageSize); //先查詢總記錄數 select count(*) criteria.setProjection(Projections.rowCount()); List<Number> list = (List<Number>) this.getHibernateTemplate().findByCriteria(criteria); if(list != null && list.size() > 0){ int totalCount = list.get(0).intValue(); //總記錄數 page.setTotalCount(totalCount); } //要吧select count(*) 先清空 變成select *... criteria.setProjection(null); //提供分頁查詢 List<Cutton> beanList = (List<Cutton>) this.getHibernateTemplate().findByCriteria(criteria,(pageCode - 1)*pageSize, pageSize); //分頁查詢的數據,每頁顯示的數據,使用limit page.setBeanList(beanList); return page; }
百度分頁算法(每頁顯示10個頁碼): 當點擊頁碼7以後的頁碼,最前端的頁碼依次減小 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 點擊[7] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 算法: 若 總頁數 <= 10 則begin=1 end=總頁數 若 總頁數 > 10 則begin=當前頁-5 end=當前頁+4 頭溢出: 若begin < 1 則begin=1 end=10 尾溢出: 若begin > 當前頁 則brgin=end-9 end=總頁數 我對詞項目每頁顯示5個頁碼: 若 總頁數 <= 5 則begin=1 end=總頁數 若 總頁數 > 5 則begin=當前頁-1 end=當前頁+3 頭溢出: 若begin < 1 則begin=1 end=5 尾溢出: 若begin > 當前頁 則brgin=end-4 end=總頁數
<form class="listForm" name="listForm" method="post" action="<%=basePath%>/cutton_findByPage.action"> <div class="row"> <div class="form-inline"> <label style="font-size:14px;margin-top:22px;"> <strong>共<b>${page.totalCount}</b>條記錄,共<b>${page.totalPage}</b>頁</strong> <strong>每頁顯示</strong> <select class="form-control" name="pageSize"> <option value="4" <c:if test="${page.pageSize == 4}">selected</c:if> >4 </option> <option value="6" <c:if test="${page.pageSize == 6}">selected</c:if> >6 </option> <option value="8" <c:if test="${page.pageSize == 8}">selected</c:if> >8 </option> <option value="10" <c:if test="${page.pageSize == 10}">selected</c:if> >10 </option> </select> <strong>條</strong> <strong>到第</strong> <input type="text" size="3" id="page" name="pageCode" class="form-control input-sm" style="width:11%"/> <strong>頁</strong> <button type="submit" class="btn btn-sm btn-info">GO!</button> </label> <ul class="pagination" style="float:right;"> <li> <a href="<%=basePath%>/cutton_findByPage.action?pageCode=1"><strong>首頁</strong></a> </li> <li> <c:if test="${page.pageCode > 2}"> <a href="<%=basePath%>/cutton_findByPage.action?pageCode=${page.pageCode - 1}">«</a> </c:if> </li> <!-- 寫關於分頁頁碼的邏輯 --> <c:choose> <c:when test="${page.totalPage <= 5}"> <c:set var="begin" value="1"/> <c:set var="end" value="${page.totalPage}"/> </c:when> <c:otherwise> <c:set var="begin" value="${page.pageCode - 1}"/> <c:set var="end" value="${page.pageCode + 3}"/> <!-- 頭溢出 --> <c:if test="${begin < 1}"> <c:set var="begin" value="1"/> <c:set var="end" value="5"/> </c:if> <!-- 尾溢出 --> <c:if test="${end > page.totalPage}"> <c:set var="begin" value="${page.totalPage -4}"/> <c:set var="end" value="${page.totalPage}"/> </c:if> </c:otherwise> </c:choose> <!-- 顯示頁碼 --> <c:forEach var="i" begin="${begin}" end="${end}"> <!-- 判斷是不是當前頁,這裏用if判斷實現是否被點擊的頁碼呈現active樣式 --> <c:if test="${i == page.pageCode}"> <li class="active"><a href="javascript:void(0);">${i}</a></li> </c:if> <c:if test="${i != page.pageCode}"> <li> <a href="<%=basePath%>/cutton_findByPage.action?pageCode=${i}">${i}</a> </li> </c:if> </c:forEach> <li> <c:if test="${page.pageCode < page.totalPage}"> <a href="<%=basePath%>/cutton_findByPage.action?pageCode=${page.pageCode + 1}">»</a> </c:if> </li> <li> <a href="<%=basePath%>/cutton_findByPage.action?pageCode=${page.totalPage}"><strong>末頁</strong></a> </li> </ul> </div> </div> </form>
<br/>
若是你們有興趣,歡迎你們加入個人Java交流羣:671017003 ,一塊兒交流學習Java技術。博主目前一直在自學JAVA中,技術有限,若是能夠,會盡力給你們提供一些幫助,或是一些學習方法,固然羣裏的大佬都會積極給新手答疑的。因此,別猶豫,快來加入咱們吧!
<br/>
If you have some questions after you see this article, you can contact me or you can find some info by clicking these links.