平常开发中时常用到重定向,正好借此总结一下,上面的图在开发中以及参考网上文章总结出来的(参考文章见文末)。
重定向
@RequestMapping(value = "/redirect",method = RequestMethod.GET)
@ResponseBody
public String redirect(HttpServletResponse response){
try {
response.sendRedirect("http://127.0.0.1:8080/api/redirect/test");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect";
}
@RequestMapping(value = "/redirect/test",method = RequestMethod.GET)
@ResponseBody
public String redirectTest(HttpServletRequest request, HttpServletResponse response){
return "redirect success";
}
项目启动成功后,在浏览器输入http://127.0.0.1:8080/api/redirect
,在chrome检查Network栏目下,可以看到:
客户端发生了两次接口请求,第一次是http://127.0.0.1:8080/api/redirect
,第二次是http://127.0.0.1:8080/api/redirect/test
;且第一次接口请求的响应状态码为302(重定向),从其请求、响应头中可以清晰交互流程:
从上面分析,重定向时,进行了两次接口请求;过程简单理解为浏览器首先请求接口A,接口A进行了重定向到B,接口A给浏览器的响应状态码为302,并且返回了目的接口地址B,然后浏览器再次发起请求,请求接口地址B.
转发
@RequestMapping(value = "/forward",method = RequestMethod.GET)
@ResponseBody
public String forward(HttpServletRequest request, HttpServletResponse response){
try {
request.getRequestDispatcher("/api/forward/test").forward(request,response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
return "index";
}
@RequestMapping(value = "/forward/test",method = RequestMethod.GET)
@ResponseBody
public String forwardTest(HttpServletRequest request, HttpServletResponse response){
return "forward success";
}
在浏览器中访问http://localhost:8080/api/forward
,会返回forward success
,在chrome检查Network栏目下:
浏览器只请求了一次接口,请求地址没有发生变化;而且只能转发给当前的WEB应用资源。
总结
- 重定向是客户端行为,转发是服务器行为
- 转发只发生一次请求;且只能转发到当前应用资源;请求地址不会发生变化
- 重定向发生两次请求;且能重定向到任何资源;地址栏会发生变化
- 转发速度快于重定向
参考文章