- 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 伺服器
- 使用 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 - WebSocket
- 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 - Rest 模板
Rest Template 用於建立使用 RESTful Web 服務的應用程式。您可以使用exchange()方法使用所有 HTTP 方法使用 web 服務。下面給出的程式碼展示瞭如何建立 Rest Template 的 Bean 來自動裝配 Rest Template 物件。
...
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
GET
使用 RestTemplate - exchange() 方法使用 GET API
假設此 URL https://:8080/products 返回以下 JSON,我們將使用以下程式碼使用 Rest Template 使用此 API 響應:
[
{
"id": "1",
"name": "Honey"
},
{
"id": "2",
"name": "Almond"
}
]
您需要遵循以下幾點來使用 API:
自動裝配 Rest Template 物件。
使用 HttpHeaders 設定請求頭。
使用 HttpEntity 包裝請求物件。
為 Exchange() 方法提供 URL、HttpMethod 和返回型別。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@GetMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity <String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange("
https://:8080/products", HttpMethod.GET, entity, String.class).getBody();
}
}
POST
使用 RestTemplate - exchange() 方法使用 POST API
假設此 URL https://:8080/products 返回如下所示的響應,我們將使用 Rest Template 使用此 API 響應。
下面給出的程式碼是請求體:
{
"id":"3",
"name":"Ginger"
}
下面給出的程式碼是響應體:
Product is created successfully
您需要遵循以下幾點來使用 API:
自動裝配 Rest Template 物件。
使用 HttpHeaders 設定請求頭。
使用 HttpEntity 包裝請求物件。在這裡,我們將 Product 物件包裝起來發送到請求體。
為 exchange() 方法提供 URL、HttpMethod 和返回型別。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@PostMapping(value = "/template/products")
public String createProducts(@RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"https://:8080/products", HttpMethod.POST, entity, String.class).getBody();
}
}
PUT
使用 RestTemplate - exchange() 方法使用 PUT API
假設此 URL https://:8080/products/3 返回以下響應,我們將使用 Rest Template 使用此 API 響應。
下面給出的程式碼是請求體:
{
"name":"Indian Ginger"
}
下面給出的程式碼是響應體:
Product is updated successfully
您需要遵循以下幾點來使用 API:
自動裝配 Rest Template 物件。
使用 HttpHeaders 設定請求頭。
使用 HttpEntity 包裝請求物件。在這裡,我們將 Product 物件包裝起來發送到請求體。
為 exchange() 方法提供 URL、HttpMethod 和返回型別。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@PutMapping(value = "/template/products/{id}")
public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"https://:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
}
}
DELETE
使用 RestTemplate - exchange() 方法使用 DELETE API
假設此 URL https://:8080/products/3 返回以下響應,我們將使用 Rest Template 使用此 API 響應。
下面顯示的程式碼行是響應體:
Product is deleted successfully
您需要遵循以下幾點來使用 API:
自動裝配 Rest Template 物件。
使用 HttpHeaders 設定請求頭。
使用 HttpEntity 包裝請求物件。
為 exchange() 方法提供 URL、HttpMethod 和返回型別。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@DeleteMapping(value = "/template/products/{id}")
public String deleteProduct(@PathVariable("id") String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(headers);
return restTemplate.exchange(
"https://:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
}
}
完整的 Rest Template Controller 類檔案如下:
ConsumeWebService.java
package com.tutorialspoint.demo.controller;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
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 org.springframework.web.client.RestTemplate;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@GetMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange(
"https://:8080/products", HttpMethod.GET, entity, String.class).getBody();
}
@PostMapping(value = "/template/products")
public String createProducts(@RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"https://:8080/products", HttpMethod.POST, entity, String.class).getBody();
}
@PutMapping(value = "/template/products/{id}")
public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"https://:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
}
@DeleteMapping(value = "/template/products/{id}")
public String deleteProduct(@PathVariable("id") String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(headers);
return restTemplate.exchange(
"https://:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
}
}
充當 REST 服務的 Rest Controller 類,我們的 Web 服務正在呼叫。
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);
}
}
Spring Boot Application 類 – DemoApplication.java 的程式碼如下:
DemoApplication.java
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
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>
<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 的程式碼如下:
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')
}
您可以建立一個可執行的 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-05T13:35:28Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 9476 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo) [2024-09-05T13:35:28Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default" [2024-09-05T13:35:29Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [111] [INFO ] Tomcat initialized with port 8080 (http) [2024-09-05T13:35:29Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing ProtocolHandler ["http-nio-8080"] [2024-09-05T13:35:29Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting service [Tomcat] [2024-09-05T13:35:29Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting Servlet engine: [Apache Tomcat/10.1.28] [2024-09-05T13:35:29Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing Spring embedded WebApplicationContext [2024-09-05T13:35:29Z] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] [main] [296] [INFO ] Root WebApplicationContext: initialization completed in 928 ms [2024-09-05T13:35:29Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting ProtocolHandler ["http-nio-8080"] [2024-09-05T13:35:29Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [243] [INFO ] Tomcat started on port 8080 (http) with context path '/' [2024-09-05T13:35:29Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 1.852 seconds (process running for 2.829)
現在在 POSTMAN 應用程式中點選以下 URL,您可以看到輸出。
透過 Rest Template 獲取產品 - https://:8080/template/products
建立產品 POST - https://:8080/template/products
更新產品 PUT - https://:8080/template/products/3
刪除產品 - https://:8080/template/products/3