Set HTTP status code for redirect when returning a String in a Spring 3 controller

青春壹個敷衍的年華 提交于 2019-12-10 18:15:17

问题


Is there a way to specify the HTTP status code when returning "redirect:/new/url" in Spring 3?


回答1:


Haven't tried it, but looking at the source of org.springframework.web.servlet.view.RedirectView it has getHttp11StatusCode() method that determines the HTTP status of response.

It seems like you can override the default response code by settings org.springframework.web.servlet.View#RESPONSE_STATUS_ATTRIBUTE property on request. Simply set:

httpServletRequest.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, status)

before returning with "redirect:" view.




回答2:


As noted by Scolytus, you must return a RedirectView with the statusCode set. Using the "redirect:" prefix will always result in a status of HttpStatus.MOVED_TERMPORARILY (302).

If you need the ability to return String from your controller method as well as RedirectView, you must change the method signature to return Object. Example:

@RequestMapping
public Object someMethod() {
    if (doRedirect) {
        RedirectView rv = new RedirectView("/new/url");
        rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY); // set our own status code
        return rv;
    } else {
        return "someView";
    }
}


来源:https://stackoverflow.com/questions/7360531/set-http-status-code-for-redirect-when-returning-a-string-in-a-spring-3-controll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!