Spring Boot 请求转发和重定向

Spring Boot Java HTTP About 853 words

区别

转发

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

重定向

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

请求链路

转发

  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");
}
Views: 11,022 · Posted: 2020-03-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh