首先来看看传统的风格资源描述形式
http://localhost/user/getById?id=2(获得id为2的User信息)http://localhost/user/saveUser(添加并保存一个User信息至数据库)
然后看看同样的功能REST是什么样的?
http://localhost/user/user/2(获得id为2的User信息)
http://localhost/user/user (添加并保存一个User信息至数据库)
可以发现REST风格的几个优点:
-
可以隐藏资源的访问行为,无法通过地址得知资源是什么操作
-
可以简化书写
肯定有人会问那怎么规定这个地址具体是什么操作呢?
那是因为按照REST风格访问资源时使用行为动作区分资源进行了什么操作。看下图
ok,现在来测试一下。
在Springboot中创建一个控制类,是用GET传递参数
- @RequestParam:常用于接收url地址url地址传参或表单传参
- @RequestBody:用于接收json数据
- @PathVariable:用于接收路径参数,使用{参数名称}描述路径参数
package com.example.controller;
import org.springframework.web.bind.annotation.*;
//Rest模式
@RestController
public class BookController {
@RequestMapping(value = "/books/{id}", method = RequestMethod.GET)
@ResponseBody
public String getById(@PathVariable Integer id){
System.out.println(id);
return String.valueOf(id);
}
}
启动引导类
使用postman测试
使用GET方式,输入 http://localhost:8080/books/23http://localhost:8080/books/23
测试成功。其他的方式大家可以自己尝试。