由于之前自己做过jquery分页,就是调用jni接口时,只能用前台分页解决显示问题。最近看到有人提这样的问题:一个请求传过来上万个数据怎么办?于是萌生了写这篇博客的想法。
效果展示:
因为核心代码主要在前端jquery,为了简便,后台就用servlet遍历本地磁盘目录文件的形式模拟响应的数据。
本项目的目录结构:
本项目的本地遍历文件夹结构:
处理显示请求的servlet:
}
protected void doPost(HttpServletRequest req,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();
protected void doPost(HttpServletRequest req,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:
获取所要下载文件的路径
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配置:
web.xml
前台完整HTML代码:
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
nofollow" rel="stylesheet">
nofollow" rel="stylesheet">
Num
Files
Size
Operation
首页"/>上一页"/>下一页"/>跳转"/>