1. 程式人生 > >Java Web——商品分頁

Java Web——商品分頁

我其實只瞭解一點點的js,所以我在用這個jquery庫的時候,完全是連蒙帶猜的看說明+原始碼,最後利用debug,勉勉強強實現了分頁功能;會jquery的同學可以自行去github看原始碼了;

實現效果:

jsp部分:

<script type="text/javascript" src="js/jquery.min.js"></script>
<link href="css/pagination_style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.paging.js"></script>
<div class="pagelink">
    <!-- 隱藏標籤,儲存元素總數(即商品總數);我是在servlet中利用request.setAttribute儲存的-->
	<input type="hidden" name="elements" value="${elements}">   
    <!-- 隱藏標籤,儲存當前所在頁碼(頁面重新整理後頁碼不變);同樣是在servlet中利用request.setAttribute儲存的-->
	<input type="hidden" name="currentpage" value="${page}">
	<ul id="paging" class="pagination modal-2">
		<li>&lt; </li>   <!-- 向前翻7頁 -->
		<li> first </li>    <!-- 回到第一頁 -->
		<li> #n</li>
		<li> #n</li>
		<li> #c</li>    <!-- current,即向前/後翻頁時自動定位(第三個n)-->
		<li> #n</li>
		<li> #n</li>
		<li> #n</li>
		<li> #n</li>
		<li> last </li>   <!-- 到達最後一頁 -->
		<li> &gt;</li>    <!-- 向後翻7頁 -->
	</ul>
</div>
<div id="output"></div>

備註:nncnnnn即表示頁面上最多顯示7個頁碼;
elements在java中利用mysql查詢即可得出;
page:我的想法是滑鼠點選第m頁,則在跳轉地址後面加上page引數(http://localhost:8088/exp1/GetProductInfo?page=m),然後在servlet中利用request.setAttribute儲存,保證頁面重新載入,頁碼不變

css部分(自行定義即可,這個是我在網上找的一個樣式):

.pagelink {
	text-align:center;
}
#output{
	text-align:center;
    color:#337ab7;
}
.pagination {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}
.pagination li {
  display: inline;
  text-align: center;
}
.pagination a {
  float: left;
  display: block;
  font-size: 14px;
  text-decoration: none;
  padding: 5px 12px;
  color: #fff;
  margin-left: -1px;
  border: 1px solid transparent;
  line-height: 1.5;
}
.pagination a.current {
  cursor: default;
}
.pagination a:active {
  outline: none;
}

.modal-2 a.prev {
  -moz-border-radius: 50px 0 0 50px;
  -webkit-border-radius: 50px;
  border-radius: 50px 0 0 50px;
}
.modal-2 a.prev:after {
  content: '';
  position: absolute;
  width: 10px;
  height: 100%;
  top: 0;
  right: 0;
  background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.2) 100%);
  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.2) 100%);
  background-image: linear-gradient(to right, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.2) 100%);
}
.modal-2 a.next {
  -moz-border-radius: 0 50px 50px 0;
  -webkit-border-radius: 0;
  border-radius: 0 50px 50px 0;
}
.modal-2 a.next:after {
  content: '';
  position: absolute;
  width: 10px;
  height: 100%;
  top: 0;
  left: 0;
  background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
}
.modal-2 a {
  border-color: #ddd;
  color: #999;
  background: #fff;
}
.modal-2 a:hover {
  color: #E34E48;
  background-color: #eee;
}
.modal-2 a.current, .modal-2 a:active {
  border-color: #E34E48;
  background: #E34E48;
  color: #fff;
}

