Spring + Tiles. How to return 301 redirects (instead of 302) to controller

I am using code like:

@RequestMapping(value="/oldPath")
public String doProductOld(
    @PathVariable(value = "oldProductId") Long oldProductId,
   Model model
) throws Exception {
    Product product = productDao.findByOldId(oldProductId);

    return "redirect:" + product.getUrlNewPath();
 }

      

Everything works fine, but this redirect returns a 302

response code instead of 301

which is needed for SEO. How easy is it (without ModelAndView

or Http response) to update it to get the 301

code back ?

PS. I found solutions when the returned object was ModelAndView

returned from the controller, but the solution Tiles

requires a solution when an alias (String) is returned.

+3


source to share


4 answers


General idea:



@RequestMapping(value="/oldPath")
public ModelAndView doProductOld(
    @PathVariable(value = "oldProductId") Long oldProductId,
   Model model
) throws Exception {
    Product product = productDao.findByOldId(oldProductId);
    RedirectView red = new RedirectView(product.getUrlNewPath(),true);
    red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    return new ModelAndView(red);
 }

      

+3


source


Try adding @ResponseStatus annotation to your method, see below example:



@ResponseStatus(HttpStatus.MOVED_PERMANENTLY/*this is 301*/)
@RequestMapping(value="/oldPath")
public String doProductOld(...) throws Exception {
    //...
    return "redirect:path";
}

      

+5


source


There is a newer, easier way to add this before return "redirect:"...

:

request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);

      

[sic] you must set the attribute on the Request object.

+1


source


Can also be done in WebMvcConfigurer:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("oldpath","newpath").setStatusCode(HttpStatus.MOVED_PERMANENTLY);
}

      

0


source







All Articles