【SpringBoot】| Interface Architecture Style—RESTful

Table of contents 

1: Interface Architecture Style—RESTful

1. Understanding RESTful

2. RESTful annotations


1: Interface Architecture Style—RESTful

1. Understanding RESTful

(1) Interface

① Interface: API (Application Programming Interface, application programming interface) is some predefined interfaces (such as functions, HTTP interfaces), or refers to the agreement of connecting different components of the software system . A set of routines that applications and developers can access based on a piece of software or hardware without accessing the source code or understanding the details of the inner workings .

②Interface (API): It can refer to accessing servlets, urls of controllers, and calling functions of other programs.

(2) Architecture style

Refers to the way the API is organized (what it looks like), which is a traditional style: http://localhost:9002/mytrans/addStudent?name=lisi&age=26

The access resource name addStudent is provided on the address, and then the get method is used to pass parameters.

(3) REST architectural style

REST: It is an interface architectural style and design concept, not a standard. (English: Representational State Transfer, Chinese: Representational State Transfer)

① Presentation layer state transition:

Presentation layer: It is the view layer, which displays resources, such as jsp, etc., to display the results of operating resources.

Status: Indicates a change to the resource.

Transfer: Resources can be changed; resources can be created (new state), resources can be queried after resources are created (the content of the resource can be seen), and the content of the resource can be modified (the modified resource is different from the previous one).

②Elements in REST: use REST to represent resources and operations on resources

Resources are represented by URLs, and resources are represented by nouns:

In url, use nouns to represent resources and access resource information. In url, use "/" to separate resource information, for example: http:// localhost:8080/myboot/student/1001

Query resources: find resources by url.

Create resource: Add a resource.

Update resource: update resource, edit.

Delete resource: remove.

Use the action (request mode) in http to represent the operation on resources (CURD): 

GET: query resources ---> sql select

Dealing with a single resource: use its singular form

http://localhost:8080/myboot/student/1001

http://localhost:8080/myboot/student/1002

Handling Multiple Resources: Use Plurals

http://localhost:8080/myboot/students/1001/1002

POST: create resource ---> sql insert

http://localhost:8080/myboot/student

Pass data in post request

<form action="http://localhost:8080/myboot/student" method="post">
	姓名:<input type="text" name="name" />
    年龄:<input type="text" name="age" />
</form>

PUT: update resource ---> sql update

Browsers cannot directly support put, so make a post first; then use a hidden field to turn the post request into a real put

<form action="http://localhost:8080/myboot/student/1" method="post">
	姓名:<input type="text" name="name" />
    年龄:<input type="text" name="age" />
    <input type="hidden" name="_method" value="PUT" />
</form>

DELETE: delete resources ---> sql delete

<a href="http://localhost:8080/myboot/student/1">删除1的数据</a>

Summary: use url to represent resources, and use http actions to manipulate resources!

(4) Pagination

If parameters such as pagination and sorting are required, they should still be placed after the url in the form of ?, for example:

http://localhost:8080/myboot/students?page=1&pageSize=20

(5) Advantages

① Lightweight: directly based on http, no other protocol such as message is needed.

②Resource-oriented: It is clear at a glance and self-explanatory.

③Simple data description: Generally, data exchange is done with xml and json.

④ Stateless: When calling an interface (accessing and operating resources), you don't need to consider the context or the current state, which greatly reduces the complexity.

⑤Simple and low coupling

2. RESTful annotations

@PathVariable , used to obtain the data in the url ; this annotation is the most important annotation to realize RESTFul!

@GetMapping , receive the request of get method ; it is equivalent to @RequestMapping( method=RequestMethod.GET).

@PostMapping , receive and process the request of Post mode ; it is equivalent to @RequestMapping( method=RequestMethod.POST).

@PutMapping , receive the request of put method ; it is equivalent to @RequestMapping( method=RequestMethod.PUT).

@DeleteMapping , to receive requests in delete mode ; equivalent to @RequestMapping( method=RequestMethod.DELETE).

@RestController composite annotation is a combination of @Controller and @ResponseBody ; using @RestController on the class means that all methods of the current class have been added to @ResponseBody.

