Spring-boot-consuming-restful-web-services
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 {
}
以下に示すように、HTMLファイルにリダイレクトするリクエストURIメソッドを定義できます-
@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"
}
]
次に、クラスパスのテンプレートディレクトリの下にview-productslファイルを作成します。
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
次に、クラスパスのテンプレートディレクトリの下にadd-productslファイルを作成します。
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.finddevguides</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.finddevguides’
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.finddevguides.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-productslファイルです-
<!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-productslファイルを以下に示します-
<!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 Applicationクラスファイルは以下のとおりです-
package com.finddevguides.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コマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。
Mavenの場合、以下のコマンドを使用します-
mvn clean install
「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。
Gradleの場合、以下のコマンドを使用します-
gradle clean build
「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。
次のコマンドを使用してJARファイルを実行します-
java –jar <JARFILE>
これで、アプリケーションはTomcatポート8080で開始されました。
Tomcat Port_8080で開始されたアプリケーション
今、あなたのウェブブラウザでURLを打つと、次のように出力を見ることができます-
http://localhost:8080/view-products
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形式のリクエスト本文を表します。