LoginSignup
7
13

More than 5 years have passed since last update.

SpringBootでアプリを作りたいので、Spring Initializrを試してみた

Posted at

SpringBootでアプリを作りたいと思い、試した内容をメモ。

環境

  • Mac High Sierra 10.13.5
  • Java 1.8.0_11
  • Maven 3.5.4
  • springboot 2.0.3

手順

Spring Initializrのサイトに行き、プロジェクトを作成

  • Group はルートパッケージ名(今回はcom.example)
  • Artifact はプロジェクト名(今回はdemo)
  • Search for dependencies はwebとthymeleafを追加

Generate Projectで雛形をダウンロード。
zip形式でダウンロードされるので解凍して使う。

ディレクトリ構造

src/
├ main/
│ ├ java/
│ │ └ 以下Groupで指定したディレクトリ/
│ │  └ Artifactで指定したディレクトリ/ - ①
│ └ resources/
│  ├ static/
│  └ templates/ - ②
├ test/
│ └ java/
│   └ 以下Groupで指定したディレクトリ/
│    └ Artifactで指定したディレクトリ/
├ mvnw
├ mvnw.cmd
└ pom.xml

①のディレクトリにControllerを作成する

HelloController.java
package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/")
    public String index(Model model) {
        model.addAttribute("hello", "Hello World !");
        return "index";
    }
}

②のディレクトリにテンプレートファイルを作成する

index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>index page</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta charset="UTF-8" />
</head>
<body>
  <p>index page</p>
  <p th:text="${hello}"></p>
</body>
</html>

ついでに②のディレクトリにerror.htmlを作成しておくと、エラー遷移用のページができる。

次に、mavenのコマンドでjarファイルを作成する。
プロジェクトのディレクトリに移動して、

mvn clean package

とすると、srcのディレクトリと同じ階層にtargetディレクトリが作成され、
jarファイルも出来ている。

実行

mvn spring-boot:run

ブラウザを起動して、
http://localhost:8080/

index page

Hello World !

と表示されればOK!
HelloController.javaで設定した、メッセージが表示されている。

参考

https://qiita.com/hikarut/items/d1273f99e5b124a887bd
https://qiita.com/paty-fakename/items/c82ed27b4070feeceff6

7
13
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
7
13