js部分(直接放在body標籤的最後即可):

    <script type="text/javascript">
        elements=parseInt($("input[name='elements']").val());	//總元素
        currentpage_str=$("input[name='currentpage']").val();	//當前page/初始page
        if(currentpage_str===""){
            currentpage=1;
        }else{
            currentpage=parseInt(currentpage_str);
        }

        var $li=$(".pagination").children("li");
        var masks = {};
        var format_buff="";
        $li.each(function(i) {
            if (0 === i) {
                masks.prev = this.innerHTML;
                format_buff += "<";
            } else if(1 === i) {
                masks.first = this.innerHTML;
                format_buff += "["
            } else if (i === $li.length - 2) {
                masks.last=this.innerHTML;
                format_buff += "]"
            } else if (i + 1 === $li.length) {
                masks.next = this.innerHTML;
                format_buff += ">";
            } else {
                masks[i-1] = this.innerHTML.replace(/#[nc]/, function(str) {
                    format_buff += str.replace("#", "");
                    return "([...])";
                });
            }
        });

        pages = 1 + Math.ceil((elements - 16) / (16 - 0));    //自行計算總頁數(16是每頁最多顯示的商品數,自行設定)
        $("#output").html("You are on page "+currentpage+"/"+pages);

        var pager=$("#paging").paging(elements,{
            perpage:16,    //每頁最多顯示16個商品(可自行設定)
            page:currentpage,
            format:format_buff,

            onClick:function(ev){
                ev.preventDefault();    //阻止ev元素髮生預設的行為,比如表單的提交、URL的開啟
                var cpage=$(this).data('page');    //切換頁面

                //Call asynchronously,could be ajax,or whatever
                window.setTimeout(function(){   //500毫秒後......
                    pager.setPage(cpage);    //跳轉頁面

                    //可以自行新增切換頁面以後的動作
                },500);
            },

            //Typical onFormat handler
            onFormat:function(type){
                var value = "";
                switch (type) {
                    case 'block':
                        value = masks[this["pos"]].replace("([...])", this["value"]);
                        //沒有被啟用
                        if (!this['active'])
                            return '<li><a href="#">' + value + '</a></li>';
                        //已經啟用,但不是初始的current,需要跳轉
                        if (this["page"] !== this["value"])
                            return '<li><a href="#' + this["value"] + '">' + value + '</a></li>';
                        //已經啟用,初始的current
                        return '<li><a href="#" class="current">' + value + '</a></li>';
                    case 'next':
                        if (!this['active'])
                            return '<li><a href="#" class="next">' + masks[type] + '</a></li>';
                        return '<li><a href="#' + this["value"] + '" class="next">' + masks[type] + '</a></li>';
                    case 'prev':
                        if (!this['active'])
                            return '<li><a href="#" class="prev">' + masks[type] + '</a></li>';
                        return '<li><a href="#' + this["value"] + '" class="prev">' + masks[type] + '</a></li>';
                    case 'first':
                        if (!this['active'])
                            return '<li><a href="#" class="first">' + masks[type] + '</a></li>';
                        return '<li><a href="#' + this["value"] + '" class="first">' + masks[type] + '</a></li>';
                    case 'last':
                        if (!this['active'])
                            return '<li><a href="#" class="last">' + masks[type] + '</a></li>';
                        return '<li><a href="#' + this["value"] + '" class="last">' + masks[type] + '</a></li>';
                }
            }
        });
    </script>

servlet部分:
得到當前頁引數page後,選擇資料庫中相應頁資料即可,例:select * from product_info limit (page-1)*perpage,perpage

補充:jquery.paging.js檔案中的下面這段程式碼,其實就是設定頁面跳轉功能的,我修改了prev和next的程式碼(註釋程式碼為原始碼),主要是為了設定向前/後翻頁時,一次性翻perpage頁,而不是1頁;(block就是普通頁碼)

switch (node.ftype) {
                        case "block":
                            for (; rStart < rStop; ++rStart) {

                                data["value"]  = rStart;
                                data["pos"]    = 1 + format.blockwide - rStop + rStart;

                                data["active"] = rStart <= pages || number < 0;     // true if infinity series and rStart <= pages
                                data["first"]  = 1 === rStart;                      // check if it is the first page
                                data["last"]   = rStart === pages && 0 < number;    // false if infinity series or rStart != pages

                                buffer_append(opts, data, node.ftype);
                            }
                            continue;

                        case "left":
                            data["value"]  = node.fpos;
                            data["active"] = node.fpos < rStart; // Don't take group-visibility into account!
                            break;

                        case "right":
                            data["value"]  = pages - format.rights + node.fpos;
                            data["active"] = rStop <= data["value"]; // Don't take group-visibility into account!
                            break;

                        case "first":
                            data["value"]  = 1;
                            data["active"] = tmp && 1 < page;
                            break;

                        case "prev":
                            if ((data["active"] = opts["circular"])) {
                                data["value"]   = page === 1 ? pages : page - 1;
                            } else {
                                //data["value"]   = Math.max(1, page - 1);
                                data["value"]   = Math.max(1, page - opts.perpage);
                                data["active"]  = tmp && 1 < page;
                            }
                            break;

                        case "last":
                            if ((data["active"] = (number < 0))) {
                                data["value"]   = 1 + page;
                            } else {
                                data["value"]   = pages;
                                data["active"]  = tmp && page < pages;
                            }
                            break;

                        case "next":
                            if ((data["active"] = opts["circular"])) {
                                data["value"]  = 1 + page % pages;
                            } else if ((data["active"] = (number < 0))) {
                                data["value"]   = 1 + page;
                            } else {
                                //data["value"]   = Math.min(1 + page, pages);
                                data["value"]   = Math.min(opts.perpage + page, pages);
                                data["active"]  = tmp && page < pages;
                            }
                            break;

                        case "leap":
                        case "fill":
                            data["pos"]    = node.fpos;
                            data["active"] = tmp; // tmp is true by default and changes only for group behaviour
                            buffer_append(opts, data, node.ftype);
                            continue;
                    }