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 .
method = RquestMethod.GET
method = {RquestMethod.GET, RquestMethod.POST}consumesindicates Content-Type of the mapped request. A request will be mapped only when its Content-Type matches it.
consumes = "application/json"
consumes = {"application/json", "text/html"}producesindicates the producible media types of the mapped request, a request will be mapped only when Accept matches it.
produces = "application/json"
produces = {"application/json", "charset=UTF-8"}headersindicates only the requests having these headers can be mapped.
headers = "content-type=text/*"paramsindicates only the requests having these parameters can be mapped. We could also add!=pr==to add conditions.
// myParam exists and its value is myValue
params="myParam = myValue"
// myParamA exists and its value is myValueA. // myParamB exists and its value is not myValueB
params = {"myParamA = myValueA", "myParamB != myValueB"}
// myParamA exists
params = "myParamA"
// myParamA exists and myParamB does not exits
params = {"myParamA", "!myParamB"} Example
@Controller
@RequestMapping("/users")
public class TestController {
// Handler all /users GET request
@RequestMapping(method = RequestMethod.GET)
public void functionA() {
...
}
// Handler all /users/new POST request
@RequestMapping(value="/new", method = RequestMethod.POST)
public void functionC() {
...
}
}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.
@Controller
@RequestMapping("/users")
public class TestController {
// Handler all /users/{id} GET request
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public void functionA(@PathVariable int id) {
...
}
// Or if you want another parameter name
//@RequestMapping(value="/{id}", method = RequestMethod.GET)
//public void functionB(@PathVariable("id") int anotherName) {
// // ToDo
//}
}A more complex example:
@Controller
@RequestMapping("/users/{userId}")
public class TestController {
@RequestMapping("/book/{bookId}")
public void test(@PathVariable String userId, @PathVariable String bookId) {
...
}
}@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:
@RequestMapping(value="/user/{userId}/books", method = RequestMethod.GET)
public void test(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
}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
@RequestMapping(value="/user", method = RequestMethod.GET)
public void test(@CookieValue("foo") String valueFromCookie) {
...
}@RequestBody and @ResponseBody
Check another note SpringMVC-Http-Message-Converters