RESTful风格支持
RESTful是一种软件架构风格,使用URL定位资源,HTTP方法描述操作。
RESTful设计原则
| HTTP方法 | CRUD操作 | 说明 |
|---|---|---|
| GET | Read | 查询资源 |
| POST | Create | 新增资源 |
| PUT | Update | 更新资源 |
| DELETE | Delete | 删除资源 |
| PATCH | Update | 部分更新 |
注解支持
GetMapping
Java
@GetMapping("/users/{id}")
public User getUser(@PathVariable Integer id) {
return userService.findById(id);
}
@GetMapping("/users")
public List<User> listUsers() {
return userService.findAll();
}
PostMapping
Java
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.save(user);
}
PutMapping
Java
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Integer id, @RequestBody User user) {
user.setId(id);
return userService.update(user);
}
DeleteMapping
Java
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Integer id) {
userService.delete(id);
}
完整RESTful接口
Java
@RestController
@RequestMapping("/api/users")
public class UserRestController {
@Autowired
private UserService userService;
@GetMapping
public List<User> list() {
return userService.findAll();
}
@GetMapping("/{id}")
public User get(@PathVariable Integer id) {
return userService.findById(id);
}
@PostMapping
public User create(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User update(@PathVariable Integer id, @RequestBody User user) {
user.setId(id);
return userService.update(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id) {
userService.delete(id);
}
}
RESTful URL规范
| 操作 | URL | HTTP方法 |
|---|---|---|
| 查询列表 | /users | GET |
| 查询单个 | /users/{id} | GET |
| 新增 | /users | POST |
| 修改 | /users/{id} | PUT |
| 删除 | /users/{id} | DELETE |
RESTful接口应返回JSON数据,使用@RestController或@ResponseBody注解。
要点总结
- RESTful:URL定位资源,HTTP方法描述操作
- 使用@GetMapping等衍生注解简化代码
- @PathVariable绑定路径参数
- @RestController = @Controller + @ResponseBody
📝 发现内容有误?点击此处直接编辑