前回IntelliJでHelloWorldしました。
今回は簡単なREST APIを作ります。
ここを参考しました。
プロジェクトを作成
Spring initializrでプロジェクトのひな型を作成します。
Artifact: restservice
Name: restservice
Package name: restservice
Dependenciesで[Spring Web]のみ選択します。
[Generate]を押下します。
restservice.zipを解凍し、解凍されたフォルダにあるpom.xmlを右クリックします。
IntelliJで開きます。
プロジェクトをインポート
モデルファイルを作成
Greeting.java
package com.example.restservice;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
コントローラファイルを作成
GreetingController.java
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Requestに/greetingのみであれば、defaultValue = "World"になります。
プロジェクトのビルドと実行
mainメソッドのあるDemoApplication.javaを右クリックし、Run DemoApplication mainをクリックします。
アクセスしてみる
下記のリンクをアクセスすると、
http://localhost:8080/greeting
ちゃんとレスポンスが返ってきました。
{"id":1,"content":"Hello, World!"}
下記のリンクをアクセスすると、Hello, User!が戻ってきます。
http://localhost:8080/greeting?name=User
{"id":2,"content":"Hello, User!"}