当前位置:网站首页>Application of restful API based on MVC

Application of restful API based on MVC

2020-11-06 20:10:00 itread01

### Based on `MVC` Of `RESTful` The realization of style #### 1.`RESTful` Style statement > `REST` Service is a kind of `ROA`(Resource-Oriented Architecture, Resource Oriented Architecture ) Apply . The main feature is that method information exists in `HTTP` In the method of agreement (`GET`,`POST`,`PUT`,`DELETE`), Scope exists in `URL` in . for example , In a device resource list `GET` On request , The method information is `GET`, The scope information is URI It contains the filtering of device resources 、 Pagination and sorting, etc > > == good `REST API` You don't need any documents == ##### 1.1`REST` Style resource path `REST` Style of resource path design is resource oriented ,== The name of the resource == It should be an accurate description of the resource == Noun ==. > Resource path Overview :`sheme://host:port/path?queryString` > > example :http://localhost:8080/bywlstudio/users/user?username=xiuer ##### 1.2`HTTP` Method > `GET` Used for == Read ==、== Retrieve ==、== Inquire about ==、== Filtration == Resources > > `PSOT` Used for == establish == A resource > > `PUT` Used for == modify ==、== to update == Resources 、== Create a resource for the client to maintain the primary key information == > > `DELETE` Used for == Delete == Resources ** Resource address and `HTTP` Methods can be combined to achieve a complete positioning of resources ** ##### 1.3`RESTful` Style `API` Design * The above is about the adoption of HTTP Method and resource path to locate a resource on the server * Let's take a look at REST Style `API` Design of | function | describe | | -------------- | ------------------------------------------------------------ | | newly added / establish | `POST/users`
`PUT/users{id}`[^ Create a resource for the client to maintain the primary key information ] | | Delete | `DELETE/users/{id}` | | modify / to update | `PUT/users/{id}` | | Look up all | `GET/users` | | Primary key query | `GET/users/{id}`
`GET/users?id=26` | | Paging scope query | `GET/users?start=0&size=10`
`GET/users?07,2019-07,2020` | You can see through this `RESTAPI` It's all through the right to == The same resource == The operation of , The difference is through different ==HTTP Method == To achieve different processing of resources . #### 2.`MVC` Yes `REST` Support for ##### 1.1 Mainly through annotations * `@Controller` Name a controller that handles requests * `@RequestMapping` Request mapping address , It has several sub annotations for implementation `REST` In terms of style, it is more == Semantic == * `@GETMapping` ==GET Ask for == * `@PUTMapping` ==PUT Ask for == * `@POSTMapping` ==POST Ask for == * `@DELETEMapping` ==DELETE Ask for == * `@ResponseBody` Convert the response content to `JSON` Format * `@RequestBody` The request content is converted to `JSON` Format * `@PathVariable("id")` Used to bind an argument * `@RESTController` Equal to `@Controller`+`@ResponseBody` This annotation is written on the class , All methods that identify this class are only == Return data ==, Instead of == View jump == ##### 1.2 return `HTTP` Status code **`REST` Style `API` One of the most distinctive features is by returning the corresponding `HTTPStatus` To determine whether the operation of the client is completed ** == Here is spring About `Http` The enumeration class described by the state code , This paper lists the common status codes ==( If readers are interested in this, they can check `HttpStatus` Source code ) ~~~java public enum HttpStatus{ OK(200, "OK"),// Used for server with physical response CREATED(201, "Created"),// A new entity has been established , Respond to the entity NO_CONTENT(204, "No Content"),// The server is responding normally , But no physical response BAD_REQUEST(400, "Bad Request"),// Client request syntax error NOT_FOUND(404, "Not Found"),// The target resource does not exist INTERNAL_SERVER_ERROR(500, "Internal Server Error"),// Server internal error NOT_IMPLEMENTED(501, "Not Implemented"),// The server does not support the current request } ~~~ Spring The status code is returned by `@ResponseStatus` Note or `ResponseEntity ` Class . ==`@ResponseStatus` The way == ~~~java @GetMapping(path = "/user/{id}" , produces = "application/json;charset=utf-8") @ResponseStatus(HttpStatus.OK) public User findUserById(@PathVariable("id")Integer id){ User user = userService.findUserById(id); return user ; } ~~~ ==`ResponseEntity `== The way ~~~java @GetMapping(produces = "application/json;charset=utf-8") public ResponseEntity > findAll(){ List users = userService.findAll(); return new ResponseEntity >(users , HttpStatus.OK); } ~~~ ##### 1.3 Because of `MVC` Default not supported `PUT` and `DELETE` Method , So you need to turn it on manually * stay `tomcat` Server's `web.xml` Open the configuration in the file * ~~~xml default org.apache.catalina.servlets.DefaultServlet debug 0 listings false readonly true 1 ~~~ In the project `web.xml` Middle configuration ~~~xml HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter dispathcherServlet ~~~ #### 3.`MVC` Realize `REST` Code implementation ##### 3.1 Example environment * `JDK1.8` * `maven3.60` * `tomcat9` ##### 3.2`API` Design | URI | Description | Response | HTTPStatus | | --------------------- | ------------------------ | :------: | ---------- | | ==GET==/users | Get all users | `JSON` | 200 | | ==GET==/users/{id} | Gets the user of the specified primary key | `JSON` | 200 | | ==PUT==/users/{id} | Modify the user information of the specified primary key | `JSON` | 200/201 | | ==POST==/users | Add a user | `JSON` | 201 | | ==DELETE==/users/{id} | Delete a user | `void` | 204 | ##### 3.3 Control layer code ~~~java @RestController @RequestMapping("/users") public class UserControler { @Autowired private IUserService userService ; //REST Style implementation method /** * Query all * @return */ @GetMapping(produces = "application/json;charset=utf-8") public ResponseEntity > findAll(){ List users = userService.findAll(); return new ResponseEntity >(users , HttpStatus.OK); } /**、 * According to ID Inquire about * @param id * @return */ @GetMapping(path = "/{id}" , produces = "application/json;charset=utf-8") @ResponseStatus(HttpStatus.OK) public User findUserById(@PathVariable("id")Integer id){ User user = userService.findUserById(id); return user ; } /** * Add a user * Return the user */ @PostMapping(produces = "application/json;charset=utf-8") @ResponseStatus(HttpStatus.CREATED) public User addUser(@RequestBody User user){ User newUser = userService.addUser(user); return newUser ; } /** * to update * @param user */ @PutMapping(path = "/{id}" ,produces = "application/json;charset=utf-8") public ResponseEntity updateUser(@PathVariable("id") Integer id , @RequestBody User user){ user.setUid(id); // Whether the resource is modified boolean flag = userService.updateUser(user); User deUser = userService.findUserById(id); if(flag) return new ResponseEntity (deUser,HttpStatus.CREATED); return new ResponseEntity (deUser,HttpStatus.OK); } @DeleteMapping(path = "/{id}" , produces = "application/json;charset=utf-8") @ResponseStatus(HttpStatus.NO_CONTENT) public void delUser(@PathVariable("id") Integer id){ User user = userService.findUserById(id); userService.delUser(id); } } ~~~ More original articles and Java Learning materials focus on @ Public number Ma

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