【问题标题】:HTTP redirect: 301 (permanent) vs. 302 (temporary) in SpringHTTP 重定向:Spring 中的 301(永久)与 302(临时)
【发布时间】:2016-09-08 00:43:18
【问题描述】:

我想在 Spring 中进行 301 重定向,所以这里是我使用的一段代码

@RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
    private String initGetForm(@ModelAttribute("searchForm") final SearchForm searchForm,
                            BindingResult result, 
                            HttpServletRequest request,
                            HttpServletResponse response,
                            Model model, Locale locale) throws Exception {


        String newUrl = "/devices/en";

        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", newUrl);
        response.setHeader("Connection", "close");

        return "redirect:" + newUrl;

}

但是检查 IE 开发者工具我得到了这个 Status 302 Moved Temporarily !

【问题讨论】:

  • 因为你正在返回redirect:+newUrl,这基本上会让你在那之前所做的一切都变得毫无用处。不要返回任何东西,返回无效。

标签: spring spring-mvc redirect


【解决方案1】:

Spring 在处理重定向时会重置您的响应标头,因为您将返回一个带有特殊重定向前缀的逻辑视图名称。如果您想手动设置标头,则在不使用 Spring 视图解析的情况下自行处理响应。更改代码如下

@RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private void initGetForm(@ModelAttribute("searchForm") final SearchForm searchForm,
                                BindingResult result, 
                                HttpServletRequest request,
                                HttpServletResponse response,
                                Model model, Locale locale) throws Exception {

            String newUrl = request.getContextPath() + "/devices/en";
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", newUrl);
            response.setHeader("Connection", "close");

    }

【讨论】:

    【解决方案2】:

    您可以将RedirectView 与TEMPORARY_REDIRECT 状态一起使用。

    @RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
    private ModelAndView initGetForm(@ModelAttribute("searchForm") final SearchForm searchForm,
                                BindingResult result, 
                                HttpServletRequest request,
                                HttpServletResponse response,
                                Model model, Locale locale) throws Exception {
        ....
        RedirectView redirectView = new RedirectView(url);
        redirectView.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
        return new ModelAndView(redirectView);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-26
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 2013-07-17
      • 1970-01-01
      • 2012-05-31
      相关资源
      最近更新 更多