Based on theMVCtheRESTfulImplementation of Style

1.RESTfulstyle

RESTService is one
ROA(Resource-Oriented Architecture) applications. The main feature is that method information exists in
HTTPProtocol method (
GET.
POST.
PUT.
DELETE), the scope exists in
URLIn the. For example, in a list of device resources
GETIn the request, the method information is
GET, scope information is URI type containing conditions for filtering, paging, and sorting device resources

A good REST API does not require any documentation ==

1.1RESTStyle 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.2HTTPmethods

GETFor == Read ==, == Retrieve ==, == Query ==, == Filtering == Resources

PSOT 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 andHTTPMethods are combined to achieve a complete location of a resource

1.3RESTfulstyleAPIdesign

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.MVCrightRESTThe support of

1.1 mainly through annotations to achieve
  • @ControllerName 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
  • @ResponseBodyConvert the response content toJSONformat
  • @RequestBodyThe request content is converted toJSONformat
  • @PathVariable("id")Used to bind a parameter
  • @RESTControllerIs equivalent to@Controller+@ResponseBodyThis 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 returnHTTPStatus code

RESTstyleAPIOne of the most distinctive features is the return of the correspondingHTTPStatusTo 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 theMVCNot supported by defaultPUTandDELETEMethod, so it needs to be turned on manually

intomcatThe server’sweb.xmlOpen 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.MVCimplementationRESTCode implementation

3.1 Instance Environment
  • JDK1.8
  • maven3.60
  • tomcat9
3.2APIdesign
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


  1. Create a resource ↩ where the client maintains primary key information