Spring Boot 教程:消費(fèi) Rest Web 服務(wù)
【注】本文譯自: https://www.tutorialspoint.com/spring_boot/spring_boot_consuming_restful_web_services.htm

? ? 本文將討論如何使用?jQuery AJAX 來(lái)消費(fèi)?RESTful Web 服務(wù)。
? ??創(chuàng)建一個(gè)簡(jiǎn)單的?Spring Boot web 應(yīng)用并編寫一個(gè)控制器類文件用于重定向到 HTML 文件中,以消費(fèi) RESTful web 服務(wù)。
? ??我們要在構(gòu)件配置文件中加上?Spring Boot starter Thymeleaf 和 Web 依賴。
? ??對(duì)于 Maven 用戶,在?pom.xml 文件中加上以下依賴:
<dependency>
???<groupId>org.springframework.boot</groupId>
???<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
???<groupId>org.springframework.boot</groupId>
???<artifactId>spring-boot-starter-web</artifactId>
</dependency>
? ??對(duì)于 Gradle 用戶,在?build.gradle 中加上如下依賴:
compile?group:?‘org.springframework.boot’,?name:?‘spring-boot-starter-thymeleaf’
compile(‘org.springframework.boot:spring-boot-starter-web’)
? ??@Controller 類文件如下:
@Controller
public?class?ViewController?{
}
? ??可以定義請(qǐng)求?URI 方法來(lái)重定向到 HTML 文件中,如下所示:
@RequestMapping(“/view-products”)
public?String?viewProducts()?{
???return?“view-products”;
}
@RequestMapping(“/add-products”)
public?String?addProducts()?{
???return?“add-products”;
}
? ?API?http://localhost:9090/products?應(yīng)當(dāng)返回以下所示的 JSON 響應(yīng):
[
???{
??????"id":?"1",
??????"name":?"Honey"
???},
???{
??????"id":?"2",
??????"name":?"Almond"
???}
]
? ??現(xiàn)在,在 classpath 下的?templates 目錄中創(chuàng)建 view-products.html 文件:
? ??在這個(gè) HTML 文件中,我們加上了 jQuery 類,且編寫代碼在頁(yè)面加載時(shí)消費(fèi) RESTful web 服務(wù)。
<script?src?=?"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
???$.getJSON("http://localhost:9090/products",?function(result){
??????$.each(result,?function(key,value)?{
?????????$("#productsJson").append(value.id+"?"+value.name+"?");
??????});?
???});
});
</script>
? ??POST 方法和 URL?http://localhost:9090/products?應(yīng)當(dāng)包含以下請(qǐng)求體和響應(yīng)體:
? ??請(qǐng)求體代碼如下:
{
???"id":"3",
???"name":"Ginger"
}
? ??響應(yīng)體代碼如下:
Product is created successfully
? ??現(xiàn)在,在 classpath 下的 templates 目錄中創(chuàng)建?add-products.html 文件。
? ??在 HTML 文件中,我們加上 jQuery 庫(kù)并編寫,在單擊按鈕時(shí)提交表單以消費(fèi) RESTful web 服務(wù)。
<script?src?=?"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
???$(document).ready(function()?{
??????$("button").click(function()?{
?????????var?productmodel?=?{
????????????id?:?"3",
????????????name?:?"Ginger"
?????????};
?????????var?requestJSON?=?JSON.stringify(productmodel);
?????????$.ajax({
????????????type?:?"POST",
????????????url?:?"http://localhost:9090/products",
????????????headers?:?{
???????????????"Content-Type"?:?"application/json"
????????????},
????????????data?:?requestJSON,
????????????success?:?function(data)?{
???????????????alert(data);
????????????},
????????????error?:?function(data)?{
????????????}
?????????});
??????});
???});
</script>
? ??完整的代碼如下:
? ??Maven – 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?
???http://maven.apache.org/xsd/maven-4.0.0.xsd">
???
???<modelVersion>4.0.0</modelVersion>
???<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>
???<parent>
??????<groupId>org.springframework.boot</groupId>
??????<artifactId>spring-boot-starter-parent</artifactId>
??????<version>1.5.8.RELEASE</version>
??????<relativePath?/>
???</parent>
???<properties>
??????<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
??????<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
??????<java.version>1.8</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>
??????<dependency>
?????????<groupId>org.springframework.boot</groupId>
?????????<artifactId>spring-boot-starter-thymeleaf</artifactId>
??????</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?=?‘1.5.8.RELEASE’
???}
???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?=?1.8
repositories?{
???mavenCentral()
}
dependencies?{
???compile(‘org.springframework.boot:spring-boot-starter-web’)
???compile?group:?‘org.springframework.boot’,?name:?‘spring-boot-starter-thymeleaf’
???testCompile(‘org.springframework.boot:spring-boot-starter-test’)
}
? ?控制類代碼如下:
? ? ViewController.java 如下:
package?com.tutorialspoint.demo.controller;
import?org.springframework.stereotype.Controller;
import?org.springframework.web.bind.annotation.RequestMapping;
@Controller
public?class?ViewController?{
???@RequestMapping(“/view-products”)
???public?String?viewProducts()?{
??????return?“view-products”;
???}
???@RequestMapping(“/add-products”)
???public?String?addProducts()?{
??????return?“add-products”;???
???}???
}
? ??view-products.html 文件如下:
<!DOCTYPE?html>
<html>
???<head>
??????<meta?charset?=?"ISO-8859-1"/>
??????<title>View?Products</title>
??????<script?src?=?"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
??????
??????<script>
?????????$(document).ready(function(){
????????????$.getJSON("http://localhost:9090/products",?function(result){
???????????????$.each(result,?function(key,value)?{
??????????????????$("#productsJson").append(value.id+"?"+value.name+"?");
???????????????});?
????????????});
?????????});
??????</script>
???</head>
???
???<body>
??????<div?id?=?"productsJson">?</div>
???</body>
</html>
? ??add-products.html 文件如下:
<!DOCTYPE?html>
<html>
???<head>
??????<meta?charset?=?"ISO-8859-1"?/>
??????<title>Add?Products</title>
??????<script?src?=?"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
??????
??????<script>
?????????$(document).ready(function()?{
????????????$("button").click(function()?{
???????????????var?productmodel?=?{
??????????????????id?:?"3",
??????????????????name?:?"Ginger"
???????????????};
???????????????var?requestJSON?=?JSON.stringify(productmodel);
???????????????$.ajax({
??????????????????type?:?"POST",
??????????????????url?:?"http://localhost:9090/products",
??????????????????headers?:?{
?????????????????????"Content-Type"?:?"application/json"
??????????????????},
??????????????????data?:?requestJSON,
??????????????????success?:?function(data)?{
?????????????????????alert(data);
??????????????????},
??????????????????error?:?function(data)?{
??????????????????}
???????????????});
????????????});
?????????});
??????</script>
???</head>
???
???<body>
??????<button>Click?here?to?submit?the?form</button>
???</body>
</html>
? ??主 Spring Boot 應(yīng)用類文件如下:
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);
???}
}
? ?現(xiàn)在可以使用 Maven 或 Gradle 命令創(chuàng)建可執(zhí)行?executable JAR 文件并運(yùn)行 Spring Boot 應(yīng)用了:
? ?Maven 命令如下:
mvn clean install
? ?在 “BUILD SUCCESS” 之后,你可以在 target 目錄下找到 JAR 文件。
? ?Gradle 可以使用以下命令:
gradle clean build
? ?在 “BUILD SUCCESSFUL” 之后,你可以在?build/libs 目錄下找到?JAR 文件。
? ?使用以下命令運(yùn)行 JAR 文件:
java –jar <JARFILE>
? ? 應(yīng)用已在?Tomcat 8080 端口啟動(dòng),如下圖所示:

