First, review and elaborate on the @controller, @RestController, @RequestMapping annotations used in the QuickStart. If you are unfamiliar with spring MVC and have not yet tried a QuickStart case, it is recommended that you take a look at QuickStart content first.
@Controller: Modifier class, used to create an object that handles HTTP requests
@RestController: Spring4 added after the note, the original in @controller back JSON needs @responsebody to cooperate, if directly
Replacing @controller with @restcontroller requires no further configuration of the @responsebody, which returns the JSON format by default.
@RequestMapping: Configuring URL Mappings
Here we try to use spring MVC to implement a set of restful APIs for user object operations, with comments detailing how in spring MVC
Map HTTP requests, how to pass parameters, and how to write unit tests.
The RESTful API is specifically designed as follows:
User Entity definition:
public class User { private Long id; private String name; private Integer age; // 省略setter和getter }
Implementing an interface to the user object
@RestController @RequestMapping (value= "/users")//by configuring this to make the following mappings under/users public class Usercontroller {//Create thread-safe m AP Static Map<long, user> users = Collections.synchronizedmap (new Hashmap<long, user> ()); @RequestMapping (value= "/", Method=requestmethod.get) public list<user> getuserlist () {//handle "/users/" ge T request, used to get a list of users//can also be passed @requestparam from the page parameters to query conditions or the transfer of page information list<user> r = new Arraylist<user> ( Users.values ()); return R; } @RequestMapping (value= "/", method=requestmethod.post) public String postuser (@ModelAttribute user user) { A POST request for "/users/" is used to create a user///In addition to the @modelattribute binding parameter, you can pass parameters users.put from the page by @requestparam (User.geti D (), user); Return "Success"; } @RequestMapping (value= "/{id}", method=requestmethod.get) public User getUser (@PathVariable Long ID) {// Get request to process "/users/{id}" to get user information for ID value in URL//ID in URL can be tied by @pathvariablereturn Users.get (ID) to the parameters of the function; } @RequestMapping (value= "/{id}", method=requestmethod.put) public String putuser (@PathVariable Long ID, @ModelAttr Ibute User user) {//Processing "/users/{id}" put request 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) { Delete request to process "/users/{id}" to delete user users.remove (ID); Return "Success"; } }
Building RESTful APIs