[SpringMVC] The difference between Servlet forwarding and redirection

1 Overview

Forwarding and redirection are two ways to jump pages in Servlet. The following figure shows its working principle. The left figure shows forwarding and the right figure shows redirection.
Forward left, redirect right
As can be seen from the figure above, the biggest difference between the two is that forwarding is performed within the server, with only one request and response; redirection is the behavior of the client, with two request and response.

It is precisely because of the difference in the working methods of the two that we can deduce the following points that need attention:

  • If Servlet1 shares data in the request field , Servlet2 can also obtain the data after forwarding. If redirection is used, an error will be reported because the two Servlets are no longer in the same request domain.
  • The browser's address bar will change after redirection, but the forwarding address bar will not change.
  • Redirection can jump to any URL, while forwarding can only jump to resources on this site.

2. Using forwarding and redirection in SpringMVC

2.1 Forward view

The default forwarding view in SpringMVC is InternalResourceView

The situation of creating forwarding view in SpringMVC:

When the view name set in the controller method is prefixed with "forward:", the InternalResourceView view is created. The view name at this time will not be parsed by the view parser configured in the SpringMVC configuration file, but will be prefixed with "forward. :"Remove it, and the remaining part will be used as the final path to jump through forwarding.

@RequestMapping("/testForward")
public String testForward(){
    
    
    return "forward:/testHello";
}

2.2 Redirect view

The default redirect view in SpringMVC is RedirectView

When the view name set in the controller method is prefixed with "redirect:", the RedirectView view is created. The view name at this time will not be parsed by the view parser configured in the SpringMVC configuration file, but will be prefixed with "redirect :"Remove it, and the remaining part will be used as the final path to jump through redirection.

@RequestMapping("/testRedirect")
public String testRedirect(){
    
    
    return "redirect:/testHello";
}

2.3 Thymeleaf

In SpringMVC we usually use Thymeleaf as the view rendering technology. After configuring Thymeleaf's view parser in the configuration file, the controller method can directly return the name of the view. The view parser will automatically add the prefix and suffix and then forward it, which is very convenient. . Note that Thymeleaf uses forwarding by default to implement jumps.

@RequestMapping("/testHello")
public String testHello() {
    
    
return "hello";

Thymeleaf's view parser will add the prefix "/" and the suffix ".html", and then jump to hello.html.

Guess you like

Origin blog.csdn.net/weixin_43390123/article/details/124124744