@ResponseStatus
Marks a method or exception class with the status code() and reason() that should be returned.
The status code is applied to the HTTP response when the handler method is invoked and overrides status information set by other means, like ResponseEntity or "redirect:".
Warning: when using this annotation on an exception class, or when setting the reason attribute of this annotation, the
HttpServletResponse.sendError
method will be used.Warning: With
HttpServletResponse.sendError
, the response is considered complete and should not be written to any further. Furthermore, the Servlet container will typically write an HTML error page therefore making the use of a reason unsuitable for REST APIs. For such cases it is preferable to use aResponseEntity
as a return type and avoid the use of@ResponseStatus
altogether.
ResponseEntity
和@ResponseStatus
会有冲突,换句话说,当@ResponseStatus
注解了一个exception或者设置reason
属性,等于已经设置好了restful风格的response内容,如:
@RequestMapping("/io")
public String io() throws IOException{
throw new IOException("caused by some reasons!!");
}
@ResponseStatus(code = HttpStatus.NOT_FOUND)
@ExceptionHandler(IOException.class)
public ResponseEntity<String> handleIOException() {
return new ResponseEntity<String>("handleIOException", HttpStatus.BAD_REQUEST);
}
如果使用api访问(不使用浏览器访问)的话,返回的是“handleIOException”,HTTP code是HttpStatus.BAD_REQUEST
而换成
@RequestMapping("/io")
public String io() throws IOException{
throw new IOException("caused by some reasons!!");
}
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "test")
@ExceptionHandler(IOException.class)
public ResponseEntity<String> handleIOException() {
return new ResponseEntity<String>("handleIOException", HttpStatus.BAD_REQUEST);
}
如果使用api访问(不使用浏览器访问)的话,返回的则是@ResponseStatus
交给HttpServletResponse.sendError
的响应内容,HTTP code为HttpStatus.NOT_FOUND
Note that a controller class may also be annotated with @ResponseStatus
and is then inherited by all @RequestMapping
methods.(控制类也可以被@ResponseStatus
注解,注解的内容被所有@RequestMapping
方法继承)