当前位置: 首页 > news >正文

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

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等组件构建完整的企业级应用。

相关文章:

  • 本地部署DeepSeek后的调用与删除全攻略
  • 计算机网络知识速记:TCP 与 UDP
  • 在 debian 12 上安装 mysqlclient 报错
  • Gemini Thinks Faster
  • 10 . Docker 中的 DockerFile 解析(各种指令说明)
  • 安装mysql5.7报错 mysqld.exe-系统错误 由于找不到MSVCP120.dll,无法继续执行代码。重新安装程序可能 会解决此问题。 确定
  • /etc/sysctl.conf——系统的配置文件
  • #define宏与编译时定义的本质对决:从const常量到typedef的类型安全演进
  • 第二章:基础概念精讲 - 第一节 - Tailwind CSS 响应式设计系统
  • Okay, But Please Don’t Stop Talking
  • Flutter编译问题记录
  • [Windows] 微软常用运行库合集版 2025.02.12
  • 【黑马点评优化】1-使用JWT登录认证+redis实现自动续期
  • Flutter 中的生命周期
  • 理解 WebGPU 中的 GPUQueue:GPU 的命令队列
  • 针对Prompt优化的深入分析
  • 储能能量管理监测系统在储能物联网中的应用优势
  • 【java】List<String> fruits = new ArrayList<>(); 这一句是什么
  • 机器视觉3D缺陷检测痛点
  • P9584 「MXOI Round 1」城市
  • 首届巴塞尔艺术奖公布:大卫·哈蒙斯、曹斐等36人获奖
  • 音著协宣布胜诉,虎牙公司终审被判侵权
  • 永久基本农田竟沦为垃圾场,湖南湘潭回应:全面启动专项整治
  • 4月份国民经济顶住压力稳定增长
  • 复旦一校友捐赠1亿元,却不留名
  • 种植耐旱作物、启动备用水源,甘肃各地多举措应对旱情