? ? 在瀏覽器中輸入下面的?URL 你會(huì)看到如下圖所示的輸出:
? ??http://localhost:8080/view-products

? ??http://localhost:8080/add-products

? ? 現(xiàn)在,單擊按鈕?Click here to submit the form?你可以看到如下圖所示的結(jié)果:

? ? 現(xiàn)在,單擊如下查看產(chǎn)品 URL 查看所創(chuàng)建的產(chǎn)品。
? ??http://localhost:8080/view-products

Angular JS
? ?要使用?Angular JS 消費(fèi)?APIs,如下所示:
? ?使用下面的代碼創(chuàng)建?Angular JS 控制來(lái)消費(fèi) GET API -?http://localhost:9090/products:
angular.module('demo',?[])
.controller('Hello',?function($scope,?$http)?{
???$http.get('http://localhost:9090/products').
???then(function(response)?{
??????$scope.products?=?response.data;
???});
});
? ?使用下面的代碼創(chuàng)建?Angular JS 控制來(lái)消費(fèi)?POST API -?http://localhost:9090/products:
angular.module('demo',?[])
.controller('Hello',?function($scope,?$http)?{
???$http.post('http://localhost:9090/products',data).
???then(function(response)?{
??????console.log("Product?created?successfully");
???});
});
注意:?Post 方法數(shù)據(jù)表示用于創(chuàng)建產(chǎn)品的 JSON 格式的請(qǐng)求體