当前位置:网站首页>Restful style details
Restful style details
2022-07-29 08:41:00 【Who is Huang Huang】
One . What is? Restful style
1.1 Concept
RESTFUL It is a kind of design style and development method of network application program , be based on HTTP, have access to XML Format definition or JSON Format definition . The most common data format is JSON. because JSON Can be directly by JavaScript Read , therefore , Use JSON Format REST Style API Simple 、 Easy to read 、 Easy to use features .
1. It's a style , It's not the agreement , This style is more brief and beautiful
2. be based on HTTP, have access to XML Format definition or JSON Format definition , It is used in the era of front and back separation json Passing the data
1.2 REST It's resource oriented
Each resource has a unique resource locator (URI). Every URI Represents a resource (resource), therefore URI There can be no verbs in , Only nouns , And the nouns used often correspond to the table name of the database .
1. Resource oriented access json data , How to face resources ?
2. adopt url Address to get resources , How to pass url Address to get resources
3. stay url Add parameters after the address , Pay attention to is : stay url Only nouns can be added after , That is, the value of writing death ,( Be similar to session A kind of parameter transmission , Go to url Write the value after the address , But the two are quite different , The following distinction )
4.url The nouns added later often correspond to the table name of the database ,
5. Most of the time , We operate on the database and get many values , Will choose to pass list Set up these many values ), therefore URI The nouns in should also use the plural
1.3 Request mode
| Commonly used | - |
|---|---|
| Request mode | meaning |
| get | Inquire about |
| post | Add to change |
| delete | Delete |
| Not commonly used | - |
|---|---|
| Request mode | meaning |
| put | Update resources on the server ( Update full resources ) |
| update | Update resources on the server , PATCH Update individual properties |
1.4 The traditional model URl and Restful Style contrast
1.4.1 Inquire about
| Inquire about | Tradition | REST | REST Background reception |
|---|---|---|---|
| Query all | http://localhost:8080/employee/ | http://localhost:8080/employees | @RequestMapping(value = “/employees”, method = RequestMethod.GET) |
| Query individual | http://localhost:8080/employee/list?id=1 | http://localhost:8080/employees/1 | @RequestMapping(value = “/employees/{id}”, method = RequestMethod.GET) @ResponseBody public Employee queryById(@PathVariable Long id) {} |
1.4.2 add to
| add to | Tradition | REST | REST Background reception |
|---|---|---|---|
| add to | http://localhost:8080/employee/add | http://localhost:8080/employees | @RequestMapping(value = “/employees”, method = RequestMethod.POST) public Employee add(@ModelAttribute(“emp”) Employee employee) {} |
1.4.3 modify
| modify | Tradition | REST | REST Background reception |
|---|---|---|---|
| add to | http://localhost:8080/employee/update | http://localhost:8080/employees | @RequestMapping(value = “/employees”, method = RequestMethod.PUT) public Employee update(@ModelAttribute(“emp”) Employee employee) {} |
1.4.4 Delete
| Delete | Tradition | REST | REST Background reception |
|---|---|---|---|
| Delete | http://localhost:8080/employee/delete | http://localhost:8080/employees | @RequestMapping(value = “/employees/{id}”, method = RequestMethod.DELETE) @ResponseBody public JsonResult delete(@PathVariable Long id) {} |
Be careful :
1. When the parameters to be returned are not single , Do not use parameter path
2. When the parameter name is sensitive , It is recommended to use parameter path , Parameter names can be hidden
Two . Restful Specification of style
The principles followed : From Baidu Encyclopedia
1、 every last URI representative 1 Species resources ;
2、 Client side usage GET、POST、PUT、DELETE4 Verbs representing operation mode operate on server resources :GET Used to obtain resources ,POST Used to create a new resource ( Can also be used to update resources ),PUT Used to update resources ,DELETE Used to delete resources ;
3、 Operate resources through their representation ;
4、 The expression of resources is XML perhaps HTML;
5、 The interaction between client and server is stateless between requests , Every request from the client to the server must contain the information necessary to understand the request . [1]
3、 ... and .Restful Notes related to style
| annotation | effect |
|---|---|
| @RestController | from @Controller + @ResponseBody form ( return JSON data format ) |
| @PathVariable | URL Medium {xxx} Placeholders can be @PathVariable(“xxx“) Bound to the formal parameters of the controller processing method |
| @RequestMapping | Annotation is used for the resolution of the request address , Is the most commonly used annotation |
| @GetMapping | Query request |
| @PostMapping | Add request |
| @DeleteMapping | Delete request |
| @RequestParam | Bind the request parameters to the method parameters of your controller ( yes springmvc Receive comments for common parameters in ) |
3.1 @RequestParam Use caution
grammar
grammar :@RequestParam(value=” Parameter name ”,required=”true/false”,defaultValue=””)
value: Parameter name
required: Whether to include this parameter , The default is true, Indicates that the request path must contain the parameter , If it is not included, an error is reported .
defaultValue: Default parameter value , If the value is set ,required=true Will fail , Automatically for false, If the parameter is not passed , Just use the default values
@RequestParam The correct use of – Bound object
Here is an added interface , It should be noted that , Here we are @RequestParam This annotation is better Used to bind objects To the method parameters of our controller . And Only one parameter can be bound , So when we use this annotation to pass json Data time , It's best to package all the data into a wrapper class .
1. Bind a parameter
2. Can only be used to pass objects
3. Cannot pass an object a parameter value , One binding, one unbound
@PostMapping("/insert")
public ResponseCode addEmployeeec(@PathVariable Employeeec employeeec){
int counts = employeeecService.addEmployeeec(employeeec);
if (counts == 1) {
return ResponseCode.ok(" Insert the success ");
}else if (counts == -1){
return ResponseCode.error(" Users exist , Insert the failure ");
}
return ResponseCode.error(" User insertion failed ");
}

