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

轉載至:html

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

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

 

        首先咱們須要一個分頁的工具類:瀏覽器

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語句,以下:
session

[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屬性值一致:
app

[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頁面返回處理結果。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過程。ide

[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 "跳轉的頁面";  
            } 
相關文章
相關標籤/搜索