spring-framework / org.springframework.web.bind.annotation / ResponseStatus

ResponseStatus

@Target([AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]) class 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.

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 a org.springframework.http.ResponseEntity as a return type and avoid the use of @ResponseStatus altogether.

Note that a controller class may also be annotated with @ResponseStatus and is then inherited by all @RequestMapping methods.

Author
Arjen Poutsma

Author
Sam Brannen

Since
3.0

See Also
org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolverjavax.servlet.http.HttpServletResponse#sendError(int, String)

Constructors

<init>

ResponseStatus(value: HttpStatus, code: HttpStatus, reason: String)

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.

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 a org.springframework.http.ResponseEntity as a return type and avoid the use of @ResponseStatus altogether.

Note that a controller class may also be annotated with @ResponseStatus and is then inherited by all @RequestMapping methods.

Properties

code

val code: HttpStatus

The status code to use for the response.

Default is HttpStatus#INTERNAL_SERVER_ERROR, which should typically be changed to something more appropriate.

reason

val reason: String

The reason to be used for the response.

value

val value: HttpStatus

Alias for #code.