First, review and elaborate on what is used in Quick Start @Controller Annotations: @RestController, @RequestMapping. If you're not familiar with Spring MVC and haven't tried the Quick Start case yet, it's recommended to take a look at the Quick Start content first.
- @Controller Modify class to create objects that handle http requests
- @ RestController: Annotations added after Spring 4 originally require @ResponseBody to cooperate with the return of json in @Controller. If @RestController is directly used instead of @Controller, there is no need to reconfigure @ResponseBody, and json format is returned by default.
- @ RequestMapping: Configuring url mappings
Next, we try to use Spring MVC to implement a set of RESTful API s for manipulating User objects. With annotations, we explain in detail how to map HTTP requests, how to pass parameters, and how to write unit tests in Spring MVC.
RESTful API is designed as follows:
User entity definition:
public class User { private Long id; private String name; private Integer age; // Omit setter and getter }
Implementing the Operational Interface to User Objects
@RestController @RequestMapping(value="/users") // Configuration allows the following mappings to be under / users public class UserController { // Create thread-safe Map s static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); @RequestMapping(value="/", method=RequestMethod.GET) public List<User> getUserList() { // Processing GET requests for'/ users /'to obtain user lists // You can also pass parameters from the page through @RequestParam to transfer query conditions or page turning information. List<User> r = new ArrayList<User>(users.values()); return r; } @RequestMapping(value="/", method=RequestMethod.POST) public String postUser(@ModelAttribute User user) { // Processing POST requests for'/ users /'to create User // In addition to @ModelAttribute binding parameters, you can also pass parameters from pages through @RequestParam users.put(user.getId(), user); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { // Processing GET requests for "/users/{id}" to obtain User information for ID values in URLs // The id in the url can be bound to the parameters of the function by @PathVariable return users.get(id); } @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { // Processing PUT requests for "/users/{id}" to update User information User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // Processing DELETE requests for "/users/{id}" to delete User users.remove(id); return "success"; } }
Source Source Technology Support for Complete Project 1791743380