使用@ResponseStatus注解的注意事项

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用@ResponseStatus注解的注意事项相关的知识,希望对你有一定的参考价值。

当@ResponseStatus用在方法上,如

@RequestMapping("/test")
@ResponseStatus(reason="ok",code=HttpStatus.OK)
public String test() {
    return "test";
}

如果只是为了指示返回状态码,最好不要添加reason属性。
如果添加了reason属性,且reason不为"",且code > 0(哪怕状态码是200),会对当前请求走错误处理。

原因

org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod 类中,设置返回状态。如图:
技术分享图片
io.undertow.servlet.handlers.ServletInitialHandler 类中,判断错误码,如图:
技术分享图片

返回状态码的其他方案

返回状态码也可通过modelAndView.setStatus()实现,如

@RequestMapping(value = { "/test" }, method = RequestMethod.GET)
public ModelAndView test() {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
    return modelAndView;
}

以上是关于使用@ResponseStatus注解的注意事项的主要内容,如果未能解决你的问题,请参考以下文章