Spring Boot使用RESTful Web服務

本章將詳細討論和學習如何使用jQuery AJAX來調用RESTful Web服務。

創建一個簡單的Spring Boot Web應用程式並編寫一個控制器類檔,用於重定向到HTML檔以使用RESTful Web服務。需要在構建配置檔中添加Spring Boot啟動程式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"
   }
]

現在,在類路徑的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

現在,在類路徑的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.zaixian</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.zaixian'
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.zaixian.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.zaixian.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 Boot應用程式。

對於Maven,請使用下麵給出的命令 -

mvn clean install

在“BUILD SUCCESS”之後,可以在目標目錄下找到JAR檔。

對於Gradle,請使用下麵給出的命令 -

gradle clean build

在“BUILD SUCCESSFUL”之後,在build/libs目錄下找到JAR檔。
使用以下命令運行JAR檔 -

java –jar <JARFILE>

現在,應用程式已在Tomcat端口8080上啟動。

在Web流覽器中訪問URL => http://localhost:8080/view-products ,可以看到如下所示的輸出 -

訪問URL => http://localhost:8080/add-products ,可以看到如下所示的輸出 -

現在,單擊按鈕提交表單,可以看到顯示的結果 -

現在,點擊查看產品URL => http://localhost:8080/view-products ,查看創建的產品。

使用 Angular JS

要使用Angular JS來使用API,可以使用下麵給出的示例 -

使用以下代碼創建Angular JS Controller以使用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 Controller以使用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 Thymeleaf示例 下一篇: Spring Boot CORS支持