spring boot 请求转发和重定向
在尝试过滤器的时候牵扯到请求转发的场景,就顺手测试了一下。这里记录基本的使用套路。1. 添加依赖maven:<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --><dependency><groupId>javax.servlet</groupId><
·
在尝试过滤器的时候牵扯到请求转发的场景,就顺手测试了一下。这里记录基本的使用套路。
1. 添加依赖
maven:
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
gradle:
// https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
2. 测试代码
目标:不论是 forward 还是 redirect,最终是到达这个方法中。从请求中拿出 method 并打印出来。
@GetMapping("/forward")
public String filterForward(HttpServletRequest request,HttpServletResponse response){
String method = request.getParameter("method");
System.out.println("method: "+ method);
return "hello "+ method ;
}
请求转发:
(1) 这种请求转发方式是不 work 的。网上有好多这样的 demo,但我测试的时候都是直接返回了 forward:/forward 字符串。
@GetMapping("/hello")
public String helloFilter() {
String hello = "hello filter \n";
return "forward:/forward";
}
(2)转发正确的打开方式。
@GetMapping("/hello/forward")
public void helloForward(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/forward?method=forward");
requestDispatcher.forward(request,response);
}
从代码中可以看出,请求转发是通过请求分配器( RequestDispatcher ) 直接将请求转发到了另一个 url 上。此时请求依旧在后端,还没有返回响应给前端。
重定向:
@GetMapping("hello/redirect")
public void helloRedirect(HttpServletRequest request,HttpServletResponse response)
throws IOException {
response.sendRedirect(request.getContextPath() + "/forward?method=redirect");
}
从代码中可以看出,重定向是当前请求已经被 helloRedirect 执行完了,在 response 中”嵌入“新的 URL 并返回给前端。浏览器收到响应后会向嵌入的 URL 再发起一次请求,并将这次请求的结果渲染給用户。我测试了一把,当前端不是浏览器,而只是个 curl 命令,那么是不会有第二次请求的。
3. 转发和重定向的区别
最大的区别是:转发是有一次请求,重定向是两次请求。其他的区别点都是从这个点衍生来的。
转发:
- 浏览器上的 URL 不会发生变化。
- 原始的请求会发送到第二个 url 对应的方法中去。
请求:
-
浏览器上的 URL 会发生变化。
-
浏览器会创建一个新的请求发送给第二个 url 对应的方法。
4. demo 地址
更多推荐



所有评论(0)