301 status redirection in Spring MVC 4 without ModelAndView

I am trying to redirect from 301 Status Code(you know that I want to be SEO friendly, etc.).

I use InternalResourceViewResolver, so I wanted to use some kind of code similar to return "redirect:http://google.com"in my controller. This, although it would send302 Status Code

I tried to use HttpServletResponseto set the title

@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 returns anyway 302.

After checking the documentation and Google results, I got 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 works fine and, as expected, returns code 301

I would like to achieve this without using ModelAndView (maybe this is fine, though). Is it possible?

. - , ( URL-).

+4
3

redirectView spring, . URL-, .., , 302. , HttpServletResponse, , .

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

, , v4.3.7 . , spring View :

@RequestMapping(value="/url/{seo}", method = RequestMethod.GET)
public String detail(@PathVariable String seo, HttpServletRequest request){
    request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);
    return "redirect:http://google.com";
}
+1

If you already returned ModelAndView and do not want to use HttpServletResponse, you can use this snippet:

        RedirectView rv = new RedirectView("redirect:" + myNewURI);
        rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        return new ModelAndView(rv);
+1
source

All Articles