REST 接口开发
Spring Boot 基于 Spring MVC 开发 REST 接口,核心就是 @RestController + 一组请求映射注解。
基本骨架
@RestController
@RequestMapping("/users") // 类级公共路径前缀
public class UserController {
@GetMapping("/{id}") // GET /users/1
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@GetMapping // GET /users?name=xx&page=1
public Page<User> list(@RequestParam(required = false) String name,
@RequestParam(defaultValue = "1") int page) {
return userService.list(name, page);
}
@PostMapping // POST /users(JSON 请求体)
public User create(@RequestBody @Valid UserCreateDTO dto) {
return userService.create(dto);
}
@PutMapping("/{id}") // PUT /users/1(全量更新)
public User update(@PathVariable Long id, @RequestBody UserUpdateDTO dto) {
return userService.update(id, dto);
}
@DeleteMapping("/{id}") // DELETE /users/1
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
请求映射注解
| 注解 | HTTP 方法 | 典型语义 |
|---|---|---|
@GetMapping | GET | 查询 |
@PostMapping | POST | 新增 |
@PutMapping | PUT | 全量更新 |
@PatchMapping | PATCH | 局部更新 |
@DeleteMapping | DELETE | 删除 |
@RequestMapping | 任意 | 通用形式,可指定 method 属性 |
RESTful 设计规范
GET /users 查询用户列表
GET /users/1 查询指定用户
POST /users 新增用户
PUT /users/1 全量更新用户
DELETE /users/1 删除用户
- URL 用名词复数表示资源,不要把动词放进 URL(❌
/getUser)。 - 用 HTTP 方法表达操作语义,用状态码表达结果。
@RestController vs @Controller
| 对比项 | @Controller | @RestController |
|---|---|---|
| 返回值 | 默认视为视图名,交给模板引擎渲染 | 直接序列化为 JSON/XML 写入响应体 |
| 组成 | 单独注解 | @Controller + @ResponseBody |
| 场景 | 服务端渲染页面(Thymeleaf) | 前后端分离的 REST API |
返回文件下载
@GetMapping("/export")
public ResponseEntity<byte[]> export() {
byte[] data = userService.exportExcel();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=users.xlsx")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(data);
}