8、《5分钟构建RESTful API:Spring Boot Web开发入门》

发布于:2025-02-14 ⋅ 阅读:(36) ⋅ 点赞:(0)

5分钟构建RESTful API:Spring Boot Web开发入门

一、RESTful API核心认知

REST(Representational State Transfer)通过HTTP协议实现资源操作,其核心特征包括:

  1. 资源以URI标识(/api/users
  2. 通过HTTP方法表达操作语义(GET/POST/PUT/DELETE)
  3. 无状态通信
  4. 返回标准状态码(200/404/500等)

二、项目快速搭建

使用Spring Initializr创建项目:

<!-- pom.xml核心依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
</dependency>

三、@RestController深度实践

3.1 基础控制器

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

    // 模拟内存数据库
    private Map<Long, User> users = new ConcurrentHashMap<>();
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }
}

3.2 完整CRUD示例

@PostMapping
public ResponseEntity<Void> createUser(@RequestBody User user) {
    users.put(user.getId(), user);
    return ResponseEntity.created(URI.create("/users/"+user.getId())).build();
}

@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
    if (!users.containsKey(id)) {
        return ResponseEntity.notFound().build();
    }
    users.put(id, user);
    return ResponseEntity.ok(user);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
    users.remove(id);
    return ResponseEntity.noContent().build();
}

四、统一响应封装

4.1 响应体标准化

@Data
public class ApiResponse<T> {
    private int code;       // 业务状态码
    private String message; // 提示信息
    private T data;         // 业务数据
    private long timestamp; // 响应时间戳

    public ApiResponse(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.timestamp = System.currentTimeMillis();
    }

    // 快速构建成功响应
    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "Success", data);
    }
}

4.2 控制器改造示例

@GetMapping("/{id}")
    public ResponseEntity<ApiResponse<User>> getUser(@PathVariable Integer id) {
        User user = users.get(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(404, "User NOT exists", null));
        }
        return ResponseEntity.status(HttpStatus.OK)
                .body(ApiResponse.success(user));
    }

五、全局异常处理

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleGlobalException(Exception ex) {
        return new ApiResponse<>(500, "Server Error: " + ex.getMessage(), null);
    }
}

六、HTTP状态码精准控制

6.1 状态码使用规范

状态码 使用场景
200 OK 常规成功请求
201 Created 资源创建成功
204 No Content 成功无返回体
400 Bad Request 请求参数错误
401 Unauthorized 未认证
403 Forbidden 无权限访问
404 Not Found 资源不存在
500 Internal Server Error 服务器内部错误

6.2 状态码实战应用

@PostMapping
public ResponseEntity<ApiResponse<User>> createUser(@Valid @RequestBody User user) {
    if (users.containsKey(user.getId())) {
        return ResponseEntity.status(HttpStatus.CONFLICT)
               .body(new ApiResponse<>(409, "User already exists", null));
    }
    users.put(user.getId(), user);
    return ResponseEntity.status(HttpStatus.CREATED)
           .body(ApiResponse.success(user));
}

项目结构参考:

src/main/java
└── com.example.demo
    ├── config        # 配置类
    ├── controller    # 控制器层
    ├── exception     # 自定义异常
    ├── model         # 数据模型
    └── response      # 响应封装
    └── Application   # 启动类

本文完整源码:

通过标准化响应封装、精确的状态码控制和全局异常处理,开发者可以快速构建出符合RESTful规范的健壮API。这种设计模式不仅提升接口的可维护性,更能显著降低前后端联调成本。后续可结合Spring Data JPA、Redis等组件构建完整的企业级应用。