(轉)ssm框架分頁實現后端


轉載至:

https://blog.csdn.net/zhshulin/article/details/26447713

分頁是JAVA WEB項目常用的功能,昨天在Spring MVC中實現了簡單的分頁操作和搜索分頁,在此記錄一下。使用的框架為(MyBatis+SpringMVC+Spring)。

 

        首先我們需要一個分頁的工具類:

1.分頁

 

[java]
  
    import java.io.Serializable;  
      
    /** 
     * 分頁 
     */  
    public class Page implements Serializable {  
      
        private static final long serialVersionUID = -3198048449643774660L;  
      
        private int pageNow = 1; // 當前頁數  
      
        private int pageSize = 4; // 每頁顯示記錄的條數  
      
        private int totalCount; // 總的記錄條數  
      
        private int totalPageCount; // 總的頁數  
      
        @SuppressWarnings("unused")  
        private int startPos; // 開始位置,從0開始  
      
        @SuppressWarnings("unused")  
        private boolean hasFirst;// 是否有首頁  
      
        @SuppressWarnings("unused")  
        private boolean hasPre;// 是否有前一頁  
      
        @SuppressWarnings("unused")  
        private boolean hasNext;// 是否有下一頁  
      
        @SuppressWarnings("unused")  
        private boolean hasLast;// 是否有最后一頁  
          
        /** 
         * 通過構造函數 傳入  總記錄數  和  當前頁 
         * @param totalCount 
         * @param pageNow 
         */  
        public Page(int totalCount, int pageNow) {  
            this.totalCount = totalCount;  
            this.pageNow = pageNow;  
        }  
          
        /** 
         * 取得總頁數,總頁數=總記錄數/總頁數 
         * @return 
         */  
        public int getTotalPageCount() {  
            totalPageCount = getTotalCount() / getPageSize();  
            return (totalCount % pageSize == 0) ? totalPageCount  
                    : totalPageCount + 1;  
        }  
      
        public void setTotalPageCount(int totalPageCount) {  
            this.totalPageCount = totalPageCount;  
        }  
      
        public int getPageNow() {  
            return pageNow;  
        }  
      
        public void setPageNow(int pageNow) {  
            this.pageNow = pageNow;  
        }  
      
        public int getPageSize() {  
            return pageSize;  
        }  
      
        public void setPageSize(int pageSize) {  
            this.pageSize = pageSize;  
        }  
      
        public int getTotalCount() {  
            return totalCount;  
        }  
      
        public void setTotalCount(int totalCount) {  
            this.totalCount = totalCount;  
        }  
        /** 
         * 取得選擇記錄的初始位置 
         * @return 
         */  
        public int getStartPos() {  
            return (pageNow - 1) * pageSize;  
        }  
      
        public void setStartPos(int startPos) {  
            this.startPos = startPos;  
        }  
      
        /** 
         * 是否是第一頁 
         * @return 
         */  
        public boolean isHasFirst() {  
            return (pageNow == 1) ? false : true;  
        }  
      
        public void setHasFirst(boolean hasFirst) {  
            this.hasFirst = hasFirst;  
        }  
        /** 
         * 是否有首頁 
         * @return 
         */  
        public boolean isHasPre() {  
            // 如果有首頁就有前一頁,因為有首頁就不是第一頁  
            return isHasFirst() ? true : false;  
        }  
      
        public void setHasPre(boolean hasPre) {  
            this.hasPre = hasPre;  
        }  
        /** 
         * 是否有下一頁 
         * @return 
         */  
        public boolean isHasNext() {  
            // 如果有尾頁就有下一頁,因為有尾頁表明不是最后一頁  
            return isHasLast() ? true : false;  
        }  
      
        public void setHasNext(boolean hasNext) {  
            this.hasNext = hasNext;  
        }  
        /** 
         * 是否有尾頁 
         * @return 
         */  
        public boolean isHasLast() {  
            // 如果不是最后一頁就有尾頁  
            return (pageNow == getTotalPageCount()) ? false : true;  
        }  
      
        public void setHasLast(boolean hasLast) {  
            this.hasLast = hasLast;  
        }  
      
    }  

 


       有了這個工具類后,首先編寫MyBatis的XxxxMapper.xml配置文件中的SQL語句,如下:

