Spring MVC

Submodule within Spring lang.java.spring.web (Private), which provides specific capabilities for implementing MVC architecture.

Provides out-of-the-box REST service capabilities.

Defining web service using annotations

Stereotypes

@Controller

Makes Controllers capable of handling HTTP requests.

Works along with @RequestMapping annotation to map HTTP handler methods.

@RestController

@Controller + @ResponseBody

Special type of Controller, which combines @Controller and @RequestBody.

=> Return values of handler methods are automatically serialized into JSON or XML and returned as response.

NOTE: For the below annotations to work, it is important that the class is annotated with @Controller or @RESTController. Otherwise, it won't work, there won't be any errors, it simply wouldn't work.

Endpoints and HTTP methods

  • @RequestMapping
  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @PatchMapping
  • @DeleteMapping

Request, response and parameters

Payload and response

Can be specified by @RequestBody and @ResponseBody (not required if you're using REST Controller) annotation.

URI (Path) Params and Query (Request) Params

/users/{userId}/orders/{status}?search=keyword&page=1

@GetMapping("/users/{userId}/orders/{status}")
public String getItemUser(@PathVariable String userId, @PathVariable String status, @RequestParam("search") String searchString, @RequestParam int page){
...
}

Consuming Web Service

References


Backlinks