全部学科
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结构:/资源名/{参数}

📝 发现内容有误?点击此处直接编辑

← 上一篇 PathVariable注解
下一篇 → RESTful风格支持
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库