5. RESTful style of SpringMVC and ajax asynchronous interaction

5. RESTful style of SpringMVC and ajax asynchronous interaction

Springmvc uses MappingJackson2HttpMessageConverter to convert json data by default, and needs to add
jackson package; at the same time use <mvc:annotation-driven />

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.8</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.0</version>
</dependency>

1. @RequestBody annotation

This annotation is used for the formal parameter declaration of the Controller method. When submitted using ajax and specifying the contentType as json, it will be converted to the corresponding POJO object through the HttpMessageConverter interface.

    <input type="text" id="username" name="username" />
    <input type="text" id="age" name="age" />
    <button id="btn" >button2</button>
    <script>
        $("#btn").click(function () {
    
    

            let url = '${pageContext.request.contextPath}/user/ajaxRequest';
            let data = '[{"id":1,"username":"张三"},{"id":2,"username":"李四"}]';

            $.ajax({
    
    
                type: 'POST',
                url: url,
                data : data,
                contentType : 'application/json;charset=utf-8',
                success: function (resp) {
    
    
                    alert(JSON.stringify(resp));
                }
            })
        })
    @RequestMapping("/ajaxRequest")
    @ResponseBody
    public List<User> ajaxRequest(@RequestBody List<User> list){
    
    
        System.out.println(list);
        return list;
    }

2. @ResponseBody

This annotation is used to convert the object returned by the Controller method into data in the specified format through the HttpMessageConverter interface, such as: json, xml, etc., and respond to the client through Response.

/*
 @RequestMapping
 produces = "application/json;charset=utf-8" 响应返回数据的mime类型和编码,默认为
json
*/
@RequestMapping(value = "/ajaxRequest")
@ResponseBody
public List<User> ajaxRequest(@RequestBody List<User> list) {
    
    
  System.out.println(list);
  return list;
}

3. What is RESTful

Restful is a software architectural style and design style, not a standard, but only provides a set of design principles and constraints. Mainly used for client-server interaction software, software designed based on this style can be more concise, more hierarchical, and easier to implement caching mechanisms.

Restful-style requests use "url + request method" to indicate the purpose of a request. The four verbs in the HTTP protocol that indicate the operation method are as follows:

  • GET: read (Read)

  • POST: New (Create)

  • PUT:更新(Update)

  • DELETE: Delete

    image-20220312154246255

4. Code implementation

  • @PathVariable is
    used to receive the value of the placeholder in the RESTful request address
  • @RestController
    RESTful style is mostly used for front-end and back-end separation project development. The front-end interacts with the server asynchronously through ajax. Our processor usually returns json data, so @RestController is used to replace the @Controller and @ResponseBody annotations.
// @Controller
@RestController
public class RestFulController {
    
    
  @GetMapping(value = "/user/{id}")
  // 相当于 @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
  // @ResponseBody
  public String get(@PathVariable Integer id) {
    
    
    return "get:" + id;
 }
  @PostMapping(value = "/user")
  // @ResponseBody
  public String post() {
    
    
    return "post";
 }
  @PutMapping(value = "/user")
  // @ResponseBody
  public String put() {
    
    
    return "put";
 }
  @DeleteMapping(value = "/user/{id}")
  // @ResponseBody
  public String delete(@PathVariable Integer id) {
    
    
    return "delete:"+ id;
 }
}

Guess you like

Origin blog.csdn.net/qq_41239465/article/details/123447957