SpringMVC RequestMapping
Quick note about request mapping annotations in SpringMVC controller
@RequestMapping
Annotation for mapping web requests onto specific handler classes and/or handler methods. It means DispatcherServlet intercepts the request, then it switches request to the corresponding method determined by @RequestMapping.
@RequestMapping("path")on class means all handling methods on this controller are relative to the given path.@RequestMapping("path")on method means mapping requests which match given path to this method
Properties
valueindicates url to map. If no other properties, we could use its simplified form@RequestMapping("path").methodindicates HTTP methods. It will support all methods if not specified .
1 | method = RquestMethod.GET |
consumesindicates Content-Type of the mapped request. A request will be mapped only when its Content-Type matches it.
1 | consumes = "application/json" |
producesindicates the producible media types of the mapped request, a request will be mapped only when Accept matches it.
1 | produces = "application/json" |
headersindicates only the requests having these headers can be mapped.
1 | headers = "content-type=text/*" |
paramsindicates only the requests having these parameters can be mapped. We could also add!=pr==to add conditions.
1 | // myParam exists and its value is myValue |
Example
1 |
|
Ant-style path patterns to indicate map url.
/user/*/loginmatches /user/aaa/login/user/**/loginmatches /user/login or /user/aaa/login or /user/aaa/bbb/login/user/login??matches /user/loginAA or /user/loginBB/user/{userId}matches /user/123 or /user/342 (using@PathVariableto indicate userID)
@PathVariable
It can be used on a method argument to bind it to the value of a URI template variable. The argument can be of any simple type such as int, long, Date, etc. Spring automatically converts to the appropriate type or throws a TypeMismatchException if it fails to do.
If we do not specify the url placeholder name like
@PathVariable('name'), we must keep method parameter name same as url placeholder.
1 |
|
A more complex example:
1 |
|
@RequestParam
It is used to bind request parameters to a method parameter in the controller. Do not mix it with @PathVariable which is used to obtain placeholders from the uri only.
As usual, we do it like this request.getParameter("name"), now with annotation:
1 |
|
It has three properties:
valueis the key to get value from requestrequiredis to indicate whether request must have this parameter. By default is true.defaultValueis to set default value when parameter in request does not exist.
Same as
@PathVariable('name'). If we do not specifyvalue. We must need to keep method parameter name the same as key.
@CookieValue
Same as @RequestParam but bind cookie values to a method parameter. It also has three properties value, required and defaultValue which are also the same
1 |
|