Spring MVC is built on top of the servlet API. Thus, any component that has access to the HttpServletResponse can theoretically use it to sendRedirect(String) or manually set the response code. (I speak theoretically because the answer has not yet been fulfilled when these calls are made.)
Typically, in a Spring MVC application, a @Controller can accept HttpServletResponse (or ServletResponse ) in the @RequestMapping method as an argument .
A HandlerInterceptor gets it three times as part of the DispatcherServlet request processing life cycle.
Any registered instance of Servlet Filter also has access to ServletResponse before (and after) Spring DispatcherServlet , since filters act in front of servlets.
Spring is trying to hide all of these dependencies with the Servlet API to simplify web server programming. Therefore, it provides other ways to redirect. They mainly depend on the types of return methods of the handler. More specifically, we care about String , View , ModelAndView and ResponseEntity .
All default cases are listed below:
When you return String , Spring will use the ViewResolver to solve the View based on the String value that identifies the view name. Spring UrlBasedViewResolver detect a redirect: prefix in String name names and treat them as an indication to send a redirect response. It will create a RedirectView (part of this is actually done in the ViewNameMethodReturnValueHandler , but UrlBasedViewResolver creates the View ), which will be responsible for doing the redirection using the HttpServletResponse .
This is an implementation detail, but most Spring default ViewResolver do this.
With View you can simply create and return a RedirectView yourself. You can also implement your own View class, which will do the same. Spring will use the appropriate HandlerMethodReturnValueHandler to process it.
With ModelAndView this is a combination of the two previous parameters, because you can specify either the name of the view or View .
With ResponseEntity it becomes more interesting as you control the entire response. That is, you can set the status code, headers, body, everything. All you have to do is set the status code to 302 and put the Location header with the URL redirection.
Finally, you have similar behavior in @ExceptionHandler methods (with similar return types), which you can also mix with @ResponseStatus and manually change the headers.
These are all basic cases, but since Spring MVC is almost completely configurable, there are other components to be aware of. These are HandlerMethodArgumentResolver , HandlerMethodReturnValueHandler , HandlerAdapter , HandlerExceptionResolver and ExceptionHandler , etc. Note that you rarely play with these and those that come with Spring do pretty much all the work.