servlet文件下载

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了servlet文件下载相关的知识,希望对你有一定的参考价值。

一、创建servlet

package com.demo.log4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
	}

	public void doGet(HttpServletRequest req, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/plain");
		response.setHeader("Content-Disposition",
				"attachment; filename=demo.docx");
		OutputStream outputStream = response.getOutputStream();
		File file = new File("D:\\demo.docx");
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int i = -1;
			while ((i = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, i);
			}
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
	}

	public void destroy() {
	}
}

二、配置web.xml

<servlet>
	<servlet-name>download</servlet-name>
	<servlet-class>com.demo.log4j.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>download</servlet-name>
	<url-pattern>/download</url-pattern>
</servlet-mapping>

三、下载文件

  浏览器访问地址

http://127.0.0.1:8080/download

以上是关于servlet文件下载的主要内容,如果未能解决你的问题,请参考以下文章

JSP 学习笔记

JSP基础学习

filter与servlet

JSP是什么?

servlet和filter的区别

Java基础——JSP