[html]
  
    <!-- 分頁SQL語句 -->  
    <select id="selectProductsByPage" resultMap="返回值類型">  
      select   
      *  
      from 表名 WHERE user_id = #{userId,jdbcType=INTEGER} limit #{startPos},#{pageSize}   
    </select>  
    <!-- 取得記錄的總數 -->  
    <select id="getProductsCount" resultType="long">  
      SELECT COUNT(*) FROM 表名 WHERE user_id = #{userId,jdbcType=INTEGER}   
    </select> 

 


             此處我們可以看到,2個<select>需要分別傳入3個和1個參數,此時在對應的DAO文件IXxxxDao中編寫接口來編寫對應的方法,方法名和mapper.xml中的id屬性值一致:

[java]
    /** 
     * 使用注解方式傳入多個參數,用戶產品分頁,通過登錄用戶ID查詢 
     * @param page 
     * @param userId 
     * @return startPos},#{pageSize}  
     */  
    public List<Products> selectProductsByPage(@Param(value="startPos") Integer startPos,@Param(value="pageSize") Integer pageSize,@Param(value="userId") Integer userId);  
      
    /** 
     * 取得產品數量信息,通過登錄用戶ID查詢 
     * @param userId 
     * @return 
     */  
    public long getProductsCount(@Param(value="userId") Integer userId);  

 

接口定義完成之后需要編寫相應的業務接口和實現方法,在接口中定義這樣一個方法,然后實現類中覆寫一下:

 

[java]
    /** 
         * 分頁顯示商品 
         * @param request 
         * @param model 
         * @param loginUserId 
         */  
        void showProductsByPage(HttpServletRequest request,Model model,int loginUserId);  

 

        接下來實現類中的方法就是要調用DAO層和接受Controller傳入的參數,進行業務邏輯的處理,request用來獲取前端傳入的參數,model用來向JSP頁面返回處理結果。

[java]  controller層
    @Override  
    public void showProductsByPage(HttpServletRequest request, Model model,int loginUserId) {  
        String pageNow = request.getParameter("pageNow");  
      
        Page page = null;  
      
        List<ProductWithBLOBs> products = new ArrayList<ProductWithBLOBs>();  
      
        int totalCount = (int) productDao.getProductsCount(loginUserId);  
      
        if (pageNow != null) {  
            page = new Page(totalCount, Integer.parseInt(pageNow));  
            allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId);  
        } else {  
            page = new Page(totalCount, 1);  
            allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId);  
        }  
      
        model.addAttribute("products", products);  
        model.addAttribute("page", page);  
    }  

 


       接下來是控制器的編寫,當用戶需要跳轉到這個現實產品的頁面時,就需要經過這個控制器中相應方法的處理,這個處理過程就是調用業務層的方法來完成,然后返回結果到JSP動態顯示,服務器端生成好頁面后傳給客戶端(瀏覽器)現實,這就是一個MVC過程。

[java]
  
    /** 
     * 初始化 “我的產品”列表 JSP頁面,具有分頁功能 
     *  
     * @param request 
     * @param model 
     * @return 
     */  
    @RequestMapping(value = "映射路徑", method = RequestMethod.GET)  
    public String showMyProduct(HttpServletRequest request, Model model) {  
        // 取得SESSION中的loginUser  
        User loginUser = (User) request.getSession().getAttribute("loginUser");  
        // 判斷SESSION是否失效  
        if (loginUser == null || "".equals(loginUser)) {  
            return "redirect:/";  
        }  
      
        int loginUserId = loginUser.getUserId();  
        //此處的productService是注入的IProductService接口的對象  
        this.productService.showProductsByPage(request, model, loginUserId);  
      
        return "跳轉到的JSP路徑";  
    }  

 

        JSP頁面接受部分,每個人都一樣,也就是結合JSTL和EL來寫,(在循環輸出的時候也做了判斷,如果接受的參數為空,那么輸出暫無商品,只有接受的參數不為空的時候,才循環輸出,使用<<c:when test="${}">結合<c:otherwise>),這里只給出分頁的相關代碼:

