Response对象

  • 功能:设置响应消息
  1. 设置响应行
  1. 格式:HTTP/1.1 200 ok
  2. 设置状态码:setStatus(int sc)
  1. 设置响应头:setHeader(String name,String value)
  2. 设置响应体
  • 使用步骤
  1. 获取输出流
  • 字符输出:PrintWrite getWriter()
  • 字节输出流:ServletOutputStream getOutStream()
  1. 使用输出流,将数据输出到客户端浏览器
  • 案例
  1. 完成重定向
  1. 重定向:资源跳转的方式
  2. 代码实现
//方式一
        //设置状态码
        resp.setStatus(302);
        //设置响应头location
        resp.setHeader("location","/demo2");
        
        //方式二
        resp.sendRedirect("/demo2");
  1. 重定向(redirect)的特点
  1. 地址栏发生变化
  1. 重定向可以访问其他站点(服务器)的资源
  2. 重定向是两次请求,不可以使用request对象来共享数据
  3. 转发(forward)的特点
  1. 转发地址栏路径不变
  2. 转发只能访问当前服务器下的资源
  3. 转发是一次请求,可以使用request对象来共享数据
  1. 路径写法
  1. 路径分类
  1. 相对路径:通过相对路径不可以确定唯一资源
  • 如:./index.html
  • 不以/开头,以.开头路径
  • 规则:找到当前资源和目标资源之间的相对位置关系
  • ./:当前目录
  • ../:后退一级目录
  1. 绝对路径:通过绝对路径可以确定唯一资源
  • 如:http://localhost/webServlet 可以省略为/webServlet
  • 以/开头
  • 规则:判断定义的路径是给谁用的?
  • 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
  • 建议虚拟目录动态获取:request.getContextPath()
  • a标签和form标签 重定向。。。
  • 给服务器使用:不需要加虚拟目录
  • 转发
  1. 服务器输出字符数据到浏览器
  • 步骤
  1. 获取字符输出流
    PrintWriter pw = respond.getWriter();
  2. 输出数据
    pw.writer(String s);
  • 乱码问题
  1. PrintWriter pw = respond.getWriter();获取的流默认编码是ISO-8895-1
  2. 设置流的默认编码
  • response.setCharacterEnconding("utf-8");
  1. 告诉浏览器响应体使用的编码
  • response.setHeader("content-type","text/html;charset=utf-8");
  • 简单形式设置编码:response.setContentType("text/html;charset=utf-8");
  1. 服务器输出字节数据到浏览器
    步骤
  1. 获取字节输出流
    ServletOutputStream sos = response.getOutputStream();
  2. 输出数据
    sos.writer("你好".getBytes("utf-8"));
  • 乱码问题
  1. 设置流的默认编码
  • response.setCharacterEnconding("utf-8");
  1. 告诉浏览器响应体使用的编码
  • response.setHeader("content-type","text/html;charset=utf-8");
  • 简单形式设置编码:response.setContentType("text/html;charset=utf-8");
  1. 验证码
  1. 本质:图片
  1. 目的:防止恶意表单注册
  1. 代码
@WebServlet("/Demo3")
public class CheckCodeServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int width = 100;
        int height = 50;
        //1.创建一对象,在内存中创建图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
//        2.美化图片
//        2.1填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.PINK);//设置画笔颜色
        g.fillRect(0,0,width,height);
//        2.2画边框
        g.setColor(Color.BLUE);//设置画笔颜色
        g.drawRect(0,0,width-1,height-1);

        String str = "ABCDEFGHIJKLNMOPQRSTUVWXYZabcdefghijklnmopqrst1234567890";
//        生成随机角标
        Random ran = new Random();
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
//        获取字符
            char ch = str.charAt(index);
//        2.3写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }
//        2.4画干扰线
        g.setColor(Color.GREEN);
//        随机生成干扰线
        for (int i = 1; i <= 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y3 = ran.nextInt(height);
            int y4 = ran.nextInt(height);
            g.drawLine(x1,y3,x2,y4);
        }


