Spring MVC — Mapping HTTP Requests

In this section, we're going to quickly brush up Spring MVC for REST API development. Let's begin with how to map HTTP requests to Java methods.

Controllers

A controller is a bean annotated with @RestController (or @Controller). Here is an example:

In controllers, methods annotated with @RequestMapping handle incoming HTTP requests. For example, the foo method above would handle GET /ping requests.

The value parameter of @RequestMapping, which is /ping in the above case, maps to the URL path. Similarly, the method parameter, which is GET in the above case, maps to the HTTP method. Consequently, the above foo method handles all GET /ping requests.

@GetMapping, @PostMapping etc.

Below are some shortcuts for @RequestMapping:

  1. @GetMapping - shortcut for @RequestMapping(method = RequestMethod.GET)
  2. @PostMapping - shortcut for @RequestMapping(method = RequestMethod.POST)
  3. @PutMapping - shortcut for @RequestMapping(method = RequestMethod.PUT)
  4. @PatchMapping - shortcut for @RequestMapping(method = RequestMethod.PATCH)
  5. @DeleteMapping - shortcut for @RequestMapping(method = RequestMethod.DELETE)

So, our foo method can also be written as below:

@PathVariable

Take another example of a request handler:

The {id} in the URL above is a path variable. That'd make fetchUserById handle requests of format GET /users/*, and the value of * would be received in the id parameter. For example, requests like GET /users/5 and GET /users/99 would hit this method. A request like GET /users/something would also hit this method, although an exception would be thrown when Spring would try to convert "something" to int (the type of the id parameter).

@RequestMapping at class level

Say you have a controller that handles GET /users, POST /users, GET /users/{id} and PUT /users/{id}, looking as below:

Notice that the URL of all the mappings above begin with /users. Such common prefix can be moved to a class level @RequestMapping, as below:

Now that we know how to map HTTP requests to Java methods, in the next lesson we'll see how to send HTTP response from those methods.

Complete and Continue  
Discussion

2 comments