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

news/2025/2/19 12:10:57/

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


http://www.ppmy.cn/news/1572425.html

相关文章

【webview Android】视频获取首帧为封面

文章目录 需求分析获得首帧其他方法 需求分析 客户端中h5上传视频&#xff0c;视频封面默认首帧。 遇到问题&#xff1a;原生的video现象如下 IOS会在加载好后显示首帧&#xff08;没加载好显示黑屏&#xff0c;符合预期&#xff09;Android加载好后默认封面为一个奇怪的占位…

IPv4 协议和TCP 协议的区别

&#x1f4e1; IPv4 协议 vs TCP 协议&#xff1a;核心区别 维度IPv4 协议TCP 协议OSI 层级网络层&#xff08;Layer 3&#xff09;传输层&#xff08;Layer 4&#xff09;主要作用负责数据包的寻址和路由&#xff08;确定数据去哪里&#xff09;负责可靠的数据传输和连接管理…

SpringAI集成DeepSeek实战

SpringAI集成DeepSeek实战教程 引言 Spring AI作为Spring生态系统中的新成员&#xff0c;为开发者提供了便捷的AI集成方案。本文将详细介绍如何在Spring项目中集成DeepSeek模型&#xff0c;实现智能对话等功能。 环境准备 在开始之前&#xff0c;请确保您的开发环境满足以下要…

5. Docker 本地镜像发布到阿里云

5. Docker 本地镜像发布到阿里云 文章目录 5. Docker 本地镜像发布到阿里云1. 本地镜像发布到阿里云流程最后&#xff1a; 1. 本地镜像发布到阿里云流程 镜像的生成方法&#xff1a; 基于当前容器创建一个新的镜像&#xff0c;新功能增强 docker commit [OPTIONS] 容器ID [REP…

使用docker compose启动postgres并设置时区

设置PostGres时区 方法 1: 使用 POSTGRES_INITDB_ARGS 设置时区方法 2: 使用初始化脚本设置时区创建 init-user-db.sql更新 docker-compose.yml 启动服务 要在启动 PostgreSQL 数据库时设置时区&#xff0c;可以通过在 docker-compose.yml 文件中添加环境变量或通过配置文件来实…

独立站赋能反向海淘:跨境代购系统的用户体验与支付解决方案

随着全球化的推进以及消费者对海外商品多样化需求的增长&#xff0c;独立站赋能的反向海淘模式愈发火热&#xff0c;其中跨境代购系统的用户体验与支付解决方案起着关键作用。 一、跨境代购系统的用户体验 界面友好性 独立站的页面设计需要简洁、直观&#xff0c;方便用户快速…

【Maven】多module项目优雅的实现pom依赖管理

【Maven】多module项目优雅的实现pom依赖管理 【一】方案设计原则【二】项目结构示例【三】实现思路【1】可能的问题点&#xff1a;【2】解决方案的思路&#xff1a;【3】需要注意的地方&#xff1a;【4】可能的错误&#xff1a; 【四】实现案例【1】父POM设计&#xff08;pare…

格式工厂 FormatFactory v5.18.便携版 ——多功能媒体文件转换工具

格式工厂 FormatFactory v5.18.便携版 ——多功能媒体文件转换工具 功能&#xff1a;视频 音频 图片 文档PDF格式 各种转换&#xff0c;同格式调整压缩比例&#xff0c;调整大小 特色&#xff1a;果风图标 好看; 支持多任务队列&#xff0c;完成自动关机 下载地址&#xff1…