Restful 风格
RESTful
-
REST(Representational State Transfer):资源以某种表现形式在HTTP方法的作用下发生变化;
-
RESTful
实践-
获取数据
1
GET "http://localhost:8080/rest/user/1"
定位id为1的用户(资源),用GET方法获取,查询资源;
-
新增数据
1
2
3
4
5
6
7POST "http://localhost:8080/rest/user"
Content-Type:application/json
{
"name":"ming",
"age":3,
"email":"ming@test.com"
}POST方法的参数通常会被放在请求体中,以Content-Type中的格式(JSON)提交到服务端;
-
更新数据
1
2
3
4
5
6
7
8PUT "http://localhost:8080/rest/user"
Content-Type:application/json
{
"id":1,
"name":"ming",
"age":21,
"email":"ming@test.com"
}与POST的区别在于请求参数还要指定一个唯一字段(如id);
-
删除数据
1
DELETE "http://localhost:8080/rest/user/1"
-
-
RESTful风格由
URI
定位资源URI
:Uniform Resource IdentifierURL
:Uniform Resource LocatorURN
:Uniform Resource Name
所有的
URL
和URN
都可以称为URI
;URL
可以定位资源,而URN
不行;
spring 中的Restful应用
-
接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class UserController {
public String hello(){
return "hello";
}
public void userInfo1({ User user)
log.info(user.toString());
}
public void userInfo2({ Integer age)
System.out.println(age);
}
public void userInfo3(String name,Integer age){
System.out.println(name+" "+age);
}
} -
请求方式
1
GET localhost:8888/user
1
2
3
4
5
6POST localhost:8888/user
Content-Type:application/json
{
"name":"ming",
"age":"20"
} -
请求路径传参
1
POST localhost:8888/user/20
-
普通路径传参
1
POST localhost:8888/user/info?name=ming&age=20
评论