Response对象

Response的功能

设置响应行

  • 设置状态码:setStatus(int sc)

设置响应头

  • 设置头:setHeader(String name, String value)

设置响应体

使用步骤

  • 获取输出流
  • 字符输出流:PrintWriter getWriter()
  • 字节输出流:ServletOutputStream getOutputStream()
  • 使用输出流,将数据输出到客户端浏览器

Response的相关小案例

重定向

  • 重定向也是资源跳转的一种方式
  • 告诉浏览器要重定向,状态码302
  • 告诉浏览器B资源的路径:响应头location:B资源的路径
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    /**
     * 1.设置状态码为302
     * 2。设置响应头location
     */
    System.out.println("demo1...");
    resp.setStatus(302);
    resp.setHeader("location", "/day/cjd.demo2");
}

或者是写成下面的简单方式:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("demo1");
    resp.sendRedirect("/day/cjd.demo2");
}

重定向的与请求转发的特点

请求转发特点
  • 转发地址栏不变
  • 转发只能访问当前服务器下的资源
  • 转发是一次请求
  • 共享request对象当中的数据
重定向的特点
  • 地址栏发生变化
  • 重定向可以访问其他站点(其他服务器)的资源
  • 重定向是两次请求
  • 不能共享request对象当中的数据
目录的书写规则
  • 给客户端浏览器使用,需要添加虚拟目录。例如,重定向、<a><form>
  • 给服务器使用,不需要添加目录。例如,请求转发
  • 注意:为了方便项目虚拟路径的修改,虚拟路径我们经常采用request.getContextPath()方法来获取虚拟目录

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

  • 获取字符输出流
  • 输出数据
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.getWriter().write("hello, world!");
    resp.getWriter().print("Hello, World!");
}

为了保证中文字符不会出现乱码的情况,我们应该同时设置服务器编码和浏览器解码的字符集

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("utf-8");
    resp.setHeader("Content-Type", "text/html;charset=utf-8");
    resp.getWriter().write("你好");
}

亦或者是写成下面的简单形式

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html;charset=utf-8");
    resp.getWriter().write("你好");
}

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

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream outputStream = resp.getOutputStream();
    outputStream.write("hellow world!".getBytes());
}

解决中文乱码问题

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html;charset=utf-8");
    ServletOutputStream outputStream = resp.getOutputStream();
    outputStream.write("你好".getBytes("utf-8"));
}

验证码

  • 验证码的本质:是一张图片
  • 验证码的目的:防止恶意的表单注册
  • java后端代码
package cn.web;

import javafx.util.Pair;
import org.omg.CORBA.INTERNAL;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet(urlPatterns = {"/check"})
public class CheckCodeServlet extends HttpServlet {
    private static int WIDTH = 100;
    private static int HEIGHT = 50;
    private static String CHECK_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private Pair<Integer, Integer> getPosition() {
        int x = (int) (Math.random() * WIDTH);
        int y = (int) (Math.random() * HEIGHT);

        return new Pair<Integer, Integer>(x, y);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建对象,能够在内存当中代表一张图片
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        //2.美化图片
        /**
         * 1.填充背景色
         * 2.画出边框
         * 3.写验证码
         * 4.划线
         */
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.PINK);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
        graphics.setColor(Color.YELLOW);
        graphics.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        graphics.setColor(Color.BLUE);
        for (int i = 1; i <= 4; i++) {
            int index = (int) (Math.random() * CHECK_STRING.length());
            char ch = CHECK_STRING.charAt(index);
            graphics.drawString(ch + "", WIDTH / 5 * i, HEIGHT / 2);
        }

        graphics.setColor(Color.GREEN);
        for (int i = 0; i < 6; i++) {
            Pair<Integer, Integer> position1 = getPosition();
            Pair<Integer, Integer> position2 = getPosition();
            graphics.drawLine(position1.getKey(), position1.getValue(), position2.getKey(), position2.getValue());
        }

        //3.将图片输出到页面展示
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        //response.getOutputStream().write();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
  • html前端框架代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img id="code" src="/day/check">
    <a id="check" href="javascript:void(0);">看不清楚?换一张</a>
</body>

<footer>
    <script src="register.js"></script>
</footer>
</html>
  • js响应事件代码
var code = document.getElementById("code");
code.onclick = function () {
    var date = new Date().getTime();//在后面加一个时间戳来欺骗浏览器,使得浏览器更换图片
    this.src="/day/check?" + date;
};

var check = document.getElementById("check");
check.onclick = function () {
    var date = new Date().getTime();
    code.src="/day/check?" + date;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值