全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 7 分钟 ✍️ juanwangdev

RESTful风格支持

RESTful是一种软件架构风格,使用URL定位资源,HTTP方法描述操作。

RESTful设计原则

HTTP方法CRUD操作说明
GETRead查询资源
POSTCreate新增资源
PUTUpdate更新资源
DELETEDelete删除资源
PATCHUpdate部分更新

注解支持

GetMapping

Java
@GetMapping("/users/{id}")
public User getUser(@PathVariable Integer id) {
    return userService.findById(id);
}

@GetMapping("/users")
public List<User> listUsers() {
    return userService.findAll();
}

PostMapping

Java
@PostMapping("/users")
public User createUser(@RequestBody User user) {
    return userService.save(user);
}

PutMapping

Java
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Integer id, @RequestBody User user) {
    user.setId(id);
    return userService.update(user);
}

DeleteMapping

Java
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Integer id) {
    userService.delete(id);
}

完整RESTful接口

Java
@RestController
@RequestMapping("/api/users")
public class UserRestController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> list() {
        return userService.findAll();
    }

    @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);
    }
}

RESTful URL规范

操作URLHTTP方法
查询列表/usersGET
查询单个/users/{id}GET
新增/usersPOST
修改/users/{id}PUT
删除/users/{id}DELETE

RESTful接口应返回JSON数据,使用@RestController或@ResponseBody注解。

要点总结

  • RESTful:URL定位资源,HTTP方法描述操作
  • 使用@GetMapping等衍生注解简化代码
  • @PathVariable绑定路径参数
  • @RestController = @Controller + @ResponseBody

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

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

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

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