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

编写第一个RESTful接口

Spring Boot 简化了 RESTful API 的开发。

@RestController

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

    // 自动处理HTTP请求,返回JSON
}

@RestController = @Controller + @ResponseBody

RESTful CRUD示例

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

    // GET - 查询
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }

    // GET - 列表
    @GetMapping
    public List<User> listUsers() {
        return userService.findAll();
    }

    // POST - 创建
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }

    // PUT - 更新
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.update(id, user);
    }

    // DELETE - 删除
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.delete(id);
    }
}

HTTP方法注解

注解HTTP方法用途
@GetMappingGET查询资源
@PostMappingPOST创建资源
@PutMappingPUT更新资源
@DeleteMappingDELETE删除资源
@PatchMappingPATCH局部更新

参数注解

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

    // 路径参数
    @GetMapping("/users/{id}")
    public User getById(@PathVariable Long id) {
        // /api/users/123 → id=123
    }

    // 查询参数
    @GetMapping("/users")
    public List<User> list(@RequestParam String name) {
        // /api/users?name=test → name=test
    }

    // 请求体
    @PostMapping("/users")
    public User create(@RequestBody User user) {
        // JSON → User对象
    }

    // 多个参数
    @GetMapping("/search")
    public Result search(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        // /api/search?page=1&size=20
    }
}
注解来源
@PathVariableURL路径
@RequestParamURL查询参数
@RequestBody请求体JSON

完整示例

实体类

Java
@Data
public class User {
    private Long id;
    private String name;
    private String email;
}

控制器

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

    private List<User> users = new ArrayList<>();

    @GetMapping("/{id}")
    public User get(@PathVariable Long id) {
        return users.stream()
            .filter(u -> u.getId().equals(id))
            .findFirst()
            .orElse(null);
    }

    @GetMapping
    public List<User> list() {
        return users;
    }

    @PostMapping
    public User create(@RequestBody User user) {
        user.setId(System.currentTimeMillis());
        users.add(user);
        return user;
    }

    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        users.stream()
            .filter(u -> u.getId().equals(id))
            .findFirst()
            .ifPresent(u -> {
                u.setName(user.getName());
                u.setEmail(user.getEmail());
            });
        return user;
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        users.removeIf(u -> u.getId().equals(id));
    }
}

测试接口

Bash
# GET查询
curl http://localhost:8080/api/users/1

# GET列表
curl http://localhost:8080/api/users

# POST创建
curl -X POST http://localhost:8080/api/users \
    -H "Content-Type: application/json" \
    -d '{"name":"张三","email":"test@example.com"}'

# PUT更新
curl -X PUT http://localhost:8080/api/users/1 \
    -H "Content-Type: application/json" \
    -d '{"name":"李四","email":"new@example.com"}'

# DELETE删除
curl -X DELETE http://localhost:8080/api/users/1

响应格式

JSON
// 单个对象
{
    "id": 1,
    "name": "张三",
    "email": "test@example.com"
}

// 列表
[
    {"id": 1, "name": "张三"},
    {"id": 2, "name": "李四"}
]

启动测试

Bash
# 启动项目
mvn spring-boot:run

# 或IDEA运行MyApplication.main()

# 访问测试
curl http://localhost:8080/api/users

要点总结

  • @RestController返回JSON
  • @GetMapping/@PostMapping等映射HTTP方法
  • @PathVariable取路径参数
  • @RequestBody绑定JSON请求体
  • RESTful遵循资源+动作设计

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

← 上一篇 使用Spring Initializr创建项目
下一篇 → SpringBoot多环境配置dev与prod
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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