
- Spring Boot 教程
- Spring Boot - 首頁
- Spring Boot - 簡介
- Spring Boot - 快速入門
- Spring Boot - 引導
- Spring Tool Suite
- Spring Boot - Tomcat 部署
- Spring Boot - 構建系統
- Spring Boot - 程式碼結構
- Spring Bean & 依賴注入
- Spring Boot - 執行器
- Spring Boot - 啟動器
- Spring Boot - 應用屬性
- Spring Boot - 配置
- Spring Boot - 註解
- Spring Boot - 日誌
- 構建 RESTful Web 服務
- Spring Boot - 異常處理
- Spring Boot - 攔截器
- Spring Boot - Servlet 過濾器
- Spring Boot - Tomcat 埠號
- Spring Boot - Rest 模板
- Spring Boot - 檔案處理
- Spring Boot - 服務元件
- Spring Boot - Thymeleaf
- 消費 RESTful Web 服務
- Spring Boot - CORS 支援
- Spring Boot - 國際化
- Spring Boot - 排程
- Spring Boot - 啟用 HTTPS
- Spring Boot - Eureka Server
- 使用 Eureka 進行服務註冊
- 閘道器代理伺服器和路由
- Spring Cloud 配置伺服器
- Spring Cloud 配置客戶端
- Spring Boot - Actuator
- Spring Boot - Admin 伺服器
- Spring Boot - Admin 客戶端
- Spring Boot - 啟用 Swagger2
- Spring Boot - 使用 SpringDoc OpenAPI
- Spring Boot - 建立 Docker 映象
- 跟蹤微服務日誌
- Spring Boot - Flyway 資料庫
- Spring Boot - 傳送郵件
- Spring Boot - Hystrix
- Spring Boot - Web Socket
- Spring Boot - 批處理服務
- Spring Boot - Apache Kafka
- Spring Boot - Twilio
- Spring Boot - 單元測試用例
- Rest Controller 單元測試
- Spring Boot - 資料庫處理
- 保護 Web 應用程式
- Spring Boot - 使用 JWT 的 OAuth2
- Spring Boot - Google Cloud Platform
- Spring Boot - Google OAuth2 登入
- Spring Boot 資源
- Spring Boot - 快速指南
- Spring Boot - 有用資源
- Spring Boot - 討論
Spring Boot - 構建 RESTful Web 服務
Spring Boot 為企業應用程式構建 RESTful Web 服務提供了非常好的支援。本章將詳細解釋如何使用 Spring Boot 構建 RESTful Web 服務。
注意 - 為了構建 RESTful Web 服務,我們需要將 Spring Boot Starter Web 依賴項新增到構建配置檔案中。
如果您是 Maven 使用者,請使用以下程式碼將以下依賴項新增到您的 pom.xml 檔案中:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
如果您是 Gradle 使用者,請使用以下程式碼將以下依賴項新增到您的 build.gradle 檔案中。
compile('org.springframework.boot:spring-boot-starter-web')
完整的構建配置檔案 Maven 構建 – pom.xml 程式碼如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
完整的構建配置檔案 Gradle 構建 – build.gradle 程式碼如下:
buildscript { ext { springBootVersion = '3.3.3' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 21 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') }
在您繼續構建 RESTful Web 服務之前,建議您瞭解以下註解:
Rest Controller
@RestController 註解用於定義 RESTful Web 服務。它提供 JSON、XML 和自定義響應。其語法如下:
@RestController public class ProductServiceController { }
Request Mapping
@RequestMapping 註解用於定義訪問 REST 端點的請求 URI。我們可以定義請求方法來消費和生成物件。預設請求方法為 GET。
@RequestMapping(value = "/products") public ResponseEntity<Object> getProducts() { }
Request Body
@RequestBody 註解用於定義請求正文內容型別。
public ResponseEntity<Object> createProduct(@RequestBody Product product) { }
Path Variable
@PathVariable 註解用於定義自定義或動態請求 URI。請求 URI 中的路徑變數定義為花括號 {},如下所示:
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) { }
Request Parameter
@RequestParam 註解用於從請求 URL 讀取請求引數。預設情況下,它是一個必需引數。我們還可以為請求引數設定預設值,如下所示:
public ResponseEntity<Object> getProduct( @RequestParam(value = "name", required = false, defaultValue = "honey") String name) { }
GET API
預設的 HTTP 請求方法是 GET。此方法不需要任何請求正文。您可以傳送請求引數和路徑變數來定義自定義或動態 URL。
以下程式碼示例顯示瞭如何定義 HTTP GET 請求方法。在此示例中,我們使用 HashMap 儲存 Product。請注意,我們使用 POJO 類作為要儲存的產品。
這裡,請求 URI 為 /products,它將從 HashMap 儲存庫返回產品列表。以下給出了包含 GET 方法 REST 端點的控制器類檔案。
... @RestController public class ProductServiceController { ... @GetMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } }
POST API
HTTP POST 請求用於建立資源。此方法包含請求正文。我們可以傳送請求引數和路徑變數來定義自定義或動態 URL。
以下示例顯示瞭如何定義 HTTP POST 請求方法。在此示例中,我們使用 HashMap 儲存 Product,其中 Product 是一個 POJO 類。
這裡,請求 URI 為 /products,它將在將產品儲存到 HashMap 儲存庫後返回字串。
... @RestController public class ProductServiceController { ... @PostMapping(value = "/products") public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } }
PUT API
HTTP PUT 請求用於更新現有資源。此方法包含請求正文。我們可以傳送請求引數和路徑變數來定義自定義或動態 URL。
以下示例顯示瞭如何定義 HTTP PUT 請求方法。在此示例中,我們使用 HashMap 更新現有 Product,其中 Product 是一個 POJO 類。
這裡的請求 URI 為 /products/{id},它將在將產品新增到 HashMap 儲存庫後返回字串。請注意,我們使用了路徑變數 {id},它定義了需要更新的產品 ID。
... @RestController public class ProductServiceController { ... @PutMapping(value = "/products/{id}") public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } }
DELETE API
HTTP Delete 請求用於刪除現有資源。此方法不包含任何請求正文。我們可以傳送請求引數和路徑變數來定義自定義或動態 URL。
以下示例顯示瞭如何定義 HTTP DELETE 請求方法。在此示例中,我們使用 HashMap 刪除現有產品,它是一個 POJO 類。
請求 URI 為 /products/{id},它將在從 HashMap 儲存庫刪除產品後返回字串。我們使用了路徑變數 {id},它定義了需要刪除的產品 ID。
... @RestController public class ProductServiceController { ... @DeleteMapping(value = "/products/{id}") public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } }
本節提供了完整的原始碼集。請觀察以下程式碼及其各自的功能:
Spring Boot 主應用程式類。
DemoApplication.java
package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
POJO 類
Product.java
package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Rest Controller 類
ProductServiceController.java
package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @DeleteMapping(value = "/products/{id}") public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } @PutMapping(value = "/products/{id}") public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } @PostMapping(value = "/products") public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } @GetMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } }
編譯和執行
您可以建立一個可執行的 JAR 檔案,並使用以下 Maven 或 Gradle 命令執行 Spring Boot 應用程式,如下所示:
對於 Maven,使用以下命令:
mvn clean install
“BUILD SUCCESS” 後,您可以在 target 目錄下找到 JAR 檔案。
對於 Gradle,使用以下命令:
gradle clean build
“BUILD SUCCESSFUL” 後,您可以在 build/libs 目錄下找到 JAR 檔案。
您可以使用以下命令執行 JAR 檔案:
java –jar <JARFILE>
這將在 Tomcat 埠 8080 上啟動應用程式,如下所示:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ [32m :: Spring Boot :: [39m [2m (v3.3.3)[0;39m [2024-09-04T12:55:59Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 19132 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo) [2024-09-04T12:55:59Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default" [2024-09-04T12:56:00Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [111] [INFO ] Tomcat initialized with port 8080 (http) [2024-09-04T12:56:00Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing ProtocolHandler ["http-nio-8080"] [2024-09-04T12:56:00Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting service [Tomcat] [2024-09-04T12:56:00Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting Servlet engine: [Apache Tomcat/10.1.28] [2024-09-04T12:56:00Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing Spring embedded WebApplicationContext [2024-09-04T12:56:00Z] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] [main] [296] [INFO ] Root WebApplicationContext: initialization completed in 947 ms [2024-09-04T12:56:01Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting ProtocolHandler ["http-nio-8080"] [2024-09-04T12:56:01Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [243] [INFO ] Tomcat started on port 8080 (http) with context path '/' [2024-09-04T12:56:01Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 1.857 seconds (process running for 3.612)
輸出
現在在 POSTMAN 應用程式中點選以下 URL 並檢視輸出。
GET API URL 為:https://:8080/products

POST API URL 為:https://:8080/products

PUT API URL 為:https://:8080/products/3

DELETE API URL 為:https://:8080/products/3
