欢迎光临散文网 会员登陆 & 注册

Spring Boot 教程:消费 Rest Web 服务

2020-09-08 14:28 作者:信码由缰  | 我要投稿

【注】本文译自: https://www.tutorialspoint.com/spring_boot/spring_boot_consuming_restful_web_services.htm

    本文将讨论如何使用 jQuery AJAX 来消费 RESTful Web 服务。

    创建一个简单的 Spring Boot web 应用并编写一个控制器类文件用于重定向到 HTML 文件中,以消费 RESTful web 服务。

    我们要在构件配置文件中加上 Spring Boot starter Thymeleaf 和 Web 依赖。

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

    对于 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 {

}

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

@RequestMapping(“/view-products”)

public String viewProducts() {

   return “view-products”;

}

@RequestMapping(“/add-products”)

public String addProducts() {

   return “add-products”;

}

   API http://localhost:9090/products 应当返回以下所示的 JSON 响应:

[

   {

      "id": "1",

      "name": "Honey"

   },

   {

      "id": "2",

      "name": "Almond"

   }

]

    现在,在 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 服务。

<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 应用类文件如下:

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

   }

}

   现在可以使用 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 你会看到如下图所示的输出:

    http://localhost:8080/view-products

    http://localhost:8080/add-products

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

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

    http://localhost:8080/view-products

Angular JS

   要使用 Angular JS 消费 APIs,如下所示:

   使用下面的代码创建 Angular JS 控制来消费 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:

angular.module('demo', [])

.controller('Hello', function($scope, $http) {

   $http.post('http://localhost:9090/products',data).

   then(function(response) {

      console.log("Product created successfully");

   });

});

注意 Post 方法数据表示用于创建产品的 JSON 格式的请求体


Spring Boot 教程:消费 Rest Web 服务的评论 (共 条)

分享到微博请遵守国家法律