RESTful风格参数
RESTful风格将参数融入URL路径,结合HTTP方法实现对资源的CRUD操作。
RESTful规范
| HTTP方法 | 操作 | URL示例 | 说明 |
|---|---|---|---|
| GET | 查询 | /user/1 | 查询ID为1的用户 |
| POST | 新增 | /user | 新增用户 |
| PUT | 修改 | /user/1 | 修改ID为1的用户 |
| DELETE | 删除 | /user/1 | 删除ID为1的用户 |
路径参数绑定
单个参数
Java
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable Integer id) {
return userService.findById(id);
}
}
请求:GET /api/user/100
多个参数
Java
@GetMapping("/category/{cid}/product/{pid}")
public Product getProduct(
@PathVariable("cid") Integer categoryId,
@PathVariable("pid") Integer productId
) {
return productService.findById(categoryId, productId);
}
请求:GET /api/category/10/product/100
RESTful接口示例
Java
@RestController
@RequestMapping("/users")
public class UserRestController {
@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);
}
}
URL风格对比
| 风格 | URL | 特点 |
|---|---|---|
| 传统 | /user?id=1 | 参数在query string |
| RESTful | /user/1 | 参数在路径中 |
RESTful风格URL更简洁,语义更清晰,符合资源定位的设计理念。
要点总结
- RESTful使用路径传递参数,结合HTTP方法表示操作
- @PathVariable绑定路径参数
- GET查询、POST新增、PUT修改、DELETE删除
- URL结构:
/资源名/{参数}
📝 发现内容有误?点击此处直接编辑