001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.bind.annotation;
018
019import java.lang.annotation.Documented;
020import java.lang.annotation.ElementType;
021import java.lang.annotation.Retention;
022import java.lang.annotation.RetentionPolicy;
023import java.lang.annotation.Target;
024import java.util.concurrent.Callable;
025
026import org.springframework.core.annotation.AliasFor;
027
028/**
029 * Annotation for mapping web requests onto specific handler classes and/or
030 * handler methods. Provides a consistent style between Servlet and Portlet
031 * environments, with the semantics adapting to the concrete environment.
032 *
033 * <p><b>NOTE:</b> The set of features supported for Servlets is a superset
034 * of the set of features supported for Portlets. The places where this applies
035 * are marked with the label "Servlet-only" in this source file. For Servlet
036 * environments there are some further distinctions depending on whether an
037 * application is configured with {@literal "@MVC 3.0"} or
038 * {@literal "@MVC 3.1"} support classes. The places where this applies are
039 * marked with {@literal "@MVC 3.1-only"} in this source file. For more
040 * details see the note on the new support classes added in Spring MVC 3.1
041 * further below.
042 *
043 * <p>Handler methods which are annotated with this annotation are allowed to
044 * have very flexible signatures. They may have parameters of the following
045 * types, in arbitrary order (except for validation results, which need to
046 * follow right after the corresponding command object, if desired):
047 * <ul>
048 * <li>Request and/or response objects (Servlet API or Portlet API).
049 * You may choose any specific request/response type, e.g.
050 * {@link javax.servlet.ServletRequest} / {@link javax.servlet.http.HttpServletRequest}
051 * or {@link javax.portlet.PortletRequest} / {@link javax.portlet.ActionRequest} /
052 * {@link javax.portlet.RenderRequest}. Note that in the Portlet case,
053 * an explicitly declared action/render argument is also used for mapping
054 * specific request types onto a handler method (in case of no other
055 * information given that differentiates between action and render requests).
056 * <li>Session object (Servlet API or Portlet API): either
057 * {@link javax.servlet.http.HttpSession} or {@link javax.portlet.PortletSession}.
058 * An argument of this type will enforce the presence of a corresponding session.
059 * As a consequence, such an argument will never be {@code null}.
060 * <i>Note that session access may not be thread-safe, in particular in a
061 * Servlet environment: Consider switching the
062 * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#setSynchronizeOnSession
063 * "synchronizeOnSession"} flag to "true" if multiple requests are allowed to
064 * access a session concurrently.</i>
065 * <li>{@link org.springframework.web.context.request.WebRequest} or
066 * {@link org.springframework.web.context.request.NativeWebRequest}.
067 * Allows for generic request parameter access as well as request/session
068 * attribute access, without ties to the native Servlet/Portlet API.
069 * <li>{@link java.util.Locale} for the current request locale
070 * (determined by the most specific locale resolver available,
071 * i.e. the configured {@link org.springframework.web.servlet.LocaleResolver}
072 * in a Servlet environment and the portal locale in a Portlet environment).
073 * <li>{@link java.io.InputStream} / {@link java.io.Reader} for access
074 * to the request's content. This will be the raw InputStream/Reader as
075 * exposed by the Servlet/Portlet API.
076 * <li>{@link java.io.OutputStream} / {@link java.io.Writer} for generating
077 * the response's content. This will be the raw OutputStream/Writer as
078 * exposed by the Servlet/Portlet API.
079 * <li>{@link org.springframework.http.HttpMethod} for the HTTP request method</li>
080 * <li>{@link PathVariable @PathVariable} annotated parameters (Servlet-only)
081 * for access to URI template values (i.e. /hotels/{hotel}). Variable values will be
082 * converted to the declared method argument type. By default, the URI template
083 * will match against the regular expression {@code [^\.]*} (i.e. any character
084 * other than period), but this can be changed by specifying another regular
085 * expression, like so: /hotels/{hotel:\d+}.
086 * Additionally, {@code @PathVariable} can be used on a
087 * {@link java.util.Map Map&lt;String, String&gt;} to gain access to all
088 * URI template variables.
089 * <li>{@link MatrixVariable @MatrixVariable} annotated parameters (Servlet-only)
090 * for access to name-value pairs located in URI path segments. Matrix variables
091 * must be represented with a URI template variable. For example /hotels/{hotel}
092 * where the incoming URL may be "/hotels/42;q=1".
093 * Additionally, {@code @MatrixVariable} can be used on a
094 * {@link java.util.Map Map&lt;String, String&gt;} to gain access to all
095 * matrix variables in the URL or to those in a specific path variable.
096 * <li>{@link RequestParam @RequestParam} annotated parameters for access to
097 * specific Servlet/Portlet request parameters. Parameter values will be
098 * converted to the declared method argument type. Additionally,
099 * {@code @RequestParam} can be used on a {@link java.util.Map Map&lt;String, String&gt;} or
100 * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, String&gt;}
101 * method parameter to gain access to all request parameters.
102 * <li>{@link RequestHeader @RequestHeader} annotated parameters for access to
103 * specific Servlet/Portlet request HTTP headers. Parameter values will be
104 * converted to the declared method argument type. Additionally,
105 * {@code @RequestHeader} can be used on a {@link java.util.Map Map&lt;String, String&gt;},
106 * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, String&gt;}, or
107 * {@link org.springframework.http.HttpHeaders HttpHeaders} method parameter to
108 * gain access to all request headers.
109 * <li>{@link RequestBody @RequestBody} annotated parameters (Servlet-only)
110 * for access to the Servlet request HTTP contents. The request stream will be
111 * converted to the declared method argument type using
112 * {@linkplain org.springframework.http.converter.HttpMessageConverter message
113 * converters}. Such parameters may optionally be annotated with {@code @Valid}
114 * and also support access to validation results through an
115 * {@link org.springframework.validation.Errors} argument.
116 * Instead a {@link org.springframework.web.bind.MethodArgumentNotValidException}
117 * exception is raised.
118 * <li>{@link RequestPart @RequestPart} annotated parameters
119 * (Servlet-only, {@literal @MVC 3.1-only})
120 * for access to the content
121 * of a part of "multipart/form-data" request. The request part stream will be
122 * converted to the declared method argument type using
123 * {@linkplain org.springframework.http.converter.HttpMessageConverter message
124 * converters}. Such parameters may optionally be annotated with {@code @Valid}
125 * and support access to validation results through a
126 * {@link org.springframework.validation.Errors} argument.
127 * Instead a {@link org.springframework.web.bind.MethodArgumentNotValidException}
128 * exception is raised.
129 * <li>{@link SessionAttribute @SessionAttribute} annotated parameters for access
130 * to existing, permanent session attributes (e.g. user authentication object)
131 * as opposed to model attributes temporarily stored in the session as part of
132 * a controller workflow via {@link SessionAttributes}.
133 * <li>{@link RequestAttribute @RequestAttribute} annotated parameters for access
134 * to request attributes.
135 * <li>{@link org.springframework.http.HttpEntity HttpEntity&lt;?&gt;} parameters
136 * (Servlet-only) for access to the Servlet request HTTP headers and contents.
137 * The request stream will be converted to the entity body using
138 * {@linkplain org.springframework.http.converter.HttpMessageConverter message
139 * converters}.
140 * <li>{@link java.util.Map} / {@link org.springframework.ui.Model} /
141 * {@link org.springframework.ui.ModelMap} for enriching the implicit model
142 * that will be exposed to the web view.
143 * <li>{@link org.springframework.web.servlet.mvc.support.RedirectAttributes}
144 * (Servlet-only, {@literal @MVC 3.1-only}) to specify the exact set of attributes
145 * to use in case of a redirect and also to add flash attributes (attributes
146 * stored temporarily on the server-side to make them available to the request
147 * after the redirect). {@code RedirectAttributes} is used instead of the
148 * implicit model if the method returns a "redirect:" prefixed view name or
149 * {@code RedirectView}.
150 * <li>Command/form objects to bind parameters to: as bean properties or fields,
151 * with customizable type conversion, depending on {@link InitBinder} methods
152 * and/or the HandlerAdapter configuration - see the "webBindingInitializer"
153 * property on RequestMappingHandlerMethodAdapter.
154 * Such command objects along with their validation results will be exposed
155 * as model attributes, by default using the non-qualified command class name
156 * in property notation (e.g. "orderAddress" for type "mypackage.OrderAddress").
157 * Specify a parameter-level {@link ModelAttribute @ModelAttribute} annotation for
158 * declaring a specific model attribute name.
159 * <li>{@link org.springframework.validation.Errors} /
160 * {@link org.springframework.validation.BindingResult} validation results
161 * for a preceding command/form object (the immediate preceding argument).
162 * <li>{@link org.springframework.web.bind.support.SessionStatus} status handle
163 * for marking form processing as complete (triggering the cleanup of session
164 * attributes that have been indicated by the {@link SessionAttributes @SessionAttributes}
165 * annotation at the handler type level).
166 * <li>{@link org.springframework.web.util.UriComponentsBuilder}
167 * (Servlet-only, {@literal @MVC 3.1-only})
168 * for preparing a URL relative to the current request's host, port, scheme,
169 * context path, and the literal part of the servlet mapping.
170 * </ul>
171 *
172 * <p><strong>Note:</strong> Java 8's {@code java.util.Optional} is supported
173 * as a method parameter type with annotations that provide a {@code required}
174 * attribute (e.g. {@code @RequestParam}, {@code @RequestHeader}, etc.). The use
175 * of {@code java.util.Optional} in those cases is equivalent to having
176 * {@code required=false}.
177 *
178 * <p>The following return types are supported for handler methods:
179 * <ul>
180 * <li>A {@code ModelAndView} object (Servlet MVC or Portlet MVC),
181 * with the model implicitly enriched with command objects and the results
182 * of {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods.
183 * <li>A {@link org.springframework.ui.Model Model} object, with the view name implicitly
184 * determined through a {@link org.springframework.web.servlet.RequestToViewNameTranslator}
185 * and the model implicitly enriched with command objects and the results
186 * of {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods.
187 * <li>A {@link java.util.Map} object for exposing a model,
188 * with the view name implicitly determined through a
189 * {@link org.springframework.web.servlet.RequestToViewNameTranslator}
190 * and the model implicitly enriched with command objects and the results
191 * of {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods.
192 * <li>A {@link org.springframework.web.servlet.View} object, with the
193 * model implicitly determined through command objects and
194 * {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods.
195 * The handler method may also programmatically enrich the model by
196 * declaring a {@link org.springframework.ui.Model} argument (see above).
197 * <li>A {@link String} value which is interpreted as view name,
198 * with the model implicitly determined through command objects and
199 * {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods.
200 * The handler method may also programmatically enrich the model by
201 * declaring a {@link org.springframework.ui.ModelMap} argument
202 * (see above).
203 * <li>{@link ResponseBody @ResponseBody} annotated methods (Servlet-only)
204 * for access to the Servlet response HTTP contents. The return value will
205 * be converted to the response stream using
206 * {@linkplain org.springframework.http.converter.HttpMessageConverter message
207 * converters}.
208 * <li>An {@link org.springframework.http.HttpEntity HttpEntity&lt;?&gt;} or
209 * {@link org.springframework.http.ResponseEntity ResponseEntity&lt;?&gt;} object
210 * (Servlet-only) to access to the Servlet response HTTP headers and contents.
211 * The entity body will be converted to the response stream using
212 * {@linkplain org.springframework.http.converter.HttpMessageConverter message
213 * converters}.
214 * <li>An {@link org.springframework.http.HttpHeaders HttpHeaders} object to
215 * return a response with no body.</li>
216 * <li>A {@link Callable} which is used by Spring MVC to obtain the return
217 * value asynchronously in a separate thread transparently managed by Spring MVC
218 * on behalf of the application.
219 * <li>A {@link org.springframework.web.context.request.async.DeferredResult}
220 * which the application uses to produce a return value in a separate
221 * thread of its own choosing, as an alternative to returning a Callable.
222 * <li>A {@link org.springframework.util.concurrent.ListenableFuture}
223 * which the application uses to produce a return value in a separate
224 * thread of its own choosing, as an alternative to returning a Callable.
225 * <li>A {@link java.util.concurrent.CompletionStage} (implemented by
226 * {@link java.util.concurrent.CompletableFuture} for example)
227 * which the application uses to produce a return value in a separate
228 * thread of its own choosing, as an alternative to returning a Callable.
229 * <li>A {@link org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter}
230 * can be used to write multiple objects to the response asynchronously;
231 * also supported as the body within {@code ResponseEntity}.</li>
232 * <li>An {@link org.springframework.web.servlet.mvc.method.annotation.SseEmitter}
233 * can be used to write Server-Sent Events to the response asynchronously;
234 * also supported as the body within {@code ResponseEntity}.</li>
235 * <li>A {@link org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody}
236 * can be used to write to the response asynchronously;
237 * also supported as the body within {@code ResponseEntity}.</li>
238 * <li>{@code void} if the method handles the response itself (by
239 * writing the response content directly, declaring an argument of type
240 * {@link javax.servlet.ServletResponse} / {@link javax.servlet.http.HttpServletResponse}
241 * / {@link javax.portlet.RenderResponse} for that purpose)
242 * or if the view name is supposed to be implicitly determined through a
243 * {@link org.springframework.web.servlet.RequestToViewNameTranslator}
244 * (not declaring a response argument in the handler method signature;
245 * only applicable in a Servlet environment).
246 * <li>Any other return type will be considered as single model attribute
247 * to be exposed to the view, using the attribute name specified through
248 * {@link ModelAttribute @ModelAttribute} at the method level (or the default attribute
249 * name based on the return type's class name otherwise). The model will be
250 * implicitly enriched with command objects and the results of
251 * {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods.
252 * </ul>
253 *
254 * <p><b>NOTE:</b> {@code @RequestMapping} will only be processed if an
255 * an appropriate {@code HandlerMapping}-{@code HandlerAdapter} pair
256 * is configured. This is the case by default in both the
257 * {@code DispatcherServlet} and the {@code DispatcherPortlet}.
258 * However, if you are defining custom {@code HandlerMappings} or
259 * {@code HandlerAdapters}, then you need to add
260 * {@code DefaultAnnotationHandlerMapping} and
261 * {@code AnnotationMethodHandlerAdapter} to your configuration.</code>.
262 *
263 * <p><b>NOTE:</b> Spring 3.1 introduced a new set of support classes for
264 * {@code @RequestMapping} methods in Servlet environments called
265 * {@code RequestMappingHandlerMapping} and
266 * {@code RequestMappingHandlerAdapter}. They are recommended for use and
267 * even required to take advantage of new features in Spring MVC 3.1 (search
268 * {@literal "@MVC 3.1-only"} in this source file) and going forward.
269 * The new support classes are enabled by default from the MVC namespace and
270 * with use of the MVC Java config ({@code @EnableWebMvc}) but must be
271 * configured explicitly if using neither.
272 *
273 * <p><b>NOTE:</b> When using controller interfaces (e.g. for AOP proxying),
274 * make sure to consistently put <i>all</i> your mapping annotations - such as
275 * {@code @RequestMapping} and {@code @SessionAttributes} - on
276 * the controller <i>interface</i> rather than on the implementation class.
277 *
278 * @author Juergen Hoeller
279 * @author Arjen Poutsma
280 * @author Sam Brannen
281 * @since 2.5
282 * @see GetMapping
283 * @see PostMapping
284 * @see PutMapping
285 * @see DeleteMapping
286 * @see PatchMapping
287 * @see RequestParam
288 * @see RequestAttribute
289 * @see PathVariable
290 * @see ModelAttribute
291 * @see SessionAttribute
292 * @see SessionAttributes
293 * @see InitBinder
294 * @see org.springframework.web.context.request.WebRequest
295 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
296 * @see org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping
297 * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter
298 */
299@Target({ElementType.METHOD, ElementType.TYPE})
300@Retention(RetentionPolicy.RUNTIME)
301@Documented
302@Mapping
303public @interface RequestMapping {
304
305        /**
306         * Assign a name to this mapping.
307         * <p><b>Supported at the type level as well as at the method level!</b>
308         * When used on both levels, a combined name is derived by concatenation
309         * with "#" as separator.
310         * @see org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder
311         * @see org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy
312         */
313        String name() default "";
314
315        /**
316         * The primary mapping expressed by this annotation.
317         * <p>In a Servlet environment this is an alias for {@link #path}.
318         * For example {@code @RequestMapping("/foo")} is equivalent to
319         * {@code @RequestMapping(path="/foo")}.
320         * <p>In a Portlet environment this is the mapped portlet modes
321         * (i.e. "EDIT", "VIEW", "HELP" or any custom modes).
322         * <p><b>Supported at the type level as well as at the method level!</b>
323         * When used at the type level, all method-level mappings inherit
324         * this primary mapping, narrowing it for a specific handler method.
325         */
326        @AliasFor("path")
327        String[] value() default {};
328
329        /**
330         * In a Servlet environment only: the path mapping URIs (e.g. "/myPath.do").
331         * Ant-style path patterns are also supported (e.g. "/myPath/*.do").
332         * At the method level, relative paths (e.g. "edit.do") are supported
333         * within the primary mapping expressed at the type level.
334         * Path mapping URIs may contain placeholders (e.g. "/${connect}").
335         * <p><b>Supported at the type level as well as at the method level!</b>
336         * When used at the type level, all method-level mappings inherit
337         * this primary mapping, narrowing it for a specific handler method.
338         * @see org.springframework.web.bind.annotation.ValueConstants#DEFAULT_NONE
339         * @since 4.2
340         */
341        @AliasFor("value")
342        String[] path() default {};
343
344        /**
345         * The HTTP request methods to map to, narrowing the primary mapping:
346         * GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
347         * <p><b>Supported at the type level as well as at the method level!</b>
348         * When used at the type level, all method-level mappings inherit
349         * this HTTP method restriction (i.e. the type-level restriction
350         * gets checked before the handler method is even resolved).
351         * <p>Supported for Servlet environments as well as Portlet 2.0 environments.
352         */
353        RequestMethod[] method() default {};
354
355        /**
356         * The parameters of the mapped request, narrowing the primary mapping.
357         * <p>Same format for any environment: a sequence of "myParam=myValue" style
358         * expressions, with a request only mapped if each such parameter is found
359         * to have the given value. Expressions can be negated by using the "!=" operator,
360         * as in "myParam!=myValue". "myParam" style expressions are also supported,
361         * with such parameters having to be present in the request (allowed to have
362         * any value). Finally, "!myParam" style expressions indicate that the
363         * specified parameter is <i>not</i> supposed to be present in the request.
364         * <p><b>Supported at the type level as well as at the method level!</b>
365         * When used at the type level, all method-level mappings inherit
366         * this parameter restriction (i.e. the type-level restriction
367         * gets checked before the handler method is even resolved).
368         * <p>In a Servlet environment, parameter mappings are considered as restrictions
369         * that are enforced at the type level. The primary path mapping (i.e. the
370         * specified URI value) still has to uniquely identify the target handler, with
371         * parameter mappings simply expressing preconditions for invoking the handler.
372         * <p>In a Portlet environment, parameters are taken into account as mapping
373         * differentiators, i.e. the primary portlet mode mapping plus the parameter
374         * conditions uniquely identify the target handler. Different handlers may be
375         * mapped onto the same portlet mode, as long as their parameter mappings differ.
376         */
377        String[] params() default {};
378
379        /**
380         * The headers of the mapped request, narrowing the primary mapping.
381         * <p>Same format for any environment: a sequence of "My-Header=myValue" style
382         * expressions, with a request only mapped if each such header is found
383         * to have the given value. Expressions can be negated by using the "!=" operator,
384         * as in "My-Header!=myValue". "My-Header" style expressions are also supported,
385         * with such headers having to be present in the request (allowed to have
386         * any value). Finally, "!My-Header" style expressions indicate that the
387         * specified header is <i>not</i> supposed to be present in the request.
388         * <p>Also supports media type wildcards (*), for headers such as Accept
389         * and Content-Type. For instance,
390         * <pre class="code">
391         * &#064;RequestMapping(value = "/something", headers = "content-type=text/*")
392         * </pre>
393         * will match requests with a Content-Type of "text/html", "text/plain", etc.
394         * <p><b>Supported at the type level as well as at the method level!</b>
395         * When used at the type level, all method-level mappings inherit
396         * this header restriction (i.e. the type-level restriction
397         * gets checked before the handler method is even resolved).
398         * <p>Maps against HttpServletRequest headers in a Servlet environment,
399         * and against PortletRequest properties in a Portlet 2.0 environment.
400         * @see org.springframework.http.MediaType
401         */
402        String[] headers() default {};
403
404        /**
405         * The consumable media types of the mapped request, narrowing the primary mapping.
406         * <p>The format is a single media type or a sequence of media types,
407         * with a request only mapped if the {@code Content-Type} matches one of these media types.
408         * Examples:
409         * <pre class="code">
410         * consumes = "text/plain"
411         * consumes = {"text/plain", "application/*"}
412         * </pre>
413         * Expressions can be negated by using the "!" operator, as in "!text/plain", which matches
414         * all requests with a {@code Content-Type} other than "text/plain".
415         * <p><b>Supported at the type level as well as at the method level!</b>
416         * When used at the type level, all method-level mappings override
417         * this consumes restriction.
418         * @see org.springframework.http.MediaType
419         * @see javax.servlet.http.HttpServletRequest#getContentType()
420         */
421        String[] consumes() default {};
422
423        /**
424         * The producible media types of the mapped request, narrowing the primary mapping.
425         * <p>The format is a single media type or a sequence of media types,
426         * with a request only mapped if the {@code Accept} matches one of these media types.
427         * Examples:
428         * <pre class="code">
429         * produces = "text/plain"
430         * produces = {"text/plain", "application/*"}
431         * produces = "application/json; charset=UTF-8"
432         * </pre>
433         * <p>It affects the actual content type written, for example to produce a JSON response
434         * with UTF-8 encoding, {@code "application/json; charset=UTF-8"} should be used.
435         * <p>Expressions can be negated by using the "!" operator, as in "!text/plain", which matches
436         * all requests with a {@code Accept} other than "text/plain".
437         * <p><b>Supported at the type level as well as at the method level!</b>
438         * When used at the type level, all method-level mappings override
439         * this produces restriction.
440         * @see org.springframework.http.MediaType
441         */
442        String[] produces() default {};
443
444}