Spring-boot-building-restful-web-services
Spring Boot-RESTful Webサービスの構築
Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot.
注-RESTful Webサービスを構築するには、Spring Boot Starter Web依存関係をビルド構成ファイルに追加する必要があります。
Mavenユーザーの場合、次のコードを使用して、 pom.xml ファイルに以下の依存関係を追加します-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Gradleユーザーの場合、次のコードを使用して、 build.gradle ファイルに以下の依存関係を追加します。
compile('org.springframework.boot:spring-boot-starter-web')
完全なビルド構成ファイル 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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
完全なビルド構成ファイル Gradle Build – 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')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
RESTful Webサービスの構築に進む前に、次の注釈の知識があることが推奨されます-
レストコントローラー
@RestControllerアノテーションは、RESTful Webサービスを定義するために使用されます。 JSON、XML、カスタムレスポンスを提供します。 その構文は以下に示されています-
@RestController
public class ProductServiceController {
}
リクエストマッピング
@RequestMappingアノテーションは、RESTエンドポイントにアクセスするためのリクエストURIを定義するために使用されます。 Requestメソッドを定義して、オブジェクトを消費および生成できます。 デフォルトの要求方法はGETです。
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
リクエスト本文
@RequestBody注釈は、リクエスト本文のコンテンツタイプを定義するために使用されます。
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
}
パス変数
@PathVariableアノテーションは、カスタムまたは動的なリクエストURIを定義するために使用されます。 要求URIのPath変数は、以下に示すように中括弧\ {}として定義されます-
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
}
リクエストパラメータ
@RequestParamアノテーションは、リクエストURLからリクエストパラメータを読み取るために使用されます。 デフォルトでは、これは必須パラメーターです。 ここに示すように、リクエストパラメータのデフォルト値を設定することもできます-
public ResponseEntity<Object> getProduct(
@RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
}
GET API
デフォルトのHTTP要求メソッドはGETです。 このメソッドには、リクエストボディは必要ありません。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。
HTTP GETリクエストメソッドを定義するサンプルコードを以下に示します。 この例では、HashMapを使用して製品を保存しました。 格納する製品としてPOJOクラスを使用したことに注意してください。
ここでは、リクエストURIは /products であり、HashMapリポジトリから製品のリストを返します。 GETメソッドRESTエンドポイントを含むコントローラークラスファイルを以下に示します。
package com.finddevguides.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}
POST API
HTTP POSTリクエストは、リソースを作成するために使用されます。 このメソッドにはリクエストボディが含まれます。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。
次の例は、HTTP POST要求メソッドを定義するサンプルコードを示しています。 この例では、HashMapを使用して製品を保存しました。製品はPOJOクラスです。
ここでは、リクエストURIは /products であり、製品をHashMapリポジトリに保存した後にStringを返します。
package com.finddevguides.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
@RequestMapping(value = "/products", method = RequestMethod.POST)
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
}
PUT API
HTTP PUT要求は、既存のリソースを更新するために使用されます。 このメソッドにはリクエストボディが含まれます。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。
以下の例は、HTTP PUT要求メソッドを定義する方法を示しています。 この例では、HashMapを使用して既存の製品を更新しました。製品はPOJOクラスです。
ここで、リクエストURIは /products/\ {id} であり、製品の後にHashMapリポジトリに文字列を返します。 更新が必要な製品IDを定義するPath変数 \ {id} を使用したことに注意してください。
package com.finddevguides.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
}
DELETE API
HTTP削除リクエストは、既存のリソースを削除するために使用されます。 このメソッドには、リクエストボディは含まれていません。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。
以下の例は、HTTP DELETE要求メソッドを定義する方法を示しています。 この例では、HashMapを使用して、POJOクラスである既存の製品を削除しました。
リクエストURIは /products/\ {id} であり、HashMapリポジトリから製品を削除した後に文字列を返します。 削除する必要がある製品IDを定義するPath変数 \ {id} を使用しました。
package com.finddevguides.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
}
このセクションでは、ソースコードの完全なセットを提供します。 それぞれの機能について次のコードを確認してください-
*Spring Bootメインアプリケーションクラス– DemoApplication.java*
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);
}
}
*POJOクラス– Product.java*
package com.finddevguides.demo.model;
public class Product {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
*Rest Controllerクラス– ProductServiceController.java*
package com.finddevguides.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products", method = RequestMethod.POST)
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}
あなたは、実行可能なJARファイルを作成し、示されているように以下のMavenまたはGradleコマンドを使用してスプリングブートアプリケーションを実行することができます
Mavenの場合、以下に示すコマンドを使用します-
mvn clean install
「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。
Gradleの場合、以下に示すコマンドを使用します-
gradle clean build
「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。
以下に示すコマンドを使用して、JARファイルを実行できます-
java –jar <JARFILE>
これは、以下に示すようにTomcatポート8080でアプリケーションを開始します-
次に、POSTMANアプリケーションで次のURLにアクセスして、出力を確認します。
GET API URLは: http://localhost:8080/products
POSTMAN Application Get API URL
POST API URL: http://localhost:8080/products
POSTMAN Application Post API URL
PUT API URL: http://localhost:8080/products/3
POSTMAN Application Put API URL
DELETE API URL: http://localhost:8080/products/3