Detail spring mvc request forwarding and redirection

  • 2020-06-12 09:04:44
  • OfStack

Both HttpServletResponse.sendRedirect and RequestDispatcher.forward allow the browser to get the resource that another URL points to in comparison to request redirection, but the internal mechanisms are quite different.

The RequestDispatcher. forward method can only forward requests to components in the same Web application, and HttpServletResponse. sendRedirect can redirect to resources of other applications in the same site, not only to other resources in the current application, but even to resources at other sites using absolute URL. For sendRedirect, if the URL passed begins with a "/", it is the root directory relative to the entire Web site; For forward if the URL passed starts with "/", it is the root directory relative to the current Web application.

2.sendRedirect's response to the browser is to re-issue the access request to another URL, and forward forwards the request to another resource within the server side. The browser only knows that the request was issued and the response result was obtained

3. The callers and callers of forward share the same request object and response object, which belong to the same access request and response process; The caller and the caller of sendRedirect use their respective request and response objects, which belong to two separate access request and response procedures

Request redirection starts with redirect:, request forwarding starts with forward:;

Examples are as follows:


@RequestMapping(value="/users")
@Controller
public class UserController {

  @RequestMapping(value="/queryuser",method = RequestMethod.GET)
  public String queryuser(Model model) throws Exception {
    return "forward:/users/uc";
  }

  @RequestMapping(value="/uc",method = RequestMethod.GET)
  public String quer(Model model) throws Exception {

    return "redirect:/#/home";
  }

   @RequestMapping(value = "/save", method = RequestMethod.GET) 
    public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response) throws Exception { 
      ModelAndView mv = new ModelAndView("forward:/users/uc");// The default is forward model  
//    ModelAndView mv = new ModelAndView("redirect:/#/home");//redirect model  
      return mv; 
    } 
} 


Related articles: