Restful 风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
在Restful风格中,用同一个请求接口(URL)而用不同的请求方式,这就避免了编写多个不同的URL,通过请求的方式也更容易区分出每个方法的功能。
客户端使用GET、POST、PUT、DELETE 4个表示操作方式的动词对服务端资源进行操作:
- GET用来获取资源,
- POST用来新建资源(也可以用于更新资源),
- PUT用来更新资源,
- DELETE用来删除资源

@GetMapping("/hello/{name}")
public String hello(@PathVariable("name") String name) {
return "获取到的name是:" + name;
}
localhost:8080/hello/tom
@GetMapping("/hello")
public String hello(String name) {
return "获取到的name是:" + name;
}
localhost:8080/hello?name=tom
注意:多个参数之间使用 & 连接
用于拼接在路径后边的参数名称和接收名称不一致的时候使用
@GetMapping("/hello")
public String hello(@RequestParam("namename") String name) {
return "获取到的name是:" + name;
}
localhost:8080/hello?namename=tom
@GetMapping("/hello")
public String hello(@RequestParam(required = false) String name) {
return "获取到的name是:" + name;
}
@GetMapping("/hello")
public String hello(@RequestParam(defaultValue = "unnamed") String name) {
return "获取到的name是:" + name;
}
localhost:8080/hello
@GetMapping("/hello")
public String hello(@RequestParam Map<String, Object> params) {
return "name:" + params.get("name") + ",age:" + params.get("age");
}
localhost:8080/hello?name=tom&age=18
@GetMapping("/hello")
public String hello(User user) {
return "name:" + user.getName() + ",age:" + user.getAge();
}
localhost:8080/hello?name=tom&age=jerry
其中,name 和 age 是实体对应的属性,必须要保证其一致性,才能接收到参数。
//用户注册
@PostMapping("/reg")
public R register(@RequestBody User user){
return userService.insert(user);
}
put 方式
//用户更新
@PutMapping
public R<?> modify(@RequestBody User user){
return userService.update(user);
}
delete 方式
//删除用户
@DeleteMapping("/{id}")
public R<?> remove(@PathVariable Long id){
return userService.delete(id);
}