Based on theMVC
theRESTful
Implementation of Style
1.RESTful
style
REST
Service is one
ROA
(Resource-Oriented Architecture) applications. The main feature is that method information exists in
HTTP
Protocol method (
GET
.
POST
.
PUT
.
DELETE
), the scope exists in
URL
In the. For example, in a list of device resources
GET
In the request, the method information is
GET
, scope information is URI type containing conditions for filtering, paging, and sorting device resourcesA good REST API does not require any documentation ==
1.1REST
Style Resource Path
The RESTful style of resource routing design is resource-oriented, and == the name == of the resource should be the == noun == that accurately describes the resource.
Resource path overview:
sheme://host:port/path? queryString
Example: http://localhost:8080/bywlstudio/users/user? username=xiuer
1.2HTTP
methods
GET
For == Read ==, == Retrieve ==, == Query ==, == Filtering == ResourcesPSOT is used for == to create == a resource
PUT is used for == to modify ==, == to update == resources, == to create resources == for the client to maintain primary key information
Delete is used for == to DELETE == resources
Resource address andHTTP
Methods are combined to achieve a complete location of a resource
1.3RESTful
styleAPI
design
The previous section described the process of locating a resource on a server using HTTP methods and resource paths
Next, look at the design of a RESTful API
function | describe |
---|---|
Add/Create | POST/users PUT/users{id} 1 |
delete | DELETE/users/{id} |
Modifications/Updates | PUT/users/{id} |
All the query | GET/users |
The primary key query | GET/users/{id} GET/users? id=26 |
Paging scoped queries | GET/users? start=0&size=10 GET/users? 0. 07201-07202 |
You can see that through this RESTAPI all the operations are performed on == the same resource ==, the only difference is the different ==HTTP method == to handle the resource differently.
2.MVC
rightREST
The support of
1.1 mainly through annotations to achieve
@Controller
Name a controller that handles requests-
The @RequestMapping RequestMapping address, which has several sub-annotations, is more == semantically == for implementing the REST style
@GETMapping
= = = = the GET request@PUTMapping
= = = = the PUT request@POSTMapping
= = = = the POST request@DELETEMapping
= = = = the DELETE request
@ResponseBody
Convert the response content toJSON
format@RequestBody
The request content is converted toJSON
format@PathVariable("id")
Used to bind a parameter@RESTController
Is equivalent to@Controller
+@ResponseBody
This annotation is written on the class to indicate that all methods of the class only return data == and do not do a == view jump ==
1.2 returnHTTP
Status code
REST
styleAPI
One of the most distinctive features is the return of the correspondingHTTPStatus
To determine whether the client has completed the operation
The following is an enumeration of Spring classes for HTTP status code descriptions. This article lists the common status code == (for readers interested in this, see the HttpStatus source code)
Public enum httpStatus {OK(200, "OK"),// The response CREATED by the server has an entity, No_content (204, "No Content") in response to the entity,// The server responds normally, NOT_FOUND(404, "NOT FOUND "); INTERNAL_SERVER_ERROR(500," NOT FOUND "); INTERNAL_SERVER_ERROR(500, "NOT FOUND "); INTERNAL_SERVER_ERROR(500," NOT FOUND "); Implemented (501, "Not Implemented"),// The Server does Not support the current request}
Spring returns the status code via the @responseStatus annotation or responseEntity
class implementation.
= = = = @ ResponseStatus way
@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
= =
@GetMapping(produces = "application/json; charset=utf-8") public ResponseEntity<List<User>> findAll(){ List<User> users = userService.findAll(); return new ResponseEntity<List<User>>(users , HttpStatus.OK); }
1.3 due to theMVC
Not supported by defaultPUT
andDELETE
Method, so it needs to be turned on manually
intomcat
The server’sweb.xml
Open the configuration in the file
<servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>listings</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>readonly</param-name> <param-value>true</param-value><! > </init-param> </load-on-startup> 1</load-on-startup> </servlet>
Configure in the web.xml of the project
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>dispathcherServlet</servlet-name>
</filter-mapping>
3.MVC
implementationREST
Code implementation
3.1 Instance Environment
JDK1.8
maven3.60
tomcat9
3.2API
design
URI | Description | Response | HTTPStatus |
---|---|---|---|
==GET==/users | Acquire all users | JSON |
200 |
==GET==/users/{id} | Gets the user with the specified primary key | JSON |
200 |
==PUT==/users/{id} | Modifies the user information for 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
@RestController @RequestMapping("/users") public class UserControler { @Autowired private IUserService userService ; /** * Produces = "Factories (Produces =" Factories (Produces = "Factories"); charset=utf-8") public ResponseEntity<List<User>> findAll(){ List<User> users = userService.findAll(); return new ResponseEntity<List<User>>(users , HttpStatus.OK); } /**, * @Param * @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 ; } /** * @PostMapping(Produces = "results /json") */ @PostMapping(Produces = "results /json; charset=utf-8") @ResponseStatus(HttpStatus.CREATED) public User addUser(@RequestBody User user){ User newUser = userService.addUser(user); return newUser ; } /** * update * @param user */ @putMapping (path = "/{id}", Produces = "application/json; charset=utf-8") public ResponseEntity<User> updateUser(@PathVariable("id") Integer id , @RequestBody User user){ user.setUid(id); Boolean Flag = UserService.updateUser (user); User deUser = userService.findUserById(id); if(flag) return new ResponseEntity<User>(deUser,HttpStatus.CREATED); return new ResponseEntity<User>(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 @public MakerStack
- Create a resource ↩ where the client maintains primary key information