全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-18 6 分钟 ✍️ juanwangdev

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结构:/资源名/{参数}
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 RequestParam注解
下一篇 → PathVariable注解
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码