Reputation: 256
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.
Upvotes: 3
Views: 8168
Reputation: 11891
There is a newer, simpler way, add this before the return "redirect:"...
:
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);
[sic] you have to set the attribute on the Request object.
Upvotes: 3
Reputation: 750
Can be done in WebMvcConfigurer also:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("oldpath","newpath").setStatusCode(HttpStatus.MOVED_PERMANENTLY);
}
Upvotes: 0
Reputation: 1663
Try to add @ResponseStatus annotation for your method, see below an example:
@ResponseStatus(HttpStatus.MOVED_PERMANENTLY/*this is 301*/)
@RequestMapping(value="/oldPath")
public String doProductOld(...) throws Exception {
//...
return "redirect:path";
}
Upvotes: 7
Reputation: 10377
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);
}
Upvotes: 5