分頁接收參數代碼:

轉載至:https://blog.csdn.net/zhshulin/article/details/26447713

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!--引入JSTL核心標記庫的taglib指令-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>顯示留言</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

</head>

<body>
    <a href="success.jsp">返回</a>
    <table border="1">
        <tr>
            <th width="150">留言數</th>
            <th width="150">主題</th>
            <th width="150">內容</th>
            <th width="150">留言時間</th>
            <th width="150">留言人</th>
            <th width="150">刪除選項</th>
        </tr>
        <c:forEach items="${requestScope.messages}" var="message">
            <tr>
                <td width="100">${message.messageId}</td>
                <td width="100">${message.title}</td>
                <td width="500">${message.content}</td>
                <td width="200">${message.time}</td>
                <td width="100">${message.userName}</td>
                <td width="100">
                    <form action="MessageServlet?status=deleteMessage" method="post">
                        <input type="hidden" value="${message.messageId}" name="messageId">
                        <input type="submit"  value="刪除" onclick="return confirm('確定刪除嗎?')">
                    </form></td>
            </tr>
        </c:forEach>
    </table>
    
    <center>
    <div>
        第${requestScope.currentPage}頁/共${requestScope.countPage}頁 <a
            href="${pageContext.request.contextPath}/MessageServlet?status=getMessage&currenttPage=1">首頁</a><span> </span>
        <c:choose>
            <c:when test="${requestScope.currentPage==1}">
                上一頁
            </c:when>
            <c:otherwise>
                <a
                    href="${pageContext.request.contextPath}/MessageServlet?status=getMessage<span style="font-family: Arial, Helvetica, sans-serif;">&currenttPage</span>=${requestScope.currentPage-1}">上一頁</a>
            </c:otherwise>
        </c:choose>
        <%--計算begin和end --%>
        <c:choose>
            <%--如果總頁數不足10,那么就把所有的頁都顯示出來 --%>
            <c:when test="${requestScope.countPage<=10}">
                <c:set var="begin" value="1" />
                <c:set var="end" value="${requestScope.countPage}" />
            </c:when>
            <c:otherwise>
                <%--如果總頁數大於10,通過公式計算出begin和end --%>
                <c:set var="begin" value="${requestScope.currentPage-5}" />
                <c:set var="end" value="${requestScope.currentPage+4}" />
                <%--頭溢出 --%>
                <c:if test="${begin<1}">
                    <c:set var="begin" value="1"></c:set>
                    <c:set var="end" value="10"></c:set>
                </c:if>
                <%--尾溢出 --%>
                <c:if test="${end>requestScope.countPage}">
                    <c:set var="begin" value="${requestScope.countPage - 9}"></c:set>
                    <c:set var="end" value="${requestScope.countPage}"></c:set>
                </c:if>
            </c:otherwise>
        </c:choose>
        <%--循環顯示頁碼列表 --%>
        <c:forEach var="i" begin="${begin}" end="${end}">
            <c:choose>
                <c:when test="${i == requestScope.currentPage}">
                [${i}]
                </c:when>
                <c:otherwise>
                    <a href="<c:url value ='/MessageServlet?status=getMessage
                    &currentPage=${i}'/>">[${i}]</a>
                </c:otherwise>
            </c:choose>
        </c:forEach>
        <c:choose>
            <c:when test="${requestScope.currentPage==requestScope.countPage}">
                  下一頁
            </c:when>
            <c:otherwise>
                <a
                    href="${pageContext.request.contextPath}/MessageServlet?status=getMessage&currentPage=${requestScope.currentPage+1}"> 下一頁</a>
            </c:otherwise>
        </c:choose>
        <span> </span><a
            href="${pageContext.request.contextPath}/MessageServlet?status=getMessage&currentPage=${requestScope.countPage}">尾頁</a>
    </div>
