servlet之批量下载

来源:互联网 发布:淘宝定金不退怎么投诉 编辑:程序博客网 时间:2024/04/29 01:57

上一篇文章里面,我介绍了servlet的上传和下载,但都是针对于单个文件上传下载的,今天我介绍一下,批量下载,基本原理还是单个文件下载,批量只是循环执行一下

1、新建一个servlet

package com.wepull.servlet2;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BatchServlet extends HttpServlet {/** * Constructor of the object. */public BatchServlet() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {  doPost(request,response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setCharacterEncoding("utf-8");String path=this.getServletContext().getRealPath("/down");File f=new File(path);File[] fs=f.listFiles();PrintWriter pw=response.getWriter();for (int i = 0; i < fs.length; i++) {System.out.println(fs[i]);pw.println("<a href='down?fileName="+fs[i].getName()+"'>下载 "+fs[i].getName()+"</a><br>");}}public void init() throws ServletException {// Put your code here}}


2.配置servlet

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">     <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>BatchServlet</servlet-name>    <servlet-class>com.wepull.servlet2.BatchServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>BatchServlet</servlet-name>    <url-pattern>/batch</url-pattern>  </servlet-mapping>    <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

3.新建页面并命名为batch.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><a href="batch">批量下载</a ></body></html>


4.部署并测试,在地址栏输入http://localhost:8000/TestServlet/batch.jsp(我的端口为8000)

 

原创粉丝点击