Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


Spring Boot 请求转发和重定向

Spring Boot Java HTTP 评论 1 大约 853 字

区别

转发

  • 由服务端完成;
  • 地址栏不发生变化,显示的转发前的地址(针对浏览器);
  • 只发生一次请求;
  • 请求中携带的参数不会丢失;

重定向

  • 服务端告诉浏览器或客户端重定向的地址,由客户端再次发起请求;
  • 地址栏显示重新向后的地址(针对浏览器);
  • 发生了两次请求;
  • 第一次请求的参数不会带到重定向后的请求中;

请求链路

转发

  1. 浏览器 请求 服务器
  2. 服务器 转发 服务器2
  3. 服务器2 响应 浏览器

重定向

  1. 浏览器 请求 服务器
  2. 服务器 响应 浏览器
  3. 浏览器 请求 服务器2
  4. 服务器2 响应 浏览器

代码

转发

@GetMapping("/test-forward")
public void testForward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // request.getRequestDispatcher("https://www.baidu.com").forward(request, response); // 无法跨域 forward
    request.getRequestDispatcher("/test").forward(request, response); // 只能转发至内部 servlet
}

@GetMapping("/test")
@ResponseBody
public String test() {
    return "来自test的结果";
}

重定向

@GetMapping("/test-redirect")
public void testRedirect(HttpServletResponse response) throws IOException {
    response.sendRedirect("https://www.baidu.com");
}
阅读 10505 · 发布于 2020-03-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
  • sss 1楼
     request.getRequestDispatcher("https://www.baidu.com").forward(request, response);
    只可以访问同一个服务,跨不服不可以
    Chrome | Windows 10 2021-04-06
    作者回复
    多谢指正,已修改。
    Edge | Windows 10 2021-04-07
随便看看 换一批