1. 程式人生 > >SSH框架整合(實現分頁查詢)

SSH框架整合(實現分頁查詢)


SSH框架整合、分頁查詢案例

之前已經寫過了SSM框架的分頁查詢案例,剛翻筆記時看到了以前寫過的SSH分頁查詢的功能的筆記,這裡就也再整理一下嘍,送給那些在學習SSH框架的同學,SSH框架因為用的Hibernate,所以與SSM有所不同,希望這個小案例能對大家有所幫助。

<!--more-->

關於專案

框架:
後端:spring + struts2 + hibernate5.x
前端:bootstrap + Fontawesome圖示集
環境:IDEA + maven + mysql5.7 + Tomcat8
index:localhost:8080/SSH_Paging/

我們先看一下專案目錄結構

1. 首先這是maven專案,我們要要入依賴

<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>

2. 建立資料庫

注:由於使用hibernate,我們已配置表結構由hibernate自動生成,這裡就不需要我們建立了

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','你猜','不想寫備註');

3. PageBean的封裝

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;
    }

}

4.1 action層 --> 處理前臺模態框的編輯功能

/**
     * 為模態框提供的查詢功能
     * 處理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;
    }

說明:

這裡我們就要說一下了,首先我們要明白這個功能:其實就是普通的更新資料的功能,即當我們點選編輯按鈕的時候需要先ajax非同步請求去後臺根據點選的欄位id去查詢對應的資料庫資訊,然後將資料以JSON的格式返回給頁面,最後頁面解析JSON格式資料,回顯在編輯框中,實現編輯。

那麼,在這裡是怎樣進行將這個JSON格式資料返回給頁面呢?我們需要看一下struts2.xml中配置:

<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>
  1. 注意一下這個<allowed-methods>是為我們的萬用字元服務的,在struts2.3版本以後,如果我們沒有寫這個而直接使用萬用字元就會報錯找不到對映,所以需要配置這個標籤,格式:<allowed-methods>方法名1,方法名2…</allowed-methods>。詳情請參考這篇 博文

  2. 注意<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("錯誤");
         }
    });

    詳情參考這篇 博文

4.2 action層 --> 處理分頁邏輯

  /**
     * 分頁查詢相關
     */
    //屬性驅動方式,當前頁,預設頁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";
    }

4.3 dao層 --> 處理分頁邏輯

    /**
     * 分頁查詢的方法
     * @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;
    }

5. 前臺JS的分頁邏輯

分析

百度分頁演算法(每頁顯示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>
        &nbsp;
        &nbsp;
        <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>
&nbsp;
&nbsp;
<strong>到第</strong>&nbsp;<input type="text" size="3" id="page" name="pageCode"
                                class="form-control input-sm"
                                style="width:11%"/>&nbsp;<strong></strong>
&nbsp;
<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}">&laquo;</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"/>

            
           

相關推薦

no