1. 程式人生 > >使用@ResponseStatus註解的注意事項

使用@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;
}