SpringMVC 06 -RESTFul风格接口设计
RESTFul风格接口设计
-
- 1 REST开发风格
-
- 1.1 路径
- 1.2 HTTP动词
- 1.3 过滤信息
- 1.4 返回结果
- 2 定义Rest风格的 Controller
- 3 前端使用Ajax请求实现
- 4 配置put请求过滤器(可省)
- 5 前端使用表单实现Put和delete
1 REST开发风格
Representational State Transfer简称:REST 直接翻译:表现层状态转移
是一种开发风格,遵从此风格开发软件,符合REST风格,则RESTFUL。
RESTful架构:
- 每一个URI代表一种资源
- 客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层状态转化"
1.1 路径
访问标识 | 资源 |
---|---|
http://localhost:8989/xxx/users | 所有用户 |
http://localhost:8989/xxx/users/1 | 用户1 |
http://localhost:8989/xxx/users/1/orders | 用户1的所有订单 |
1.2 HTTP动词
- GET(SELECT):从服务器取出资源(一项或多项)。
- POST(CREATE):在服务器新建一个资源。
- PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
- PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
- DELETE(DELETE):从服务器删除资源。
请求方式 | 标识 | 意图 |
---|---|---|
GET | http://localhost:8989/xxx/users | 查询所有用户 |
POST | http://localhost:8989/xxx/users | 在所有用户中增加一个 |
PUT | http://localhost:8989/xxx/users | 在所有用户中修改一个 |
DELETE | http://localhost:8989/xxx/users/1 | 删除用户1 |
GET | http://localhost:8989/xxx/users/1 | 查询用户1 |
GET | http://localhost:8989/xxx/users/1/orders | 查询用户1的所有订单 |
POST | http://localhost:8989/xxx/users/1/orders | 在用户1的所有订单中增加一个 |
1.3 过滤信息
- ?limit=10:指定返回记录的数量
- ?offset=10:指定返回记录的开始位置。
- ?page=2&limit=100:指定第几页,以及每页的记录数。
- ?sortby=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序。
- ?animal_type_id=1:指定筛选条件
1.4 返回结果
- GET /collection:返回资源对象的列表(数组)
- GET /collection/resource:返回单个资源对象
- POST /collection:返回新生成的资源对象
- PUT /collection/resource:返回完整的资源对象
- PATCH /collection/resource:返回完整的资源对象
- DELETE /collection/resource:返回一个空文档
2 定义Rest风格的 Controller
@RequestMapping(value = “/users”,method = RequestMethod.GET)
等价
@GetMapping(“/users”)
@RestController
@RequestMapping("/users")
public class UserController {@GetMappingpublic DataResult getAll(Integer pageNum,Integer limit){System.out.println("查询所有user"+"...."+pageNum+"..."+limit);List<User> userList = new ArrayList<>();for (int i = 0; i < 10; i++) {userList.add(new User("张三"+i,"123","1234"+i,30+i));}return new DataResult(200,"查询成功",userList);}@GetMapping("/{id}")public DataResult getOne(@PathVariable Integer id){User user = new User("张三","123","1234",30);System.out.println("查询指定id");return new DataResult(200,"查询成功",user);}@PostMappingpublic DataResult addUser(@RequestBody User user){System.out.println("增加..."+user);return new DataResult(200,"添加成功");}@DeleteMapping("/{id}")public DataResult deleteUser(@PathVariable Integer id){System.out.println("删除"+id);return new DataResult(200,"删除成功");}@PutMapping("/{id}")public DataResult updateUser(@RequestBody User user){System.out.println("修改..."+user.getId());System.out.println(user);return new DataResult(200,"修改成功");}
}
3 前端使用Ajax请求实现
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><!-- 引入jQuery库 --><script src="/js/jquery-3.4.1.min.js"></script>
</head>
<body><button onclick="sendGet()">GET请求</button><button onclick="sendGetByID()">GET请求指定id</button><button onclick="sendPOST()">POST请求</button><button onclick="sendPUT()">PUT请求</button><button onclick="sendDELETE()">DELETE请求</button><script>function sendGet(){$.ajax({url:'/users',data:{pageNum:3,limit:10},method:"GET",hello:function(res){console.log(res);}})}function sendGetByID(){var id = 10;$.ajax({url:`/users/${id}`,method:"GET",hello:function(res){console.log(res);}})}function sendPOST(){var user = {username:"张三",password:"123",phoneNum:"110001",age:30};$.ajax({url:`/users`,method:"POST",data:JSON.stringify(user),contentType:"application/json",hello:function(res){console.log(res);}})}function sendPUT(){var user = {username:"张三123",password:"456",phoneNum:"111101",age:20};var id = 100;$.ajax({url:`/users/${id}`,method:"PUT",data:JSON.stringify(user),contentType:"application/json",hello:function(res){console.log(res);}})}function sendDELETE(){var id = 100;$.ajax({url:`/users/${id}`,method:"DELETE",hello:function(res){console.log(res);}})}</script>
</body>
</html>
向后端提交数据必须设置请求类型为
contentType:"application/json"
4 配置put请求过滤器(可省)
如果是低版本的SpringMVC(5.1之前),是不支持PUT、DELETE请求的,需要配置过滤器,当前版本无需配置
HttpPutFormContentFilter过滤器配置
<filter><filter-name>httpPutFormContentFilter</filter-name><filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter><filter-mapping><filter-name>httpPutFormContentFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>
5 前端使用表单实现Put和delete
表单默认只支持GET、POST请求,如果使用其他的请求方式,那么都会默认当做是GET请求
配置HiddenHttpMethodFilter过滤器实现Put和delete请求
<filter><filter-name>hiddenHttpMethodFilter</filter-name><filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter><filter-mapping><filter-name>hiddenHttpMethodFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>
前端表单中有两个要求:
请求方式必须为post:
method="post"
在表单中添加隐藏域:
name="_method" value="delete|put"
<form action="请求路径" method="post"><input type="hidden" name="_method" value="delete"><!--其他表单提交信息....--><input type="submit" value="测试put和delete">
</form>