春天+瓷砖.如何在Controller中返回301重定向(而不是302)

Esc*_*der 3 java spring tiles spring-mvc http-status-code-301

我使用的代码如下:

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

    return "redirect:" + product.getUrlNewPath();
 }
Run Code Online (Sandbox Code Playgroud)

一切正常,但这个重定向返回302响应代码,而不是301SEO所需.如何轻松(没有ModelAndView或Http响应)更新它以返回301代码?

PS.当ModelAndView对象从控制器返回时我找到了解决方案,但是当返回Tilestile alias(String)时需要解决方案.

msa*_*gel 5

总体思路是:

@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);
 }
Run Code Online (Sandbox Code Playgroud)


Pia*_*nov 5

尝试为您的方法添加@ResponseStatus注释,请参阅下面的示例:

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