在没有ModelAndView的Spring MVC 4中重定向301状态

Sir*_*eta 6 java spring spring-mvc

我尝试重定向301 Status Code(你知道我想成为SEO友好等).

我使用InternalResourceViewResolver所以我想使用某种类似于return "redirect:http://google.com"我的控制器中的代码.这虽然会发送一个302 Status Code

我尝试过使用a HttpServletResponse来设置标题

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

它仍然返回302.

在检查文档和Google搜索结果后,我想出了以下内容:

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

它确实工作得很好,正如预期的那样,返回代码 301

我想在不使用ModelAndView的情况下实现它(也许它完全没问题).可能吗?

注意:包含的片段只是详细信息控制器的一部分,重定向仅在某些情况下发生(支持旧版URL).

min*_*ion 8

我建议像你一样使用 spring 的 redirectView 。你必须有一个完整的 URL,包括域等才能工作,否则它会执行 302。或者如果你有权访问 HttpServletResponse,那么你可以执行以下操作。

public void send301Redirect(HttpServletResponse response, String newUrl) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", newUrl);
        response.setHeader("Connection", "close");
    }
Run Code Online (Sandbox Code Playgroud)


Ale*_*x R 8

不知道何时添加它,但是至少在v4.3.7上可以使用。您在REQUEST上设置了一个属性,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";
}
Run Code Online (Sandbox Code Playgroud)