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

Package org.springframework.web.bind.annotation

Types

ValueConstants

interface ValueConstants

Common value constants shared between bind annotations.

Annotations

ControllerAdvice

class ControllerAdvice

Specialization of Component for classes that declare ExceptionHandler, InitBinder, or ModelAttribute methods to be shared across multiple @Controller classes.

Classes with @ControllerAdvice can be declared explicitly as Spring beans or auto-detected via classpath scanning. All such beans are sorted via org.springframework.core.annotation.AnnotationAwareOrderComparator, i.e. based on org.springframework.core.annotation.Order and org.springframework.core.Ordered, and applied in that order at runtime. For handling exceptions, an @ExceptionHandler will be picked on the first advice with a matching exception handler method. For model attributes and InitBinder initialization, @ModelAttribute and @InitBinder methods will also follow @ControllerAdvice order.

Note: For @ExceptionHandler methods, a root exception match will be preferred to just matching a cause of the current exception, among the handler methods of a particular advice bean. However, a cause match on a higher-priority advice will still be preferred to a any match (whether root or cause level) on a lower-priority advice bean. As a consequence, please declare your primary root exception mappings on a prioritized advice bean with a corresponding order!

By default the methods in an @ControllerAdvice apply globally to all Controllers. Use selectors #annotations(), #basePackageClasses(), and #basePackages() (or its alias #value()) to define a more narrow subset of targeted Controllers. If multiple selectors are declared, OR logic is applied, meaning selected Controllers should match at least one selector. Note that selector checks are performed at runtime and so adding many selectors may negatively impact performance and add complexity.

CrossOrigin

class CrossOrigin

Marks the annotated method or type as permitting cross origin requests.

By default all origins and headers are permitted, credentials are not allowed, and the maximum age is set to 1800 seconds (30 minutes). The list of HTTP methods is set to the methods on the @RequestMapping if not explicitly set on @CrossOrigin.

NOTE: @CrossOrigin is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

DeleteMapping

class DeleteMapping

Annotation for mapping HTTP DELETE requests onto specific handler methods.

Specifically, @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).

ExceptionHandler

class ExceptionHandler

Annotation for handling exceptions in specific handler classes and/or handler methods.

Handler methods which are annotated with this annotation are allowed to have very flexible signatures. They may have parameters of the following types, in arbitrary order:

  • An exception argument: declared as a general Exception or as a more specific exception. This also serves as a mapping hint if the annotation itself does not narrow the exception types through its #value().
  • Request and/or response objects (typically from the Servlet API). You may choose any specific request/response type, e.g. javax.servlet.ServletRequest / javax.servlet.http.HttpServletRequest.
  • Session object: typically javax.servlet.http.HttpSession. An argument of this type will enforce the presence of a corresponding session. As a consequence, such an argument will never be null. Note that session access may not be thread-safe, in particular in a Servlet environment: Consider switching the "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently.
  • org.springframework.web.context.request.WebRequest or org.springframework.web.context.request.NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet API.
  • java.util.Locale for the current request locale (determined by the most specific locale resolver available, i.e. the configured org.springframework.web.servlet.LocaleResolver in a Servlet environment).
  • java.io.InputStream / java.io.Reader for access to the request's content. This will be the raw InputStream/Reader as exposed by the Servlet API.
  • java.io.OutputStream / java.io.Writer for generating the response's content. This will be the raw OutputStream/Writer as exposed by the Servlet API.
  • org.springframework.ui.Model as an alternative to returning a model map from the handler method. Note that the provided model is not pre-populated with regular model attributes and therefore always empty, as a convenience for preparing the model for an exception-specific view.

The following return types are supported for handler methods:

  • A ModelAndView object (from Servlet MVC).
  • A org.springframework.ui.Model object, with the view name implicitly determined through a org.springframework.web.servlet.RequestToViewNameTranslator.
  • A java.util.Map object for exposing a model, with the view name implicitly determined through a org.springframework.web.servlet.RequestToViewNameTranslator.
  • A org.springframework.web.servlet.View object.
  • A String value which is interpreted as view name.
  • ResponseBody annotated methods (Servlet-only) to set the response content. The return value will be converted to the response stream using org.springframework.http.converter.HttpMessageConverter.
  • An org.springframework.http.HttpEntity or org.springframework.http.ResponseEntity object (Servlet-only) to set response headers and content. The ResponseEntity body will be converted and written to the response stream using org.springframework.http.converter.HttpMessageConverter.
  • void if the method handles the response itself (by writing the response content directly, declaring an argument of type javax.servlet.ServletResponse / javax.servlet.http.HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a org.springframework.web.servlet.RequestToViewNameTranslator (not declaring a response argument in the handler method signature).

In Servlet environments, you can combine the ExceptionHandler annotation with ResponseStatus, to define the response status for the HTTP response.

GetMapping

class GetMapping

Annotation for mapping HTTP GET requests onto specific handler methods.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

InitBinder

class InitBinder

Annotation that identifies methods which initialize the org.springframework.web.bind.WebDataBinder which will be used for populating command and form object arguments of annotated handler methods.

Such init-binder methods support all arguments that RequestMapping supports, except for command/form objects and corresponding validation result objects. Init-binder methods must not have a return value; they are usually declared as void.

Typical arguments are org.springframework.web.bind.WebDataBinder in combination with org.springframework.web.context.request.WebRequest or java.util.Locale, allowing to register context-specific editors.

Mapping

class Mapping

Meta annotation that indicates a web mapping annotation.

MatrixVariable

class MatrixVariable

Annotation which indicates that a method parameter should be bound to a name-value pair within a path segment. Supported for RequestMapping annotated handler methods in Servlet environments.

If the method parameter type is java.util.Map and a matrix variable name is specified, then the matrix variable value is converted to a java.util.Map assuming an appropriate conversion strategy is available.

If the method parameter is java.util.Map or org.springframework.util.MultiValueMap and a variable name is not specified, then the map is populated with all matrix variable names and values.

ModelAttribute

class ModelAttribute

Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view. Supported for controller classes with RequestMapping methods.

Can be used to expose command objects to a web view, using specific attribute names, through annotating corresponding parameters of an RequestMapping method.

Can also be used to expose reference data to a web view through annotating accessor methods in a controller class with RequestMapping methods. Such accessor methods are allowed to have any arguments that RequestMapping methods support, returning the model attribute value to expose.

Note however that reference data and all other model content is not available to web views when request processing results in an Exception since the exception could be raised at any time making the content of the model unreliable. For this reason ExceptionHandler methods do not provide access to a Model argument.

PatchMapping

class PatchMapping

Annotation for mapping HTTP PATCH requests onto specific handler methods.

Specifically, @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).

