Redirect with 301 status in Spring MVC 4 without ModelAndView

java, spring, spring-mvc

Solution

I would suggest using redirectView of spring like you have it. You have to have a complete URL including the domain etc for that to work, else it will do a 302. Or if you have access to HttpServletResponse, then you can do the below as below.

public void send301Redirect(HttpServletResponse response, String newUrl) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", newUrl);
        response.setHeader("Connection", "close");
    }

Problem

I try to have a redirect with `301 Status Code` (you know I want to be SEO friendly etc). I do use `InternalResourceViewResolver` so I wanted to use some kind of a code similar to `return "redirect:http://google.com"` in my Controller. This though would send a `302 Status Code` What I have tried is using a `HttpServletResponse` to set header ``` @RequestMapping(value="/url/{seo}", method = RequestMethod.GET) public String detail(@PathVariable String seo, HttpServletResponse response){ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return "redirect:http://google.com"; } ``` It does still return `302`. After checking documentation and Google results I've come up with the following: ``` @RequestMapping(value="/url/{seo}", method = RequestMethod.GET) public ModelAndView detail(@PathVariable String seo){ RedirectView rv = new RedirectView(); rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY); rv.setUrl("http://google.com"); ModelAndView mv = new ModelAndView(rv); return mv; } ``` It does work perfectly fine and as expected, returning code `301` I would like to achieve it without using ModelAndView (Maybe it's perfectly fine though). Is it possible? NOTE: included snippets are just parts of the detail controller and redirect does happen only in some cases (supporting legacy urls).

Original source