2026/10/14 16:32:56

SpringBoot 入门:PostMan/Apifox 接口测试实战

SpringBoot 入门:PostMan/Apifox 接口测试实战 一、项目简介本项目是一个 SpringBoot 入门示例实现支持 HTTP GET、POST、PUT、DELETE 四种请求方法的后端接口用于管理 name-age姓名-年龄数据。接口使用内存中的 HashMap 存储数据初始预置姓名 WZH、年龄 20。技术栈组件版本Spring Boot4.1.1Java17实际运行使用 JDK 25构建工具Maven接口测试工具Apifox / Postman二、核心代码2.1 启动类 L05Application.javapackage com.example.l05; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; SpringBootApplication public class L05Application { public static void main(String[] args) { SpringApplication.run(L05Application.class, args); } }2.2 控制器 HelloController.javapackage com.example.l05.controller; import org.springframework.web.bind.annotation.*; import java.util.HashMap; RestController public class HelloController { private static HashMapString, Integer nameAges new HashMap(); static { nameAges.put(WZH, 20); } GetMapping(/hello) public String hello() { return Hello SpringBoot: nameAges.toString(); } PostMapping(/hello) public String helloPost(String name, int age) { nameAges.put(name, age); return add name: name , age age; } PutMapping(/hello) public String helloPut(String name, int age) { nameAges.replace(name, age); return update name: name , age age; } DeleteMapping(/hello/{name}) public String helloDel(PathVariable String name) { nameAges.remove(name); return delete name: name; } }2.3 代码说明注解作用RestController标识 REST 控制器返回内容直接作为响应体GetMapping / PostMapping / PutMapping / DeleteMapping映射对应 HTTP 方法到处理方法PathVariable从 URL 路径中提取参数三、接口文档Base URLhttp://localhost:8080数据格式为表单参数返回纯文本。3.1 GET - 查询所有数据GET http://localhost:8080/hello响应示例Hello SpringBoot: {WZH20}3.2 POST - 新增数据POST http://localhost:8080/hello Content-Type: application/x-www-form-urlencoded nameTomage22响应示例add name: Tom, age 223.3 PUT - 修改数据PUT http://localhost:8080/hello Content-Type: application/x-www-form-urlencoded nameWZHage21响应示例update name: WZH, age 213.4 DELETE - 删除数据DELETE http://localhost:8080/hello/Tom响应示例delete name: Tom四、Apifox 测试步骤4.1 创建项目与环境打开 Apifox新建项目在「环境管理」中新建环境前置 URL 填 http://localhost:8080。4.2 推荐测试顺序顺序方法路径Body 参数预期返回①GET/hello无Hello SpringBoot: {WZH20}②POST/hellonameTom, age22add name: Tom, age 22③PUT/hellonameWZH, age21update name: WZH, age 21④DELETE/hello/Tom无delete name: Tom4.3 操作细节GET方法选 GETURL 填 /hello直接发送。POST方法选 POSTBody 选 x-www-form-urlencoded添加参数 nameTom、age22。PUT方法选 PUTBody 选 x-www-form-urlencoded添加参数 nameWZH、age21。DELETE方法选 DELETEURL 填 /hello/Tom不需要 Body。五、项目运行5.1 启动命令# Windows mvnw.cmd spring-boot:run Linux/Mac ./mvnw spring-boot:run5.2 启动成功标志控制台出现 Tomcat started on port 8080 即表示启动成功。Spring Boot 4.1.1 需要 Java 17 及以上版本若本机默认 JDK 为 Java 8需临时切换 JAVA_HOME。六、小结本项目演示了 SpringBoot 入门用法使用 RestController 构建 RESTful 接口通过四种 Mapping 注解处理 HTTP 方法使用 HashMap 实现简单 CRUD并用 Apifox 完成接口测试。后续可扩展接入 MySQL 持久化、引入 Service/DAO 分层、添加参数校验和统一异常处理。