LoginSignup
13
12

More than 3 years have passed since last update.

EclipseでSpringBoot 動かしてみた

Last updated at Posted at 2020-04-14

参考

Springの公式ページの「Spring Quickstart Guide」を参考にやってみた。
https://spring.io/quickstart

注意

動くのか確認するためだけのプログラムなので
Mainのクラスにルーティング処理とかController設定とかしちゃってるけど
実際にはこんな書き方はしません。

しっかりレイヤー構成を考慮して作りましょう。

環境

Springのプロジェクトを作成

公式のプロジェクト生成ページで好みに合わせてジェネレート。
image.png

  • Gradle
    • Mavenのpomファイルは性に合わないのでビルドシステムはGradleを選択
  • Java 8
    • Kotlinも気になるけどJava
    • Versionはデフォルト設定
  • Spring Boot 2.2.6
    • これは適当
  • Packaging Jar
    • Webであることを考えるとWarだけど試しにJarを選択

GENERATEボタンを押すとプロジェクトがzipでダウンロードされる。

Eclipseでプロジェクトをインポート

Gradleプロジェクトをインポート

image.png

ダウンロードしたフォルダを指定

image.png

インポートされた

image.png

必要なライブラリとかダウンロードされてビルドも勝手に行われて問題なければこんなん出る。
image.png

実行

image.png

Spring Bootが起動したらこんな感じ
image.png

http://localhost:8080/ にアクセス。
まだルーティング処理書いてないので「Whitelabel Error Page」というエラーが出る。
image.png

ルーティング処理を作成

プロジェクトに入っているメインのクラスにルーティング処理を追加する。
image.png

GETリクエストでリクエストパラメータを取得

package com.pakhuncho.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
}

変更したアプリケーションを再配置する。
image.png

http://localhost:8080/hello でアクセスする。
image.png

http://localhost:8080/hello?name=pakhuncho でアクセスする。
image.png

http://localhost:8080/hello?name=ぱくぱく でアクセス
image.png

パス・パラメータを取得

package com.pakhuncho.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

    @RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return String.format("Hello %s!", name);
    }
}

http://localhost:8080/hello/ぱくぱく でアクセス
image.png

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12