Case: Joint use of @PathVariable annotation and @GetMapping annotation (query resources)

① Use the @RestController composite annotation on the class to hand over the current class to the Spring container for management, and add @ResponseBody to each method under the class by default.

② Use the GetMapping annotation to send a get request. We know that there are no variables in the Restful style request path, so you must first use {variable name} to define the path variable , and then use the path variable @PathVariable annotation to reference the path variable ; for example: queryStudent(@PathVariable (value = "stuId") Integer stuId) means to assign the value passed from the path variable to the stuId variable.

package com.zl.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {

    @GetMapping("/student/{stuId}")
    public String queryStudent(@PathVariable(value = "stuId") Integer stuId){
        return "Studnet的id是:"+stuId;

    }
}

Results of the:

According to the value passed by the url, it is assigned to the path variable, and the path variable allows us to get the data and display it through the @PathVariable annotation.

Case: Joint use of @PathVariable annotation and @PostMapping annotation (creating resources)

addStudent.html form page (belonging to static resources placed in the static directory), transfer data in the post request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>添加学生</h3>
    <form action="student/zhangsan/18" method="post">
        <input type="submit" value="注册学生">
    </form>
</body>
</html>

Receive data

    // 创建资源
    @PostMapping("/student/{name}/{age}")
    public String createStudent(@PathVariable("name") String name,
                                @PathVariable("age") Integer age){
        return "创建资源Student"+name+"="+age;
    }

Results of the:

Case: It is cumbersome to write a form page for Post, Put, and Delete, and the browser does not support put and delete requests; you can use a Postman tool

Note: When the path variable name is consistent with the formal parameter name, the value in @PathVariable can be omitted.

Postman test tool: can test get, post, put, delete and other requests

    // 更新资源
    @PutMapping("/student/{id}/{age}")
    public String modifyStudent(@PathVariable Integer id,
                                @PathVariable Integer age){
        return "更新资源Student:"+id+"="+age;
    }


    // 删除资源
    @DeleteMapping("/student/{id}")
    public String removeStudentById(@PathVariable Integer id){
        return "删除资源Student:"+id;
    }

Execution result: Save writing the form page

Case: Use HiddenHttpMethodFilter filter to convert post request to put, delete

In SpringMVC there is a filter org.springframework.web.filter.HiddenHttpMethodFilter.

Function: Convert the post request in the request to put, delete.

Step 1: In application.properties(yml): enable HiddenHttpMethodFilter filter

Source code analysis found that this component has been configured by default in SpringBoot, but it is turned off by default. To take effect, it must be manually set to take effect.

package org.springframework.boot.autoconfigure.web.servlet;

public class WebMvcAutoConfiguration {
	@Bean
	@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
	@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled")
	public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
		return new OrderedHiddenHttpMethodFilter();
	}
}

set to true

#启用过滤器
spring.mvc.hiddenmethod.filter.enabled=true

Step 2: In the request page, send a post request; the type type uses the hidden field hidden, the name parameter is _method, and the value corresponds to our real request method put, delete

The form form page actually sends out a put request!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="student/test" method="post" >
        <!--指定真正的请求方式-->
        <input type="hidden" name="_method" value="put">
        <input type="submit" value="测试" />
    </form>
</body>
</html>

Extension: Currently, the _method parameter can also be set as a custom parameter

Through the previous source code analysis, if there is no custom HiddenHttpMethodFilter, the container will help us customize one into container management. The default parameter used at this time is _method!

So you can create a HiddenHttpMethodFilter yourself, call the setMethodParam method to define it yourself

package com.zl.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
 
@Configuration(proxyBeanMethods = false)
public class MyConfig {
    // 自定义Filter,纳入容器管理
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        // 设置method参数为_m
        methodFilter.setMethodParam("_m");
        return methodFilter;
    }
 
}

Problem: request path conflict

For example: the following two requests use get requests, the resource names are the same, and the data types carried are also the same; we directly access: http://localhost:8081/student/1 ; at this time, there will be path conflicts, resulting in access fail!

Solution: The design path must be unique, and the path uri and request method must be unique!

@GetMapping("/student/{id}") 
@GetMapping("/student/{age}")

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/129368624