PathVariable

class PathVariable

Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods in Servlet environments.

If the method parameter is java.util.Map or org.springframework.util.MultiValueMap then the map is populated with all path variable names and values.

PostMapping

class PostMapping

Annotation for mapping HTTP POST requests onto specific handler methods.

Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).

PutMapping

class PutMapping

Annotation for mapping HTTP PUT requests onto specific handler methods.

Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).

RequestAttribute

class RequestAttribute

Annotation to bind a method parameter to a request attribute.

The main motivation is to provide convenient access to request attributes from a controller method with an optional/required check and a cast to the target method parameter type.

RequestBody

class RequestBody

Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

Supported for annotated handler methods in Servlet environments.

RequestParam

class RequestParam

Annotation which indicates that a method parameter should be bound to a web request parameter.

Supported for annotated handler methods in Servlet and Portlet environments.

If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.

If the method parameter is java.util.Map or org.springframework.util.MultiValueMap and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

RequestPart

class RequestPart

Annotation that can be used to associate the part of a "multipart/form-data" request with a method argument.

Supported method argument types include MultipartFile in conjunction with Spring's MultipartResolver abstraction, javax.servlet.http.Part in conjunction with Servlet 3.0 multipart requests, or otherwise for any other method argument, the content of the part is passed through an HttpMessageConverter taking into consideration the 'Content-Type' header of the request part. This is analogous to what @RequestBody does to resolve an argument based on the content of a non-multipart regular request.

Note that @RequestParam annotation can also be used to associate the part of a "multipart/form-data" request with a method argument supporting the same method argument types. The main difference is that when the method argument is not a String, @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the 'Content-Type' header of the request part. @RequestParam is likely to be used with name-value form fields while @RequestPart is likely to be used with parts containing more complex content (e.g. JSON, XML).

ResponseBody

class ResponseBody

Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods in Servlet environments.

As of version 4.0 this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.

ResponseStatus

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.

RestController

class RestController

A convenience annotation that is itself annotated with Controller and ResponseBody.

Types that carry this annotation are treated as controllers where RequestMapping methods assume ResponseBody semantics by default.

NOTE: @RestController is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

RestControllerAdvice

class RestControllerAdvice

A convenience annotation that is itself annotated with ControllerAdvice and ResponseBody.

Types that carry this annotation are treated as controller advice where ExceptionHandler methods assume ResponseBody semantics by default.

NOTE: @RestControllerAdvice is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

SessionAttribute

class SessionAttribute

Annotation to bind a method parameter to a session attribute.

The main motivation is to provide convenient access to existing, permanent session attributes (e.g. user authentication object) with an optional/required check and a cast to the target method parameter type.

For use cases that require adding or removing session attributes consider injecting org.springframework.web.context.request.WebRequest or javax.servlet.http.HttpSession into the controller method.

For temporary storage of model attributes in the session as part of the workflow for a controller, consider using SessionAttributes instead.

SessionAttributes

class SessionAttributes

Annotation that indicates the session attributes that a specific handler uses.

This will typically list the names of model attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans. Declared at the type level, applying to the model attributes that the annotated handler class operates on.

NOTE: Session attributes as indicated using this annotation correspond to a specific handler's model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session. Therefore, use this facility for such conversational attributes which are supposed to be stored in the session temporarily during the course of a specific handler's conversation.

For permanent session attributes, e.g. a user authentication object, use the traditional session.setAttribute method instead. Alternatively, consider using the attribute management capabilities of the generic org.springframework.web.context.request.WebRequest interface.

NOTE: When using controller interfaces (e.g. for AOP proxying), make sure to consistently put all your mapping annotations — such as @RequestMapping and @SessionAttributes — on the controller interface rather than on the implementation class.