Restful风格越来越流行,不研究都不好意思说自己是做Web开发的。存在即合理,那么多人用这种风格开发Web应用,就证明这种风格是能解决一些问题的。个人认为,应用Restful风格最大的好处就是能统一接口的写法。比如说,一般系统都有用户管理模块,通过发送Web请求,对数据库里的User表进行增删改查(CRUD)操作。那么问题就来了,有些人喜欢这么定义:
http://localhost:8080/getUser
http://localhost:8080/addUser
http://localhost:8080/updateUser
http://localhost:8080/deleteUser
有的又喜欢定义为:
http://localhost:8080/queryUser
http://localhost:8080/insertUser
http://localhost:8080/refreshUser
http://localhost:8080/removeUser
这导致每次开发不同的系统,接口都是五花八门,什么风格都有。有什么办法能让程序员不管开发什么系统,这种类似的增删改查操作接口都能写成一样呢?那就是都使用Restful风格。Restful风格下,增删改查的Web请求URL都是一样的(当然实际写法后面可以分别带不同参数):
那怎么区分增删改查这4种操作呢?前辈们很聪明地借用了提交form时用的Get、Post方法,用Get请求表示查询操作,用Post请求表示新增操作。剩下两种操作,更新和删除怎么表示呢?前辈们又很聪明地在form里增加了两个参数PUT和DELETE,这下系统就能识别全部四种操作了。具体写法是这样的:
<form action="/user" method="get">
Get请求:<input type="submit" value="get">
</form>
<form action="/user/1" method="post">
Post请求:<input type="submit" value="post">
</form>
<form action="/user/1" method="post">
<input type="hidden" name="_method" value="PUT">
Put请求:<input type="submit" value="put">
</form>
<form action="/user/1" method="post">
<input type="hidden" name="_method" value="DELETE">
Delete请求:<input type="submit" value="delete">
</form>
页面请求写好了,Spring Boot后台接收代码如下:
@GetMapping("/user")
String getUser() {
return "get-method called!";
}
@PostMapping("/user/{id}")
String saveUser(@PathVariable("id") Integer id) {
return "post-method called!(id=" + id + ")";
}
@PutMapping("/user/{id}")
String updateUser(@PathVariable("id") Integer id) {
return "put-method called!(id=" + id + ")";
}
@DeleteMapping("/user/{id}")
String deleteUser(@PathVariable("id") Integer id) {
return "delete-method called!(id=" + id + ")";
}
OK,把Spring Boot应用启动,通过点击页面上的按钮,
就能发送对应的GET/POST/PUT/DELETE请求了。
请求页面:
结果页面: