I want to handle an AJAX request that updates an entity. I don\'t really need it to return anything. The problem is that Spring MVC insists on sending a redirect to the same
Spring MVC is built on top of the Servlet API. As such, any component that has access to the HttpServletResponse can theoretically use it to sendRedirect(String) or set the response code manually. (I say theoretically because the response must not have yet been committed when those calls are made.)
Typically, in a Spring MVC application, a @Controller can receive the HttpServletResponse (or ServletResponse) in a @RequestMapping method as an argument.
A HandlerInterceptor receives it three times as part of the DispatcherServlet's request handling lifecycle.
Any registered Servlet Filter instances also have access to the ServletResponse before (and after) Spring's DispatcherServlet since filters act before servlets.
Spring tries to hide all these dependencies to the Servlet API to make programming web server easier. It therefore provides other ways to cause a redirect. These mostly depend on the supported handler method return types. More specifically, we care about String, View, ModelAndView, and ResponseEntity.
The following are all default cases:
When you return a String, Spring will use a ViewResolver to resolve a View based on the String value, which identifies the name of the view. Spring's UrlBasedViewResolver will detect a redirect: prefix in String view names and consider it as an indication to send a redirect response. It will create a RedirectView (part of this is actually done in ViewNameMethodReturnValueHandler, but UrlBasedViewResolver creates the View) which will be in charge of doing the redirect with the HttpServletResponse.
This is an implementation detail, but most of Spring's default ViewResolver classes do this.
With View, you can simply create and return a RedirectView yourself. You can also implement your own View class that will do the same. Spring will use the appropriate HandlerMethodReturnValueHandler to handle it.
With ModelAndView, it's a mix of the two previous options since you can provide either a view name or a View itself.
With ResponseEntity it gets more interesting since you control the whole response. That is, you can set a status code, headers, body, everything. All you need to do is therefore set the status code to 302 and put a Location header with the URL to redirect to.
Finally, you have similar behavior in @ExceptionHandler methods (with similar return types) which you can also mix with @ResponseStatus and modifying the headers manually.
These are all the basic cases, but since Spring MVC is almost completely customizable, there are other components to be aware of. These are HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler, HandlerAdapter, HandlerExceptionResolver and ExceptionHandler, and more. Note that you'll rarely play with these and those that come with Spring pretty much do the whole job.