500 error
1. Server error
2. Generally speaking, the code is written incorrectly
3. Or there is something wrong with this way of request
Switch to
@PostMapping("/insert")
public ResponseCode addEmployeeec(@RequestBody Employeeec employeeec){
int counts = employeeecService.addEmployeeec(employeeec);
if (counts == 1) {
return ResponseCode.ok(" Insert the success ");
}else if (counts == -1){
return ResponseCode.error(" Users exist , Insert the failure ");
}
return ResponseCode.error(" User insertion failed ");
}

Description when delivered json As an object , We need to use it. @RequestParam
@RequestParam The wrong use of 1: Bind a parameter
// Test use
@DeleteMapping("/delete/{id}")
public ResponseCode deleteEmployeeec(@RequestBody Integer id){
int count = employeeecService.deleteEmployeeec(id);
if (count ==1 ){
return ResponseCode.ok(" Delete successful ");
}else if (count ==-1) {
return ResponseCode.error(" The user doesn't exist , Delete failed ");
}
return ResponseCode.error(" User deletion failed ");
}

400 error Http error
1.400 Wrong request
2. Due to syntax format error , The server could not understand the request
3. invalid URL
4. The browser sent a request that this server cannot understand
But instead
@DeleteMapping("/delete/{id}")
public ResponseCode deleteEmployeeec(@PathVariable Integer id){
int count = employeeecService.deleteEmployeeec(id);
if (count ==1 ){
return ResponseCode.ok(" Delete successful ");
}else if (count ==-1) {
return ResponseCode.error(" The user doesn't exist , Delete failed ");
}
return ResponseCode.error(" User deletion failed ");
}

400 error Http error
1.400 Wrong request
2. Due to syntax format error , The server could not understand the request
3. invalid URL
4. The browser sent a request that this server cannot understand
@RequestParam The wrong use of 2: Bind two parameters
Here is a paging query , Let's try binding two parameters with it
@GetMapping("/{page}/{size}")
public List<Employeeec> getAllEmployeeec(@RequestBody Integer page ,@RequestBody Integer size){
return employeeecService.getAllEmployeec(page,size);
}

400 error Http error
1.400 Wrong request
2. Due to syntax format error , The server could not understand the request
3. invalid URL
4. The browser sent a request that this server cannot understand
@GetMapping("/{page}/{size}")
public List<Employeeec> getAllEmployeeec(@PathVariable Integer page ,@PathVariable Integer size){
return employeeecService.getAllEmployeec(page,size);
}

@RequsetParam The wrong use of 3: Bind an object , One parameter , In this case, brothers pack it with packaging , I feel something wrong when I look at it ..
[email protected] Use standard – It must be a binding parameter, not an object
边栏推荐
- 01背包关于从二维优化到一维
- PostgreSQL manually creates hikaridatasource to solve the error cannot commit when autocommit is enabled
- Gan: generate adversarial networks
- Sword finger offer 32 - ii Print binary tree II from top to bottom
- Lesson 3 threejs panoramic preview room case
- 完全背包问题 从朴素到终极
- 2022 electrician (elementary) test question simulation test platform operation
- C language -- 22 one dimensional array
- Analysis of zorder sampling partition process in Hudi - "deepnova developer community"
- Chrony time synchronization
猜你喜欢
![[from_bilibili_dr_can][[advanced control theory] 9_ State observer design] [learning record]](/img/9d/d9a4a3091c00ec65a9492ca49267db.png)
[from_bilibili_dr_can][[advanced control theory] 9_ State observer design] [learning record]

2022危险化学品经营单位主要负责人操作证考试题库及答案

谷歌浏览器免跨域配置

Simple operation of SQL server data table

Arfoundation starts from scratch 5-ar image tracking

QT version of Snake game project

C language calculates the length of string

centos7/8命令行安装Oracle11g

AI application lesson 1: C language Alipay face brushing login

The first week of postgraduate freshman training: deep learning and pytorch Foundation
随机推荐
C language watch second kill assist repeatedly
7.3-function-templates
Sword finger offer 50. the first character that appears only once
搜索与回溯经典题型(八皇后)
Centos7/8 command line installation Oracle11g
Design of distributed (cluster) file system
Day6: use PHP to write file upload page
英语高频后缀
The first week of postgraduate freshman training: deep learning and pytorch Foundation
6.2 function-parameters
Node: file write data (readfile, WriteFile), two modes: overwrite and increment
Count the list of third-party components of an open source project
What are the backup and recovery methods of gbase 8s database
集群使用规范
Day4: the establishment of MySQL database and its simplicity and practicality
AI application lesson 1: C language Alipay face brushing login
Virtual augmentation and reality Part 2 (I'm a Firebird)
深度学习(1):银行客户流失预测
【OpenCV】-算子(Sobel、Canny、Laplacian)学习
Collation of ml.net related resources