Search code examples
javaspringspring-mvchttp-status-code-301tiles

Spring + Tiles. How to return 301 redirect (instead of 302) in Controller


I am using the 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();
 }

All works fine but this redirect returns 302 response code instead of 301 which is needed for SEO. How to easily (without ModelAndView or Http response) update it to return 301 code?

PS. I found solutions when ModelAndView object return from controller but need solution for Tiles when tiles alias (String) is returned.


Solution

  • General idea is:

    @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);
     }