//        将图片输出到页面展示
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}
  • ServletContext对象
  1. 概念:代表整个web应用,可以和程序的容器(服务器)通信
  2. 获取
  1. 通过request对象获取
    request.getServletContext();
  2. 通过HTTPServlet获取
    this.getServletContext();

  1. 功能
  1. 获取MIME类型
  • MIME类型:在互联网通信过程中定义的一种文件数据类型
  • 格式:大类型/小类型 text/html image/jpeg
  • 获取:String getMimeType(String file)
  1. 域对象:共享数据
  1. void setAttribute(String name,Object obj);存储数据
  2. getAttribute(String name):通过键获取值
  3. void renoveAttribute(String name):通过键移除键值对
  • ServletContext对象范围:所有用户的所有请求数据
  1. 获取文件的真实(服务器)路径
  • String getRealPath("/b.txt")
  1. 代码
public class ServletContextDemo1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.通过request对象获取
        ServletContext context1 = req.getServletContext();
//        2.通过HttpServlet对象获取
        ServletContext context2 = this.getServletContext();

        System.out.println(context1);
        System.out.println(context2);
        System.out.println(context1==context2);
        
        //获取MIME类型
         String filename = "haha.jpg";
       String mine  =  context1.getMimeType(filename);
        System.out.println(mine);
        //获取文件真实路径
        String realPath1 = context1.getRealPath("/a.txt");//web目录下的
        System.out.println(realPath1);
        String realPath2 = context1.getRealPath("/WEB-INF/b.txt");//WEB-INF目录下的
        System.out.println(realPath2);
        String realPath3 = context1.getRealPath("/WEB-INF/classes/c.txt");//src目录下的
        System.out.println(realPath3);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
  • 案例:文件下载
  • 文件下载需求
  1. 页面显示超链接
  2. 点击超链接后弹出下载提示框
  3. 完成图片文件下载
  • 分析
  1. 超链接指向的资源如果能被浏览器解析,则在浏览器中显示,如果不能解析,则弹出下载提示框。不满足需求
  2. 任何资源都必须弹出下载提示框
  3. 使用响应头设置资源的打开方式
  • 步骤
  1. 定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
  2. 定义Servlet
  1. 获取文件名称
  2. 使用字节输入流加载文件进内存
  3. 指定response的响应头:content-disposition:attachment;filename=xxx
  4. 将数据写出到response输出流
  • 问题
  • 中文文件问题
  • 解决思路
  1. 获取客户端使用的浏览器版本信息
  2. 根据不同的版本信息,设置filename的编码方式不同
  • 代码
package com.creat.test;

import com.creat.Utils.DownLoadUtils;

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;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");//获取请求下载的文件名
        String decodefilename = URLDecoder.decode(filename, "utf-8");
        //java中相同编解码规则对应的类为URLencode和URLdecode
        //这里使用URLDecoder类静态方法decode对文件名解码(请求路径中中文已被编码)

        ServletContext servletContext = getServletContext();//获取服务器域对象

        String mimeType = servletContext.getMimeType(decodefilename);//获取传输文件类型(一般文件在传输时有对应的类型,web.xml配置文件中列举了所有对应关系)
        response.setHeader("Content-Type",mimeType);//设置传输文件类型

        String agent = request.getHeader("User-Agent");//获取请求的浏览器类型
        String encodefilename = DownLoadUtils.getFileName(agent, decodefilename);//下载弹窗中文文件名会乱码,这里使用特殊方式编码

        response.setHeader("Content-Disposition","attachment;filename="+encodefilename);//设置客户端浏览器对文件以附件处理

        String realPath = servletContext.getRealPath("/"+decodefilename);//域对象获取文件真实路径

        FileInputStream inputStream=new FileInputStream(realPath);//创建输入流,加载要下载的文件进内存
        ServletOutputStream outputStream = response.getOutputStream();//创建输出流,写文件给客户端浏览器
        byte[]bys=new byte[1024*4];
        int len;
        while ((len=inputStream.read(bys))!=-1){
            outputStream.write(bys,0,len);
        }
        inputStream.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}