问题
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