1.4. Annotated Controllers
springmvc提供了基于注解的编程模型,比如@Controller,@RestController.
|
|
1.4.1. Declaration
对于@Controller @Component等的beans可以由spring自动检测。不过这并不是默认开启的,你还需要设置一下:
|
|
|
|
1.4.2. Request Mapping
@RequestMapping是用来将一个request映射到一个方法上。既可以修饰方法也可以修饰controller。
根据不同的http请求方法也有些简写:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
|
|
URI patterns
对于你匹配的url,你可以使用?、、*来进行模糊匹配。
- ?:匹配单个字符
- *:匹配一个path segment中的任意多个字符
- **:匹配任意多个path segments。
你还可以在path中通过{varName}指定变量,然后再方法参数中通过@PathVariable获取:
|
|
uri变量会自动转换为你指定的类型,如果不能转换,那么会抛出TypeMismatchException异常。
你还可以为变量指定正则表达式{varName:regx}
|
|
你还可以用${}来引用placeholder。
Pattern comparison
当一个URL同时匹配多个模式时,只会选择最匹配的一个:
- URI模式变量的数目和通配符数量的总和最少的那个路径模式更准确。比如,
/hotels/{hotel}/*
这个路径拥有一个URI变量和一个通配符,而/hotels/{hotel}/**
这个路径则拥有一个URI变量和两个通配符,因此前者是更准确的路径模式。 - 如果两个模式的URI模式数量和通配符数量总和一致,则路径更长的那个模式更准确。举个例子,
/foo/bar*
就被认为比/foo/*
更准确,因为前者的路径更长。 - 如果两个模式的数量和长度均一致,则那个具有更少通配符的模式是更加准确的。比如,
/hotels/{hotel}
就比/hotels/*
更精确。 - 默认的通配模式
/**
比其他所有的模式都更“不准确”。比方说,/api/{a}/{b}/{c}
就比默认的通配模式/**
要更准确 - 前缀通配(比如
/public/**
)被认为比其他任何不包括双通配符的模式更不准确。比如说,/public/path3/{a}/{b}/{c}
就比/public/**
更准确
Consumable media types
匹配request中的Content-Type
|
|
支持!运算符,取反
Producible media types
匹配request中的Accept
|
|
Parameters, headers
|
|
|
|
1.4.3. Handler Methods
@RequestMapping修饰的方法还是有些限制的。他们的参数和返回值,只能是某些固定类型。
Method Arguments
Controller method argument | Description |
---|---|
WebRequest , NativeWebRequest |
Generic access to request parameters, request & session attributes, without direct use of the Servlet API. |
javax.servlet.ServletRequest , javax.servlet.ServletResponse |
Choose any specific request or response type — e.g. ServletRequest , HttpServletRequest , or Spring’s MultipartRequest , MultipartHttpServletRequest . |
javax.servlet.http.HttpSession |
Enforces the presence of a session. As a consequence, such an argument is never null . Note: Session access is not thread-safe. Consider setting theRequestMappingHandlerAdapter ‘s “synchronizeOnSession” flag to “true” if multiple requests are allowed to access a session concurrently. |
javax.servlet.http.PushBuilder |
Servlet 4.0 push builder API for programmatic HTTP/2 resource pushes. Note that per Servlet spec, the injected PushBuilder instance can be null if the client does not support that HTTP/2 feature. |
java.security.Principal |
Currently authenticated user; possibly a specific Principal implementation class if known. |
HttpMethod |
The HTTP method of the request. |
java.util.Locale |
The current request locale, determined by the most specific LocaleResolver available, in effect, the configured LocaleResolver /LocaleContextResolver . |
java.util.TimeZone + java.time.ZoneId |
The time zone associated with the current request, as determined by a LocaleContextResolver . |
java.io.InputStream , java.io.Reader |
For access to the raw request body as exposed by the Servlet API. |
java.io.OutputStream , java.io.Writer |
For access to the raw response body as exposed by the Servlet API. |
@PathVariable |
For access to URI template variables. See URI patterns. |
@MatrixVariable |
For access to name-value pairs in URI path segments. See Matrix variables. |
@RequestParam |
For access to Servlet request parameters. Parameter values are converted to the declared method argument type. See @RequestParam.Note that use of @RequestParam is optional, e.g. to set its attributes. See “Any other argument” further below in this table. |
@RequestHeader |
For access to request headers. Header values are converted to the declared method argument type. See @RequestHeader. |
@CookieValue |
For access to cookies. Cookies values are converted to the declared method argument type. See @CookieValue. |
@RequestBody |
For access to the HTTP request body. Body content is converted to the declared method argument type using HttpMessageConverter s. See @RequestBody. |
HttpEntity<B> |
For access to request headers and body. The body is converted with HttpMessageConverter s. See HttpEntity. |
@RequestPart |
For access to a part in a “multipart/form-data” request. See Multipart. |
java.util.Map , org.springframework.ui.Model , org.springframework.ui.ModelMap |
For access to the model that is used in HTML controllers and exposed to templates as part of view rendering. |
RedirectAttributes |
Specify attributes to use in case of a redirect — i.e. to be appended to the query string, and/or flash attributes to be stored temporarily until the request after redirect. See Redirect attributes and Flash attributes. |
@ModelAttribute |
For access to an existing attribute in the model (instantiated if not present) with data binding and validation applied. See @ModelAttribute as well as Model and DataBinder.Note that use of @ModelAttribute is optional, e.g. to set its attributes. See “Any other argument” further below in this table. |
Errors , BindingResult |
For access to errors from validation and data binding for a command object (i.e. @ModelAttribute argument), or errors from the validation of an @RequestBody or @RequestPart arguments; an Errors , or BindingResult argument must be declared immediately after the validated method argument. |
SessionStatus + class-level @SessionAttributes |
For marking form processing complete which triggers cleanup of session attributes declared through a class-level @SessionAttributes annotation. See@SessionAttributes for more details. |
UriComponentsBuilder |
For preparing a URL relative to the current request’s host, port, scheme, context path, and the literal part of the servlet mapping also taking into account Forwarded and X-Forwarded-* headers. See URI Links. |
@SessionAttribute |
For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level @SessionAttributes declaration. See@SessionAttribute for more details. |
@RequestAttribute |
For access to request attributes. See @RequestAttribute for more details. |
Any other argument | If a method argument is not matched to any of the above, by default it is resolved as an @RequestParam if it is a simple type, as determined byBeanUtils#isSimpleProperty, or as an @ModelAttribute otherwise. |
Return Values
for more details.
Controller method return value | Description |
---|---|
@ResponseBody |
The return value is converted through HttpMessageConverter s and written to the response. See @ResponseBody. |
HttpEntity<B> , ResponseEntity<B> |
The return value specifies the full response including HTTP headers and body be converted through HttpMessageConverter s and written to the response. See ResponseEntity. |
HttpHeaders |
For returning a response with headers and no body. |
String |
A view name to be resolved with ViewResolver ‘s and used together with the implicit model — determined through command objects and @ModelAttribute methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above). |
View |
A View instance to use for rendering together with the implicit model — determined through command objects and @ModelAttribute methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above). |
java.util.Map , org.springframework.ui.Model |
Attributes to be added to the implicit model with the view name implicitly determined through a RequestToViewNameTranslator . |
@ModelAttribute |
An attribute to be added to the model with the view name implicitly determined through a RequestToViewNameTranslator .Note that @ModelAttribute is optional. See “Any other return value” further below in this table. |
ModelAndView object |
The view and model attributes to use, and optionally a response status. |
void |
A method with a void return type (or null return value) is considered to have fully handled the response if it also has a ServletResponse , or an OutputStream argument, or an @ResponseStatus annotation. The same is true also if the controller has made a positive ETag or lastModified timestamp check (see Controllers for details).If none of the above is true, a void return type may also indicate “no response body” for REST controllers, or default view name selection for HTML controllers. |
DeferredResult<V> |
Produce any of the above return values asynchronously from any thread — e.g. possibly as a result of some event or callback. See Async Requestsand DeferredResult . |
Callable<V> |
Produce any of the above return values asynchronously in a Spring MVC managed thread. See Async Requests and Callable . |
ListenableFuture<V> ,java.util.concurrent.CompletionStage<V> ,java.util.concurrent.CompletableFuture<V> |
Alternative to DeferredResult as a convenience for example when an underlying service returns one of those. |
ResponseBodyEmitter , SseEmitter |
Emit a stream of objects asynchronously to be written to the response with HttpMessageConverter ‘s; also supported as the body of a ResponseEntity . See Async Requests and HTTP Streaming. |
StreamingResponseBody |
Write to the response OutputStream asynchronously; also supported as the body of a ResponseEntity . See Async Requests and HTTP Streaming. |
Reactive types — Reactor, RxJava, or others via ReactiveAdapterRegistry |
Alternative to DeferredResult with multi-value streams (e.g. Flux , Observable ) collected to a List .For streaming scenarios — e.g. text/event-stream , application/json+stream — SseEmitter and ResponseBodyEmitter are used instead, where ServletOutputStream blocking I/O is performed on a Spring MVC managed thread and back pressure applied against the completion of each write.See Async Requests and Reactive types. |
Any other return value | If a return value is not matched to any of the above, by default it is treated as a view name, if it is String or void (default view name selection via RequestToViewNameTranslator applies); or as a model attribute to be added to the model, unless it is a simple type, as determined by BeanUtils#isSimpleProperty in which case it remains unresolved. |
#####