Response简介:
部分方法:
//设置状态码
response.setStatus(1);
//设置头部信息
response.setHeader("content-Type", "html/text;charset=utf-8");
//设置返回数据类型
response.setContentType("");
//设置字符输出流
response.getWriter();
//设置字节输出流
response.getOutputStream();
下载文件配置:
//告诉浏览器是下载文件
response.setHeader("content-disposition", "attachment;filename="+file.getName());
java代码
package com.register.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ResponseServlet
*/
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DownloadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1 读取文件
// File file=new File("F:/MyPro/javaStudy/registerDemo/src/image.jpg");//获取
// FileInputStream is=new FileInputStream(file);
// //告诉浏览器是下载文件
// response.setHeader("content-disposition", "attachment;filename="+file.getName());
//
// ServletOutputStream sos = response.getOutputStream();
// int len=0;
// byte[] btye=new byte[1024*4];
// while ((len=is.read(btye))!=-1) {
// sos.write(btye, 0, len);
// }
//2 使用类加载器
// InputStream is = DownloadServlet.class.getClassLoader().getResourceAsStream("image.jpg");
//告诉浏览器是下载文件
// response.setHeader("content-disposition", "attachment;filename="+file.getName());
// ServletOutputStream sos = response.getOutputStream();
// int len=0;
// byte[] btye=new byte[1024*4];
// while ((len=is.read(btye))!=-1) {
// sos.write(btye, 0, len);
// }
// 自动获取路径 :D:\apache-tomcat-8.0.29\webapps\registerDemo\image.jpg
ServletContext application=getServletContext();
String realpath=application.getRealPath("image.jpg");
System.out.println(realpath);
File file=new File(realpath);//获取
FileInputStream is=new FileInputStream(file);
//告诉浏览器是下载文件
response.setHeader("content-disposition", "attachment;filename="+file.getName());
ServletOutputStream sos = response.getOutputStream();
int len=0;
byte[] btye=new byte[1024*4];
while ((len=is.read(btye))!=-1) {
sos.write(btye, 0, len);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
文件:image.jpg 在工程src中 和webwebContent中各一份