</center>
</body>
</html>

 

[html]

 

 

[html]
 
  
    <!-- 分頁功能 start -->  
        <div align="center">  
            <font size="2">共 ${page.totalPageCount} 頁</font> <font size="2">第  
                ${page.pageNow} 頁</font> <a href="myProductPage?pageNow=1">首頁</a>  
            <c:choose>  
                <c:when test="${page.pageNow - 1 > 0}">  
                    <a href="myProductPage?pageNow=${page.pageNow - 1}">上一頁</a>  
                </c:when>  
                <c:when test="${page.pageNow - 1 <= 0}">  
                    <a href="myProductPage?pageNow=1">上一頁</a>  
                </c:when>  
            </c:choose>  
            <c:choose>  
                <c:when test="${page.totalPageCount==0}">  
                    <a href="myProductPage?pageNow=${page.pageNow}">下一頁</a>  
                </c:when>  
                <c:when test="${page.pageNow + 1 < page.totalPageCount}">  
                    <a href="myProductPage?pageNow=${page.pageNow + 1}">下一頁</a>  
                </c:when>  
                <c:when test="${page.pageNow + 1 >= page.totalPageCount}">  
                    <a href="myProductPage?pageNow=${page.totalPageCount}">下一頁</a>  
                </c:when>  
            </c:choose>  
            <c:choose>  
                <c:when test="${page.totalPageCount==0}">  
                    <a href="myProductPage?pageNow=${page.pageNow}">尾頁</a>  
                </c:when>  
                <c:otherwise>  
                    <a href="myProductPage?pageNow=${page.totalPageCount}">尾頁</a>  
                </c:otherwise>  
            </c:choose>  
        </div>  
        <!-- 分頁功能 End -->  

 

 

2.查詢分頁

       關於查詢分頁,大致過程完全一樣,只是第三個參數(上面是loginUserId)需要接受用戶輸入的參數,這樣的話我們需要在控制器中接受用戶輸入的這個參數(頁面中的<input>使用GET方式傳參),然后將其加入到SESSION中,即可完成查詢分頁(此處由於“下一頁”這中超鏈接的原因,使用了不同的JSP頁面處理分頁和搜索分頁,暫時沒找到在一個JSP頁面中完成的方法,出現了重復代碼,這里的重復代碼就是輸出內容的那段代碼,可以單獨拿出去,然后用一個<include>標簽加載到需要的JSP頁面就可以了,這樣可以避免代碼重復):

      這里給出控制器的代碼作為參考:

 

[java] view plain copy
 
  
        /** 
             * 通過 產品名稱 查詢產品 
             * @param request 
             * @param model 
             * @return 
             */  
            @RequestMapping(value = "映射地址", method = RequestMethod.GET)  
            public String searchForProducts(HttpServletRequest request, Model model) {  
                HttpSession session = request.getSession();  
          
                String param = request.getParameter("param");  
          
                String condition = (String) session.getAttribute("condition");  
          
                //先判斷SESSION中的condition是否為空  
                if (condition == null) {  
                    condition = new String();  
                    session.setAttribute("condition", condition);  
                    //如果Session中的condition為空,再判斷傳入的參數是否為空,如果為空就跳轉到搜索結果頁面  
                    if (param == null || "".equals(param)) {  
                        return "private/space/ProductSearchResult";  
                    }  
                }  
                //如果SESSION不為空,且傳入的搜索條件param不為空,那么將param賦值給condition  
                if (param != null && !("".equals(param))) {  
                    condition = param;  
                    session.setAttribute("condition", condition);  
                }  
                //使用session中的condition屬性值來作為查詢條件  
                this.productService.showSearchedProductsByPage(request, model, condition);  
          
                return "跳轉的頁面";  
            } 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM