一、新建SpringBoot项目文件
二、项目结构介绍
三、编写代码
(一)主程序介绍
(二)编写响应HTTP 请求URI 为/hello 的接口和逻辑
1、新建项目文件
2、实例代码
package com.example.springbootproject1.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello SpringBoot";
}
}
3、代码解释
(三)编译代码、构建项目
(四)执行SpringBoot 程序
1、运行并查看结果
监听8080 端口成功,表名HTTP 后端服务器启动成功,能够提供服务
HTTP Client 客户端[浏览器或者Postman]可以通过localhost:8080/hello 来访问对应接口服务
四、测试SpringBoot 后端接口
(一)浏览器测试
输入URL,按下回车,向后端发起HTTP GET 请求
后端返回字符串,显示在前端浏览器
(二)Postman 测试
1、Postman简述
因为浏览器只能发起HTTP GET 请求,测试方式有限
所以使用Postman测试POST、PUT、DELETE
Postman下载https://www.getpostman.com/downloads/
Postman界面
2、后端程序添加支持/hello的POST、PUT和DELELTE请求
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello SpringBoot: " + nameAges.toString();
}
private static HashMap<String, Integer> nameAges = new HashMap<>();
@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;
}
}
3、GET请求
4、POST请求
5、PUT请求
更新后,查询看一下数据是否正常
6、DELETE请求
更新后,查询看一下数据是否符合预期