一、什么是RESTful
RESTful 不是一种技术,也不是一种规范,而是一种架构(设计)风格。
参考文章:什么是REST
REST(Representational State Transfer)表述性状态转移。
7个HTTP方法:GET/POST/PUT/DELETE/PATCH/HEAD/OPTIONS
RESTful(Representational State Transfer)架构风格,是一个Web自身的架构风格,底层主要基于HTTP协议。
参考博客:Springboot实现Restful服务,基于HTTP/JSON传输
二、Springboot 实现 Restful 服务
Springboot 实现 Restful 服务,基于 HTTP / JSON 传输,适用于前后端分离。
1. 常用请求方式
根据ID获取用户信息(GET):
http://localhost:8080/rest/user/1
获取用户列表(GET):
http://localhost:8080/rest/user
新增用户(POST):
http://localhost:8080/rest/user
-- 请求参数
{
"id":2,
"name":"lisi",
"age":34
}
更新用户信息(PUT):
http://localhost:8080/rest/user
-- 请求参数
{
"id":2,
"name":"lisi",
"age":37
}
删除用户(DELETE):
http://localhost:8080/rest/user/2
2. 使用Postman测试的时候,可以选择请求的方式
3. 创建RESTful Api
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/rest/user/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable("id") Long id) {
return userService.getUserById(id);
}
@RequestMapping(value = "/rest/user", method = RequestMethod.GET)
public List<User> getUsers() {
return userService.getAllUser();
}
@RequestMapping(value = "/rest/user", method = RequestMethod.POST)
public void createUser(@RequestBody User user) {
userService.createUser(user);
}
@RequestMapping(value = "/rest/user", method = RequestMethod.PUT)
public void updateUser(@RequestBody User user) {
userService.updateUser(user);
}
@RequestMapping(value = "/rest/user/{id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("id") Long id) {
userService.deleteUser(id);
}
}
相关注解介绍:
@PathVariable:将请求URL中的参数({id})绑定到方法的参数上
@RequestBody:将json格式的请求数据绑定到POJO类型的方法参数上
@RequestMapping 注解属性:
method:指定方法接收的请求类型,POST/GET/DELETE/PUT 等。不指定则默认全部都可以,具体请求方式由请求方决定。value:指定实际的请求地址。
consumes:指定方法接收的请求参数类型,对应请求体中的请求头[Content-Type]指定的类型。
produces:指定方法返回内容的类型,例如 produces="application/json" 等价于在方法上添加 @ResponseBody 注解。