[Spring Boot]应用Restful风格进行Web请求

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都是一样的(当然实际写法后面可以分别带不同参数):

http://localhost:8080/user

那怎么区分增删改查这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请求了。

请求页面:
这里写图片描述

结果页面:
这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值