含义
- 重定向(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 里面的地址进行请求数据。地址栏的地址进行改变。