使用@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 类中,设置返回状态。如图:
使用@ResponseStatus注解的注意事项
io.undertow.servlet.handlers.ServletInitialHandler 类中,判断错误码,如图:
使用@ResponseStatus注解的注意事项

返回状态码的其他方案

返回状态码也可通过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;
}

猜你喜欢

转载自blog.51cto.com/7266799/2314818
今日推荐