Spring Boot 简明教程

Consuming RESTful Web Services

本章将详细讨论如何使用 jQuery AJAX 处理 RESTful Web 服务。

This chapter will discuss in detail about consuming a RESTful Web Services by using jQuery AJAX.

创建一个简单的 Spring Boot Web 应用程序,并编写一个用于重定向到 HTML 文件的控制器类,用于处理 RESTful Web 服务。

Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services.

我们需要在构建配置文件中添加 Spring Boot 入门 Thymeleaf 和 Web 依赖项。

We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file.

对于 Maven 用户,请在您的 pom.xml 文件中添加以下依赖项。

For Maven users, add the below dependencies in your pom.xml file.

<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>

对于 Gradle 用户,请在您的 build.gradle 文件中添加以下依赖项 -

For Gradle users, add the below dependencies into your build.gradle file −

compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-thymeleaf’
compile(‘org.springframework.boot:spring-boot-starter-web’)

@Controller 类文件的代码如下 -

The code for @Controller class file is given below −

@Controller
public class ViewController {
}

您可以定义请求 URI 方法以重定向到 HTML 文件,如下所示 -

You can define the Request URI methods to redirects into the HTML file as shown below −

@RequestMapping(“/view-products”)
public String viewProducts() {
   return “view-products”;
}
@RequestMapping(“/add-products”)
public String addProducts() {
   return “add-products”;
}

此 API http://localhost:9090/products 应返回以下 JSON 作为响应,如下所示:

This API http://localhost:9090/products should return the below JSON in response as shown below −

[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]

现在,在类路径中 templates 目录下创建一个 view-products.html 文件。

Now, create a view-products.html file under the templates directory in the classpath.

在 HTML 文件中,我们添加了 jQuery 库并在页面加载时编写了代码来利用 RESTful Web 服务。

In the HTML file, we added the jQuery library and written the code to consume the RESTful web service on page load.

<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 应包含以下请求体和响应体。

The POST method and this URL http://localhost:9090/products should contains the below Request Body and Response body.

请求体的代码如下:

The code for Request body is given below −

{
   "id":"3",
   "name":"Ginger"
}

响应体的代码如下:

The code for Response body is given below −

Product is created successfully

现在,在类路径中 templates 目录下创建 add-products.html 文件。

Now, create the add-products.html file under the templates directory in the classpath.

在 HTML 文件中,我们添加了 jQuery 库并编写了代码,以便在单击按钮时将表单提交到 RESTful Web 服务。

In the HTML file, we added the jQuery library and written the code that submits the form to RESTful web service on clicking the button.

<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>

完整的代码如下:

The complete code is given below.

Maven — pom.xml 文件

Maven – pom.xml file

<?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 的代码如下 -

The code for Gradle – build.gradle is given below −

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 如下所示——

The controller class file given below – ViewController.java is given below −

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 文件如下所示:

The view-products.html file is given below −

<!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 文件如下所示:

The add-products.html file is given below −

<!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 应用程序类文件如下所示:

The main Spring Boot Application class file is given below −

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);
   }
}

现在,您可以创建一个可执行 JAR 文件,并使用以下 Maven 或 Gradle 命令运行 Spring 引导应用程序。

Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,使用如下所示的命令:

For Maven, use the command as given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用如下所示的命令:

For Gradle, use the command as given below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用以下命令运行 JAR 文件 −

Run the JAR file by using the following command −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 8080 上启动。

Now, the application has started on the Tomcat port 8080.

started application on tomcat port 8080

现在在您的浏览器中输入 URL,您可以看到输出如下所示 −

Now hit the URL in your web browser and you can see the output as shown −

[role="bare"] [role="bare"]http://localhost:8080/view-products

1honey 2almond

[role="bare"] [role="bare"]http://localhost:8080/add-products

submit form spring boot

现在,单击按钮 Click here to submit the form ,您便可以看到结果,如下所示

Now, click the button Click here to submit the form and you can see the result as shown −

submit form spring boot output window

现在,点击查看产品网址,查看已创建的产品。

Now, hit the view products URL and see the created product.

1honey 2almond 3ginger

Angular JS

如需使用 Angular JS 消费 API,可以使用以下提供的示例 −

To consume the APIs by using Angular JS, you can use the examples given below −

使用以下代码创建 Angular JS 控制器以消费 GET API - http://localhost:9090/products

Use the following code to create the Angular JS Controller to consume the 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;
   });
});

使用以下代码创建 Angular JS 控制器以消费 POST API - http://localhost:9090/products

Use the following code to create the Angular JS Controller to consume the 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");
   });
});

Note − Post 方法数据表示以 JSON 格式创建产品的请求正文。

Note − The Post method data represents the Request body in JSON format to create a product.