请求转发和重定向

含义

  • 重定向(Redirect)就是通过各种方法将各种网络请求重新定个方向转到其它位置(如:网页重定向、域名的重定向、路由选择的变化也是对数据报文经由路径的一种重定向)
  • 请求转发是服务器内部进行转发。

图片比较

  • 这里写图片描述
  • 请求转发:是在客户端发起请求后,在服务器之间的跳转,然后服务器返回页面给客户端进行显示。此时地址栏的地址没有进行改变。
  • 这里写图片描述
  • 重定向 客户端发起请求之后,服务器会将重定向的地址发给客户端,客户端将地址拿到之后,重新发起请求,服务器进行返回数据。地址栏的地址进行改变。

重定向内部原理

  • java是如何实现重定向
  • java里面使用这句话 resp.sendRedirect(url); 重定向。
  • *
 public void sendRedirect(String location) throws IOException {
        this.sendRedirect(location, 302);
    }

    public void sendRedirect(String location, int status) throws IOException {
        if (this.isCommitted()) {
            throw new IllegalStateException(sm.getString("coyoteResponse.sendRedirect.ise"));
        } else if (!this.included) {
            this.resetBuffer(true);

            try {
                String locationUri;
                if (this.getRequest().getCoyoteRequest().getSupportsRelativeRedirects() && this.getContext().getUseRelativeRedirects()) {
                    locationUri = location;
                } else {
                    locationUri = this.toAbsolute(location);
                }

                this.setStatus(status);
                this.setHeader("Location", locationUri);
                if (this.getContext().getSendRedirectBody()) {
                    PrintWriter writer = this.getWriter();
                    writer.print(sm.getString("coyoteResponse.sendRedirect.note", new Object[]{RequestUtil.filter(locationUri)}));
                    this.flushBuffer();
                }
            } catch (IllegalArgumentException var5) {
                log.warn(sm.getString("response.sendRedirectFail", new Object[]{location}), var5);
                this.setStatus(404);
            }

            this.setSuspended(true);
        }
    }

底层的实现方法如上,其实是 将状态改成 302 ,然后在返回头中添加一个 Location 的参数里面放请求转发的地址。当客户端收到这个返回后,拿到Location 里面的地址进行请求数据。地址栏的地址进行改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值