zoukankan      html  css  js  c++  java
  • Response对象

    功能:设置响应消息

    1. 设置响应行
      1. 格式:HTTP/1.1 200 ok
      2. 设置状态码:void setStatus(int sc)
    2. 设置响应头:void setHeader(String name, String value)
    3. 设置响应体:
      • 使用步骤:
        1. 获取输出流
          • 字符输出流:PrintWriter getWriter()
          • 字节输出流:ServletOutputStream getOutputStream()
        2. 使用输出流,将数据输出到客户端浏览器

    案例

    完成重定向

    • 重定向:资源跳转的方式

      // 动态获取虚拟目录
      String contextPath = req.getContextPath();
      resp.sendRedirect(contextPath+"/Servlet资源路径");
      
    • 代码实现:

      /*
              // 1.设置状态码为302 重定向
              resp.setStatus(302);
              // 2.设置响应头location
              resp.setHeader("location", "/day15/responseDemo2");
      */
      
              // 简单的重定向方法
              resp.sendRedirect("/day15/responseDemo2");
      
    • 重定向的特点:redirect

      1. 地址栏路径发生变化
      2. 重定向可以访问其他站点(服务器)的资源
      3. 重定向是两次请求,不能使用request对象来共享数据
    • 转发的特点:forward

      1. 地址栏路径不变
      2. 转发只能访问当前服务器下的资源
      3. 转发是一次请求,可以使用一个request对象来共享数据
    • forward 和 redirect 的区别(将来面试题会这样问?)

    • 请求转发

    请求转发

    • 重定向

    重定向

    • 路径写法(重要):

    路径分类

    1. 相对路径:通过相对路径不可以确定唯一资源
      • 如:./index.html
      • 不以 / 开头,以 . 开头路径
    <!-- 不写,默认是以./开头 -->
    <a href="./responseDemo2">
    <a href="../responseDemo2">
    
      * 规则:找到当前资源和目标资源之间相对位置关系
          * `./`:当前目录
          * `../`:后退一级目录
    
    1. 绝对路径:通过绝对路径可以确定唯一资源
      • 如:http://localhost/day15/responseDemo2 /day15/responseDemo2
      • 以 / 开头的路径
      • 规则:判断定义的路径是给谁用的?判断请求将来从哪发出
        • 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
          • 建议虚拟目录动态获取:request.getContextPath();
          • <a><form>,重定向...
        • 给服务器使用:不需要加虚拟目录
          • 转发路径

    后期写 jsp页面时,推荐使用绝对路径写法,因为相对路径写起来比较麻烦

    服务器输出字符数据到浏览器

    • 步骤:

      1. 获取字符输出流
      2. 输出数据
    • 注意:

      • 乱码问题:
        • 乱码原因:编码和解码使用的字符集不同
      1. PrintWriter pw = response.getWriter():获取的流的默认编码是 ISO-8859-1
      2. 设置该流的默认编码
      3. 告诉浏览器响应体使用的编码
    // 简单的形式,设置编码,是在获取流之前设置
    response.setContentType("text/html;charset=utf-8");
    
    • 示例
    // 获取流对象PrintWriter之前,设置流的默认编码:ISO-8859-1 设置为:GBK
    // resp.setCharacterEncoding("utf-8");
    
    // 告诉浏览器,服务器发送消息体的数据的编码,建议浏览器使用该编码解码
    // resp.setHeader("content-type", "text/html;charset=utf-8");
    /*
    resp.setHeader() 等效于
    resp.setCharacterEncodin() & resp.setHeader()两行
    */
    // 简单的形式,设置编码,是在获取流之前设置
    resp.setContentType("text/html;charset=utf-8");// 一行顶两行
    // 1.获取字节输出流
    PrintWriter pw = resp.getWriter();
    // 2.输出数据
    pw.write("<h1>hello response</h1>");
    pw.write("你好啊 response");
    

    服务器输出字节数据到浏览器

    • 步骤:

      1. 获取字节输出流
      2. 输出数据
    • 示例

    resp.setContentType("text/html;charset=utf-8");
    // 1.获取字节输出流
    ServletOutputStream sos = resp.getOutputStream();
    // 2.输出数据
    sos.write("你好".getBytes("utf-8")); // getBytes()默认使用的是gbk
    

    验证码

    /**
     * 生成验证码
     */
    @WebServlet("/checkCodeServlet")
    public class CheckCodeServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 1.创建一对象,代表内存中的图片(验证码图片对象)
            int width = 100;
            int height = 50;
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    
            // 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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            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 = 0; i < 10; i++) {
                int x1 = ran.nextInt(width);
                int x2 = ran.nextInt(width);
    
                int y1 = ran.nextInt(height);
                int y2 = ran.nextInt(height);
                g.drawLine(x1, y1, x2, y2);
            }
    
            // 3.将图片输出到页面展示
            ImageIO.write(image, "jpg", response.getOutputStream());
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    
  • 相关阅读:
    VSFTP配置参数详解
    C语言---函数
    ios 学习计划
    读书笔记---金融学一<新国富论>
    读书笔记---人生规划一<斯坦福最受欢迎的人生规划课、像卡耐基一样经营人生、九型人格>
    网络基础
    swift中构造方法和Kvc
    swift中的懒加载
    private的用法
    extension
  • 原文地址:https://www.cnblogs.com/rainszj/p/12188698.html
Copyright © 2011-2022 走看看