由於之前自己做過jquery分頁,就是調用jni接口時,只能用前台分頁解決顯示問題。最近看到有人提這樣的問題:一個請求傳過來上萬個數據怎麼辦?於是萌生了寫這篇博客的想法。
效果展示:
因為核心代碼主要在前端jquery,為了簡便,後台就用servlet遍歷本地磁盤目錄文件的形式模擬響應的數據。
本項目的目錄結構:
本項目的本地遍歷文件夾結構:
處理顯示請求的servlet:
package com.cn.action; import com.alibaba.fastjson.JSON; import com.cn.entity.Downloadfile; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by Nolimitors on 2017/3/17. */ public class PagesServlet extends HttpServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /** *@Author: Nolimitor *@Params: * @param req * @param resp *@Date: 17:55 2017/3/17 */ doPost(req,resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /** *@Author: Nolimitor *@Params: * @param req * @param resp *@Date: 17:55 2017/3/17 */ Properties props = new Properties(); InputStream in = new BufferedInputStream(new FileInputStream(this.getClass().getResource("/fileroot.properties").getPath())); props.load(in); String rootPath = props.getProperty("Root"); List fileList = new ArrayList(); File file = new File(rootPath); File []files = file.listFiles(); Downloadfile df = new Downloadfile(); for(File f:files) { df.setName(f.getName()); df.setFilesize(Long.toString(f.length())); System.out.println(f.getName()); fileList.add(JSON.toJSONString(df)); } resp.addHeader("Content-type","application/json"); resp.setHeader("content-type", "text/html;charset=UTF-8"); resp.getWriter().print(JSON.toJSONString(fileList)); } } PagesServlet
處理下載文件請求的servlet:
package com.cn.action; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.Properties; /** * Created by Nolimitors on 2017/3/20. */ public class DownloadFile extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //獲取所要下載文件的路徑 Properties props = new Properties(); InputStream in = new BufferedInputStream(new FileInputStream(this.getClass().getResource("/fileroot.properties").getPath())); props.load(in); String rootPath = props.getProperty("Root"); String name = req.getParameter("filename"); name = new String(name.getBytes("ISO8859-1"),"UTF-8"); System.out.println(name); //處理請求 //讀取要下載的文件 File f = new File(rootPath+"\\"+ name); if(f.exists()){ FileInputStream fis = new FileInputStream(f); String filename=java.net.URLEncoder.encode(f.getName(),"utf-8"); //解決中文文件名下載亂碼的問題 byte[] b = new byte[fis.available()]; fis.read(b); //解決中文文件名下載後亂碼的問題 resp.setContentType("application/x-msdownload"); resp.setHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes("utf-8"),"ISO-8859-1")); //獲取響應報文輸出流對象 ServletOutputStream out =resp.getOutputStream(); //輸出 out.write(b); out.flush(); out.close(); } } } DownloadFile
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>PageServlet</servlet-name> <servlet-class>com.cn.action.PagesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PageServlet</servlet-name> <url-pattern>/doPages</url-pattern> </servlet-mapping> <servlet> <servlet-name>DownServlet</servlet-name> <servlet-class>com.cn.action.DownloadFile</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app> web.xml
前台完整html代碼:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="/resource/juqery/css/base/jquery-ui-1.9.2.custom.css" rel="external nofollow" rel="stylesheet"> <link href="/resource/css/css.css" rel="external nofollow" rel="stylesheet"> <script type="application/javascript" src="/resource/common.js"></script> <script type="application/javascript" src="/resource/juqery/js/jquery-1.8.3.js"></script> <script type="application/javascript" src="/resource/juqery/js/jquery-ui-1.9.2.custom.js"></script> </head> <script type="application/javascript"> //請求一次數據,然後存儲到js變量中,保證只發送一條請求 var datas; jQuery(function() { $.ajax({ type: "POST", url: "/doPages", data: "{}", dataType: 'json', success: function(data) { datas = data; getPages(1,5); } }); }); //用於頁碼跳轉方法 function jumPage(totalPage,psize){ var cpage=jQuery("#page_no").val(); if(0< cpage && cpage <= totalPage){ getPages(cpage,psize); } else{ alert("Out of range"); } } function getPages(pno,psize) { var num;//分頁總行數 var totalPage = 0;//分頁總頁數 var pageSize = psize;//分頁每行顯示數 var currentPage = pno;//當前頁 num = parseInt(datas.length);//獲取數據行數 if (num / pageSize > parseInt(num / pageSize)) { totalPage = parseInt(num / pageSize) + 1; } else { totalPage = parseInt(num / pageSize); } var startRow = (currentPage - 1) * pageSize + 1;//開始顯示的行 var endRow = currentPage * pageSize;//結束顯示的行 endRow = (endRow > num) ? num : endRow; var tbody = jQuery("#list_data>tbody"); tbody.empty(); jQuery.each(datas, function (i, n) { var file = JSON.parse(n); if (startRow <= parseInt(i + 1) && parseInt(i + 1) <= endRow) { var row = createRow().appendTo(tbody); //多選用,目前暫時未考慮 /* createColumn().html("<input type='checkbox' id="+"fileId"+(i+1)+" name='fileId'/>").appendTo(row);*/ createColumn().text(i + 1).appendTo(row); createColumn().text(file.name).appendTo(row); createColumn().text(getSize(file.filesize)).appendTo(row); var operationColumn = createColumn().appendTo(row); } //每次執行分頁代碼時需要將前一次分頁的判斷結果清空 jQuery("#last_page").removeAttr("onclick"); jQuery("#next_page").removeAttr("onclick"); //當前頁非第一頁時 if (currentPage > 1) { jQuery("#last_page").attr("onclick", "getPages(" + (parseInt(currentPage) - 1) + "," + psize + ")"); } //當前頁小於總頁數時 if (currentPage < totalPage) { jQuery("#next_page").attr("onclick", "getPages(" + (parseInt(currentPage) + 1) + "," + psize + ")"); } //顯示當前頁碼、總頁數及生成跳轉點擊事件 jQuery("#end_page").attr("onclick", "getPages(" + (totalPage) + "," + psize + ")"); jQuery("#first_page").attr("onclick", "getPages(" + (1) + "," + psize + ")"); jQuery("#jump_page").attr("onclick", "jumPage(" + (totalPage) + "," + psize + ")"); jQuery("#total_page").val("/" + totalPage + " 頁"); jQuery("#page_no").val(currentPage); var btnDownload = jQuery("<button class='btn_download'>下載</button>"); var btnDelete = jQuery("<button class='btn_delete'>刪除</button>"); //批量刪除獲取文件信息用,目前暫時不用 /*jQuery("#"+"fileId"+(i+1)).attr("recordQuery",JSON.stringify(recordQuery));*/ btnDownload.click(function () { location.href = "/download?filename=" + file.name; }); btnDelete.click(function () { recordQuery = jQuery(this).attr("data-record-query"); var dialogDiv = jQuery("<div></div>"); dialogDiv.dialog({ autoOpen: false, modal: true, width: 500, position: {my: "center", at: "center", of: jQuery(".content_wrapper_hidden")}, title: "文件刪除", buttons: [ { text: "確認", click: function () { jQuery.post("/delete", file.name, function (data) { location.reload(); }); jQuery(this).dialog("close"); } }, { text: "取消", click: function () { jQuery(this).dialog("close"); } } ] }); var text = "確認刪除 "+ file.name + "?"; dialogDiv.text(text).dialog("open"); }); btnDownload.appendTo(operationColumn); btnDelete.appendTo(operationColumn); }); jQuery(".btn_download,.btn_delete").button(); } function getSize(length) { var len, unit; if (length == 0) { len = 0; unit = "B"; } else if (length < 1024) { len = length; unit = "B"; } else if (length < (1024 * 1024)) { len = (length / 1024); unit = "KB"; } else { len = (length / 1024 / 1024); unit = "MB"; } return new Number(len).toFixed(2) + unit; } </script> <style> .data tbody tr td:first-child{ font-weight:bold; cursor: pointer; } </style> <body> <div class="main_wrapper"> <div class="content_wrapper_hidden"> <div class="ui_wrapper"> <table id="list_data" class="data" border="0" cellspacing="0" cellpadding="0" style="width: 100%"> <thead> <tr> <th >Num</th> <th >Files</th> <th >Size</th> <th >Operation</th> </tr> </thead> <tbody> </tbody> </table> <!-- 分頁用按鈕--> <table class="ui-corner-all grey" style="width: 100%"> <tbody align="center" valign="middle"> <tr><td><div id="pagination"> <!-- 全選和批量刪除按鈕,目前暫時未考慮--> <!--<input type="button" id='fileIds' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="全選"/><input type="button" id='delete_fileIds' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="刪除"/>--> <input type="button" id='first_page' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="首頁"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" id='last_page' value="上一頁"/><input type="button" id='next_page' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="下一頁"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" id='end_page' value="尾頁"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" id='jump_page' value="跳轉"/> <input autocomplete="off" class="ui-autocomplete-input" id="page_no" style="height: 20px;width:30px"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border: none" id='total_page' value="0 頁" /></div></td></tr> </tbody> </table> <!-- 分頁用按鈕--> </div> </div> </div> </body> </html>
分頁的核心jquery代碼:
function getPages(pno,psize) { var num;//分頁總行數 var totalPage = 0;//分頁總頁數 var pageSize = psize;//分頁每行顯示數 var currentPage = pno;//當前頁 num = parseInt(datas.length);//獲取數據行數 if (num / pageSize > parseInt(num / pageSize)) { totalPage = parseInt(num / pageSize) + 1; } else { totalPage = parseInt(num / pageSize); } var startRow = (currentPage - 1) * pageSize + 1;//開始顯示的行 var endRow = currentPage * pageSize;//結束顯示的行 endRow = (endRow > num) ? num : endRow; var tbody = jQuery("#list_data>tbody"); tbody.empty(); jQuery.each(datas, function (i, n) { var file = JSON.parse(n); if (startRow <= parseInt(i + 1) && parseInt(i + 1) <= endRow) { var row = createRow().appendTo(tbody); //多選用,目前暫時未考慮 /* createColumn().html("<input type='checkbox' id="+"fileId"+(i+1)+" name='fileId'/>").appendTo(row);*/ createColumn().text(i + 1).appendTo(row); createColumn().text(file.name).appendTo(row); createColumn().text(getSize(file.filesize)).appendTo(row); var operationColumn = createColumn().appendTo(row); } //每次執行分頁代碼時需要將前一次分頁的判斷結果清空 jQuery("#last_page").removeAttr("onclick"); jQuery("#next_page").removeAttr("onclick"); //當前頁非第一頁時 if (currentPage > 1) { jQuery("#last_page").attr("onclick", "getPages(" + (parseInt(currentPage) - 1) + "," + psize + ")"); } //當前頁小於總頁數時 if (currentPage < totalPage) { jQuery("#next_page").attr("onclick", "getPages(" + (parseInt(currentPage) + 1) + "," + psize + ")"); } //顯示當前頁碼、總頁數及生成跳轉點擊事件 jQuery("#end_page").attr("onclick", "getPages(" + (totalPage) + "," + psize + ")"); jQuery("#first_page").attr("onclick", "getPages(" + (1) + "," + psize + ")"); jQuery("#jump_page").attr("onclick", "jumPage(" + (totalPage) + "," + psize + ")"); jQuery("#total_page").val("/" + totalPage + " 頁"); jQuery("#page_no").val(currentPage); var btnDownload = jQuery("<button class='btn_download'>下載</button>"); var btnDelete = jQuery("<button class='btn_delete'>刪除</button>"); //批量刪除獲取文件信息用,目前暫時不用 /*jQuery("#"+"fileId"+(i+1)).attr("recordQuery",JSON.stringify(recordQuery));*/ btnDownload.click(function () { location.href = "/download?filename=" + file.name; }); btnDelete.click(function () { recordQuery = jQuery(this).attr("data-record-query"); var dialogDiv = jQuery("<div></div>"); dialogDiv.dialog({ autoOpen: false, modal: true, width: 500, position: {my: "center", at: "center", of: jQuery(".content_wrapper_hidden")}, title: "文件刪除", buttons: [ { text: "確認", click: function () { jQuery.post("/delete", file.name, function (data) { location.reload(); }); jQuery(this).dialog("close"); } }, { text: "取消", click: function () { jQuery(this).dialog("close"); } } ] }); var text = "確認刪除 "+ file.name + "?"; dialogDiv.text(text).dialog("open"); }); btnDownload.appendTo(operationColumn); btnDelete.appendTo(operationColumn); }); jQuery(".btn_download,.btn_delete").button(); }
用於頁面跳轉的js代碼:
//用於頁碼跳轉方法 function jumPage(totalPage,psize){ var cpage=jQuery("#page_no").val(); if(0< cpage && cpage <= totalPage){ getPages(cpage,psize); } else{ alert("Out of range"); } }
計算文件的大小js:
function getSize(length) { var len, unit; if (length == 0) { len = 0; unit = "B"; } else if (length < 1024) { len = length; unit = "B"; } else if (length < (1024 * 1024)) { len = (length / 1024); unit = "KB"; } else { len = (length / 1024 / 1024); unit = "MB"; } return new Number(len).toFixed(2) + unit; }
頁面默認請求jquery:
//請求一次數據,然後存儲到js變量中,保證只發送一條請求 var datas; jQuery(function() { $.ajax({ type: "POST", url: "/doPages", data: "{}", dataType: 'json', success: function(data) { datas = data; getPages(1,5); } }); });
項目中用到了便於生成table的自己編寫的js工具:
function createColumn() { return jQuery("<td></td>"); } function createRow() { return jQuery("<tr></tr>"); } function createEle(tag){ return jQuery("<"+tag+"></"+tag+">"); } function reload(){ window.location.reload(); } function toURL(url){ window.location.href=url; } function isString(obj){ return typeof(obj) == "string"; } function isObject(obj){ return typeof(obj) == "object"; } function fillSelect(select, data, valueKey, textKey){ var $select = isString(select) ? jQuery(select) : select; $select.empty(); jQuery.each(data, function(i, item){ var value = (!isString(item)) ? item[valueKey] : item; var text = (!isString(item)) ? item[textKey] : item; var $op = createEle("option").appendTo($select); $op.text(text).val(value); }) } common.js
為了美觀考慮,項目中引用了jquery UI:
代碼.GitHub:https://github.com/Wenchaozou/JqueryForPages
百度雲鏈接:https://pan.baidu.com/s/1dE5Cj5n
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持!