一 location :***** 302 重定向
private void doWork(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置响应 code
resp.setStatus(302);
// 设置响应 header 参数 ,通知浏览器进行重定向
resp.setHeader("location", "index.jsp");
}
二 refresh :3;url=index.jsp 浏览器自动刷新
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置响应 header 参数,通知浏览器 3 秒后进行自动刷新,重定向至 url 指定地址
resp.setHeader("refresh","3;url=index.jsp"); }
三 content-type: image/png 告知浏览器调用哪个模块打开,比如:显示图片、显示 html 信息
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置 header 参数 ,告知浏览器调用何种模块打开
resp.setHeader("content-type", "image/png");
// 使用 IO 流返回图片字节信息
InputStream inputStream = new FileInputStream("E:\\trunck\\chapter02\\servletTest2\\web\\test.png");
int len = -1;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
resp.getOutputStream().write(bytes, 0, len);
}
inputStream.close(); }
四 Content-Disposition :attachment;filename=文件名 通知浏览器下载该文件
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File file=new File("E:\\trunck\\chapter02\\servletTest2\\web\\test.png");
// 设置 header 参数,通知浏览器下载该文件
resp.setHeader("Content-Disposition","attachment;filename="+file.getName());
InputStream inputStream=new FileInputStream(file);
int len = -1 ;
byte[] bytes=new byte[1024];
while ((len=inputStream.read(bytes))!=-1){
resp.getOutputStream().write(bytes,0,len);
}
inputStream.close();
}
五 content-encoding : gzip(服务器端响应过来的压缩模式) content-length :字节长度
Accept-Encoding: gzip, deflate (客户端通知服务端,浏览器所支持的压缩模式)
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Encoding
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String content = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
System.out.println("字符串长度:" + content.length());
System.out.println("字符串转数组长度:" + content.getBytes().length);
// IO 流中 ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(content.getBytes());
gzipOutputStream.close(); byte[] bytes = byteArrayOutputStream.toByteArray();
System.out.println("压缩后数组长度:" + bytes.length); resp.setHeader("content-encoding", "gzip");
resp.setHeader("content-length", bytes.length + "");
resp.getOutputStream().write(bytes); }
六 expires :-1(HTTP1.1的客户端和缓存必须将其他非法的日期格式(包括0)看作已经过期) cache-control:no-cache pragma:no-cache 告知浏览器不进行缓存
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("expires", "-1");
resp.setHeader("cache-control", "no-cache");
resp.setHeader("pragma", "no-cache"); resp.getWriter().write("abccc");
}