Restful风格
(1)请求映射
| 注解 | 作用 | 代码示例 |
|---|---|---|
@RestController | 声明为Restful控制器,等价于 @Controller + @ResponseBody | @RestController public class UserController { ... } |
@RequestMapping | 通用请求映射(可指定路径、方法类型) | @RequestMapping("/api") |
@GetMapping | GET请求专用(替代 @RequestMapping(method=GET)) | @GetMapping("/users/{id}") |
@PostMapping | POST请求专用(创建资源) | @PostMapping("/users") |
@PutMapping | PUT请求专用(全量更新资源) | @PutMapping("/users/{id}") |
@DeleteMapping | DELETE请求专用(删除资源) | @DeleteMapping("/users/{id}") |
@PatchMapping | PATCH请求专用(部分更新资源) | @PatchMapping("/users/{id}/email") |
(2)参数处理
@PathVariable 常用于 RESTful 风格的 URL 中获取资源标识符,如 ID、名称等。
@RequestBody 常用于处理 POST、PUT 等请求方法,接收请求体中的数据。
| 注解 | 作用 | 数据来源 |
|---|---|---|
@RequestBody | 绑定请求体 | HTTP Body(如 JSON) |
@PathVariable | 绑定 URL 模板变量,从URL路径中获取参数 | URL 路径(如 /user/{id}) |
@RequestParam | 绑定查询参数,从URL查询参数中取值 | URL 参数(如 /path?name=Alice) |
@ModelAttribute | 绑定表单数据 | 表单提交或 URL 参数 |
(3)响应处理
| 注解 | 作用 | 代码示例 |
|---|---|---|
@ResponseBody | 将方法返回值直接作为响应体(默认JSON) | @ResponseBody public User getUser() { ... } |
@ResponseStatus | 自定义HTTP响应状态码 | @ResponseStatus(HttpStatus.CREATED) |
1822

被折叠的 条评论
为什么被折叠?



