HTTP重定向:Spring中的301(永久)与302(临时)

时间:2016-05-12 09:20:44

标签: spring spring-mvc redirect

我想在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开发者工具我得到了状态302暂时移动

2 个答案:

答案 0 :(得分:6)

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");

    }

答案 1 :(得分:5)

您可以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);
}