Spring Boot 教程:消费 Rest Web 服务

本文将讨论如何使用 jQuery AJAX 来消费 RESTful Web 服务。
创建一个简单的 Spring Boot web 应用并编写一个控制器类文件用于重定向到 HTML 文件中,以消费 RESTful web 服务。
我们要在构件配置文件中加上 Spring Boot starter Thymeleaf 和 Web 依赖。
对于 Maven 用户,在 pom.xml 文件中加上以下依赖:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-thymeleaf</artifactId> 4 </dependency> 5 6 <dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-web</artifactId> 9 </dependency>
对于 Gradle 用户,在 build.gradle 中加上如下依赖:
1 compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-thymeleaf’ 2 compile(‘org.springframework.boot:spring-boot-starter-web’)
@Controller 类文件如下:
1 @Controller 2 public class ViewController { 3 }
可以定义请求 URI 方法来重定向到 HTML 文件中,如下所示:
1 @RequestMapping(“/view-products”) 2 public String viewProducts() { 3 return “view-products”; 4 } 5 @RequestMapping(“/add-products”) 6 public String addProducts() { 7 return “add-products”; 8 }
API http://localhost:9090/products 应当返回以下所示的 JSON 响应:
1 [ 2 { 3 "id": "1", 4 "name": "Honey" 5 }, 6 { 7 "id": "2", 8 "name": "Almond" 9 } 10 ]
现在,在 classpath 下的 templates 目录中创建 view-products.html 文件:
在这个 HTML 文件中,我们加上了 jQuery 类,且编写代码在页面加载时消费 RESTful web 服务。
<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 应当包含以下请求体和响应体:
请求体代码如下:
{ "id":"3", "name":"Ginger" }
响应体代码如下:
Product is created successfully
现在,在 classpath 下的 templates 目录中创建 add-products.html 文件。
在 HTML 文件中,我们加上 jQuery 库并编写,在单击按钮时提交表单以消费 RESTful web 服务。
1 <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 2 <script> 3 $(document).ready(function() { 4 $("button").click(function() { 5 var productmodel = { 6 id : "3", 7 name : "Ginger" 8 }; 9 var requestJSON = JSON.stringify(productmodel); 10 $.ajax({ 11 type : "POST", 12 url : "http://localhost:9090/products", 13 headers : { 14 "Content-Type" : "application/json" 15 }, 16 data : requestJSON, 17 success : function(data) { 18 alert(data); 19 }, 20 error : function(data) { 21 } 22 }); 23 }); 24 }); 25 </script>
完整的代码如下:
Maven – pom.xml 文件:
1 <?xml version = "1.0" encoding = "UTF-8"?> 2 <project xmlns = "http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 5 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 6 7 <modelVersion>4.0.0</modelVersion> 8 <groupId>com.tutorialspoint</groupId> 9 <artifactId>demo</artifactId> 10 <version>0.0.1-SNAPSHOT</version> 11 <packaging>jar</packaging> 12 <name>demo</name> 13 <description>Demo project for Spring Boot</description> 14 15 <parent> 16 <groupId>org.springframework.boot</groupId> 17 <artifactId>spring-boot-starter-parent</artifactId> 18 <version>1.5.8.RELEASE</version> 19 <relativePath /> 20 </parent> 21 22 <properties> 23 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 24 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 25 <java.version>1.8</java.version> 26 </properties> 27 28 <dependencies> 29 <dependency> 30 <groupId>org.springframework.boot</groupId> 31 <artifactId>spring-boot-starter-web</artifactId> 32 </dependency> 33 34 <dependency> 35 <groupId>org.springframework.boot</groupId> 36 <artifactId>spring-boot-starter-test</artifactId> 37 <scope>test</scope> 38 </dependency> 39 40 <dependency> 41 <groupId>org.springframework.boot</groupId> 42 <artifactId>spring-boot-starter-thymeleaf</artifactId> 43 </dependency> 44 </dependencies> 45 46 <build> 47 <plugins> 48 <plugin> 49 <groupId>org.springframework.boot</groupId> 50 <artifactId>spring-boot-maven-plugin</artifactId> 51 </plugin> 52 </plugins> 53 </build> 54 55 </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 如下:
1 package com.tutorialspoint.demo.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @Controller 7 public class ViewController { 8 @RequestMapping(“/view-products”) 9 public String viewProducts() { 10 return “view-products”; 11 } 12 @RequestMapping(“/add-products”) 13 public String addProducts() { 14 return “add-products”; 15 } 16 }
view-products.html 文件如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset = "ISO-8859-1"/> 5 <title>View Products</title> 6 <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 7 8 <script> 9 $(document).ready(function(){ 10 $.getJSON("http://localhost:9090/products", function(result){ 11 $.each(result, function(key,value) { 12 $("#productsJson").append(value.id+" "+value.name+" "); 13 }); 14 }); 15 }); 16 </script> 17 </head> 18 19 <body> 20 <div id = "productsJson"> </div> 21 </body> 22 </html> 23 add-products.html 文件如下: 24 <!DOCTYPE html> 25 <html> 26 <head> 27 <meta charset = "ISO-8859-1" /> 28 <title>Add Products</title> 29 <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 30 31 <script> 32 $(document).ready(function() { 33 $("button").click(function() { 34 var productmodel = { 35 id : "3", 36 name : "Ginger" 37 }; 38 var requestJSON = JSON.stringify(productmodel); 39 $.ajax({ 40 type : "POST", 41 url : "http://localhost:9090/products", 42 headers : { 43 "Content-Type" : "application/json" 44 }, 45 data : requestJSON, 46 success : function(data) { 47 alert(data); 48 }, 49 error : function(data) { 50 } 51 }); 52 }); 53 }); 54 </script> 55 </head> 56 57 <body> 58 <button>Click here to submit the form</button> 59 </body> 60 </html>
主 Spring Boot 应用类文件如下:
1 package com.tutorialspoint.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 @SpringBootApplication 7 public class DemoApplication { 8 public static void main(String[] args) { 9 SpringApplication.run(DemoApplication.class, args); 10 } 11 }
现在可以使用 Maven 或 Gradle 命令创建可执行 executable JAR 文件并运行 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 端口启动,如下图所示:

在浏览器中输入下面的 URL 你会看到如下图所示的输出:


现在,单击按钮 Click here to submit the form 你可以看到如下图所示的结果:

现在,单击如下查看产品 URL 查看所创建的产品。

Angular JS
要使用 Angular JS 消费 APIs,如下所示:
使用下面的代码创建 Angular JS 控制来消费 GET API - http://localhost:9090/products:
1 angular.module('demo', []) 2 .controller('Hello', function($scope, $http) { 3 $http.get('http://localhost:9090/products'). 4 then(function(response) { 5 $scope.products = response.data; 6 }); 7 });
使用下面的代码创建 Angular JS 控制来消费 POST API - http://localhost:9090/products:
1 angular.module('demo', []) 2 .controller('Hello', function($scope, $http) { 3 $http.post('http://localhost:9090/products',data). 4 then(function(response) { 5 console.log("Product created successfully"); 6 }); 7 });
注意: Post 方法数据表示用于创建产品的 JSON 格式的请求体

浙公网安备 33010602011771号