我爱Java系列---【分页查询】
生活随笔
收集整理的這篇文章主要介紹了
我爱Java系列---【分页查询】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、需求
查詢每個分類下的商品詳情
二、實現步驟
- 菜單頁面拼接超鏈接,傳遞商品分類主鍵
- 分類商品頁面接收分類主鍵數據,向服務器發送AJAX請求
- Servlet接收客戶端分類主鍵的數據
- 調用業務層方法組裝PageBean數據
- 業務層調用持久層方法,分頁查詢數據表
- Servlet接收業務層返回的PageBean數據,轉成JSON響應客戶端
三、代碼如下
用到的jquery工具,用的時候封裝成jquery-heima-0.0.1.js,并引入當前頁面,可以直接HM.ajax(url,data,function(vo){})
?
$.ajaxSetup({type:"post",/*xhrFields: {withCredentials: true},*/error:function (xhr, textStatus, errorThrown) {if(xhr.status==0){console.log("親,請檢查后臺服務器是否啟動...手動滑稽")}if(xhr.status==404){console.log("親,請檢查請求地址是否正確...手動滑稽")}if(xhr.status==405){console.log("親,請檢查你是否實現了doPost方法...手動滑稽")}}})var HM={CTX:"http://api.itheima349.com",getParameter:function(name){var pvalues=this.getParameterValues(name);return pvalues==null?null:pvalues[0];},getParameterValues:function(name){return this.getParameterMap()[name];},getParameterMap:function(){var url = location.search; var HMRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { var pname=strs[i].split("=")[0];var pvalue=unescape(strs[i].split("=")[1]);var pvalues=null;if(HMRequest[pname]==null){HMRequest[pname]=new Array(pvalue)}else{HMRequest[pname].push(pvalue);}} } return HMRequest;},isLogin:function(){return this.cookie("JSESSIONID")==null?false:true;},cookie:function (name) {return this.cookies()[name];},cookieValue:function(name){var cookie=this.cookie(name);if(cookie==null){return null;}else{return cookie.value;}},cookies:function () {var cookiesStr = document.cookie ? document.cookie.split('; ') : [];var cookies={};for (var i = 0; i < cookiesStr.length; i++) {var parts = cookiesStr[i].split('=');var cookie = {"name":parts[0],"value":decodeURIComponent(parts[1])};cookies[parts[0]]=cookie;}return cookies;},ajax:function(url,parameter,fn){$.ajax({url:this.CTX+url,type:"post",dataType:"json",data:parameter,xhrFields: {//允許接受從服務器端返回的cookie信息 ,默認值為false 也就是說如果必須設置為true的時候 才可以接受cookie 并且請求帶上withCredentials: true},success:function (vo,status,xhr) {/*if(vo.code==2){console.log("請檢查請求方法是否存在");return;}if(vo.code==3){console.log("請檢查您的服務端控制錯誤日志");return;}*///處理登錄的filterif(true){fn(vo,status,xhr);}}})},ajaxFile:function(url,formId,fn){var formData = new FormData($("#"+formId)[0]);$.ajax({type: 'post',url:this.CTX+url,dataType:'text',data:formData,contentType:false,processData:false, success:function(data,status,xhr){//處理登錄的filterif(true){fn(data,status,xhr);}}})},page:function(pb,url){if(url.indexOf("?") != -1){//帶參數}else{//不帶參數url+="?_t="+new Date().getTime();}var pageHTML="";if(pb.pageNumber==1){pageHTML+="<li class=\"disabled\"><a href=\"javascript:;\" aria-label=\"Previous\"><span aria-hidden=\"true\">?</span></a></li>\n";}else{pageHTML+="<li ><a href=\""+url+"&pageNumber="+(pb.pageNumber-1)+"\" aria-label=\"Previous\"><span aria-hidden=\"true\">?</span></a></li>\n";}for(var i=pb.start;i<=pb.end;i++){if(i==pb.pageNumber){pageHTML+="<li class='active'><a href='javascript:;' >"+i+"</a></li>"}else{pageHTML+="<li ><a href='"+url+"&pageNumber="+i+"'>"+i+"</a></li>"}}if(pb.pageNumber==pb.totalPage){pageHTML+="<li class=\"disabled\" ><a href=\"javascript:;\" aria-label=\"Next\"><span aria-hidden=\"true\">?</span></a></li>"}else{pageHTML+="<li><a href='"+url+"&pageNumber="+(pb.pageNumber+1)+"' aria-label=\"Next\"><span aria-hidden=\"true\">?</span></a></li>"}return pageHTML; },time2str:function(t){var date=new Date(t);return ""+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();} }?JAVA中用到的PageBean類
package com.itheima.domain;import java.util.List;public class PageBean<T> {private List<T> data;private int total;private int pageSize;private int totalPage;private int pageNumber;private int start;private int end;private int showNum=10;public int getShowNum() {return showNum;}public void setShowNum(int showNum) {this.showNum = showNum;}public List<T> getData() {return data;}public void setData(List<T> data) {this.data = data;}public int getTotal() {return total;}public void setTotal(int total) {this.total = total;}public int getPageSize() {return pageSize;}public void setPageSize(int pageSize) {this.pageSize = pageSize;}public int getTotalPage() {return (int) Math.ceil(total*1.0/pageSize);}public int getPageNumber() {return pageNumber;}public void setPageNumber(int pageNumber) {this.pageNumber = pageNumber;}public int getStart() {return getRange()[0];}public int getEnd() {return getRange()[1];}private int[] getRange(){totalPage=getTotalPage();//開始計算前后可以留幾個//如果為奇數 7 3-3//如果為偶數 8 4-3int pre=showNum%2==0?showNum/2:showNum/2;int suf=showNum%2==0?showNum/2-1:showNum/2;//計算前后的滿足情況//前后的個數已定//前后都滿足的情況if(totalPage-pageNumber>=suf&&pageNumber-1>=pre){start=pageNumber-pre;end=pageNumber+suf;return new int[]{start,end};}//前面不滿足的情況if(pageNumber-1<pre&&totalPage-pageNumber>=suf){start=1;//前面缺失的個數int preNum=pre-pageNumber+1;end=pageNumber+suf+preNum>totalPage?totalPage:pageNumber+suf+preNum;return new int[]{start,end};}//后面的不滿足if(totalPage-pageNumber<suf&&pageNumber-1>=pre){end=totalPage;//后面缺失的個數int sufNum=pageNumber+suf-totalPage;start=pageNumber-pre-sufNum<1?1:pageNumber-pre-sufNum;return new int[]{start,end};}//都不滿足if(totalPage-pageNumber<suf&&pageNumber-1<pre){return new int[]{1,totalPage};}return new int[]{1,1};}}?
?
?
? header頁面添加連接
HM.ajax("/category?method=findAll","",function(data){ var str = "" var cateData = data.obj; $(cateData).each(function(i,element){ str= "<li><a href=\"http://www.itheima326.com:8020/web/view/product/list.html? cid=" +element.cid+"\">" +element.cname+"</a></li>" $("#cate_list").append(str); });list 商品分頁展示頁面
?
$(function(){ //獲取菜單傳遞的商品分類主鍵數據集 var cid = HM.getParameter("cid"); //獲取當前的頁數 var currentNumber = HM.getParameter("currentNumber"); if(currentNumber==null){ //默認第一頁 currentNumber=1; } var param = "cid="+cid+"¤tNumber="+currentNumber; HM.ajax("/product?method=findByPage",param,function(data){ //取出返回pagebean的數據 //取出商品數據 var products = data.obj.list; $.each(products, function(i,element) { var s = "<div class=\"col-md-2\" style=\"text-align:center;height:200px;padding:10px 0px;\">\n" + "\t\t\t\t\t\t<a href=\"http://www.itheima326.com:8020/web/view/product/info.html?pid="+element.pid+"\">\n" + "\t\t\t\t\t\t\t<img src=\"http://www.itheima326.com:8020/web/"+element.pimage+"\" width=\"130\" height=\"130\" style=\"display: inline-block;\">\n" + "\t\t\t\t\t\t</a>\n" + "\t\t\t\t\t\t<p><a href=\"http://www.itheima326.com:8020/web/view/product/info.html?pid="+element.pid+"\" style='color:#666'>"+element.pname+"</a></p>\n" + "\t\t\t\t\t\t<p><font color=\"#E4393C\" style=\"fontsize:16px\">¥"+element.shop_price+"</font></p>\n" + "\t\t\t\t\t</div>"; $("#products").append(s); }); var pb=data.obj; //拼接分頁字符串 ProductServlet var page = ""; //判斷第一頁 if(pb.currentNumber==1){ page+="<li class='disabled'><a href='javascript:;' aria-label='Previous'><span ariahidden='true'>?</span></a></li>"; }else{ page+="<li><a href='http://www.itheima326.com:8020/web/view/product/list.html? cid="+cid+"¤tNumber="+(pb.currentNumber-1)+"' aria-label='Previous'><span ariahidden='true'>?</span></a></li>"; } //拼接頁碼 for(var i=1;i<=pb.totalPage;i++){ //判斷當前頁 if(i==pb.currentNumber){ page+="<li class='active'><a href='javascript:;'>"+i+"</a></li>"; }else{ page+="<li><a href='http://www.itheima326.com:8020/web/view/product/list.html? cid="+cid+"¤tNumber="+i+"'>"+i+"</a></li>"; } } //判斷最后一頁 if(pb.currentNumber==pb.totalPage){ page+="<li class='disabled'><a href='javascript:;' aria-label='Next'><span ariahidden='true'>?</span></a></li>"; }else{ page+="<li><a href='http://www.itheima326.com:8020/web/view/product/list.html? cid="+cid+"¤tNumber="+(pb.currentNumber+1)+"' aria-label='Next'><span ariahidden='true'>?</span></a></li>"; } $("#page").html(page); }); })?
?ProductServlet
?
/** * 根據商品分類信息 * 分頁查詢數據 * 封裝PageBean對象 */ public void findByPage(HttpServletRequest request,HttpServletResponse response)throws IOException{ //獲取分類主鍵 String cid = request.getParameter("cid"); //獲取當前頁數 int currentNumber = Integer.parseInt(request.getParameter("currentNumber")); //定義每頁顯示條數10 int pageSize = 10; ProductService ProductDao //調用業務層方法,獲取PageBean PageBean<Product> pageBean = service.findByPage(cid, currentNumber, pageSize); Result re = new Result(pageBean); response.getWriter().print(JSONObject.fromObject(re)); }?
?ProductService
?
/** * 接收分類id * 當前頁數和每頁條數 * 查詢數據表,封裝PageBean對象 */ public PageBean<Product> findByPage(String cid,int currentNumber,int pageSize){ //分頁查詢數據表,返回集合 List<Product> productList = productDao.findByPage(cid, currentNumber, pageSize); //查詢分類商品總數 int totalCount =(int) productDao.getTotalCount(cid); //封裝PageBean對象 PageBean<Product> pageBean = new PageBean<Product>(); //當前頁數 pageBean.setCurrentNumber(currentNumber); //總條數 pageBean.setTotalCount(totalCount); //每頁個數 pageBean.setPageSize(pageSize); //計算總頁數 int totalPage = (int)Math.ceil(totalCount/pageSize*1.0); pageBean.setTotalPage(totalPage); //存儲商品數據 pageBean.setList(productList); return pageBean; }?
?ProductDao
?
/** * 查詢該分類下的所有商品的總數 * 傳遞參數,分類id */ public long getTotalCount(String cid){ String sql = "select count(*) from product where cid=?"; return template.queryForObject(sql,Long.class,cid); } /** * 分頁查詢商品數據 * 傳遞參數,分類id * 當前頁數,每頁顯示的條數 */ public List<Product> findByPage(String pid,int currentNumber,int pageSize){ String sql = "select * from product where cid=? limit ?,?"; return template.query(sql,new BeanPropertyRowMapper<Product>(Product.class), pid,(currentNumber-1)*pageSize,pageSize); }?
?Redis優化菜單查詢
菜單對于一個網站系統,基本上變化非常小,每次用戶訪問都去讀取數據庫效率很低,也浪費資源.將菜單存儲在redis
數據庫中,每次用戶訪問只要從內存數據庫中讀取菜單即可.
?
public List<Category> findAll(){ //先查詢redis數據庫 //如果不存在,查詢MySQL數據庫,存儲到redis中,再返回 Jedis jedis = JedisUtils.getConnection(); String category = jedis.get("category"); if(category==null){ List<Category> categoryList = categoryDao.findAll(); jedis.set("category", JSONArray.fromObject(categoryList).toString()); return categoryList; }else{ JSONArray jsonObject = JSONArray.fromObject(category); List<Category> list = JSONArray.toList(jsonObject,Category.class); return list; } }?
轉載于:https://www.cnblogs.com/hujunwei/p/11046544.html
總結
以上是生活随笔為你收集整理的我爱Java系列---【分页查询】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何启用dhcp linux,怎么开启D
- 下一篇: python医院管理系统代码_php医院