SpringBoot で Hello World


SpringBoot で Hello World

SpringBoot + ThymeleafでHello Worldを表示する

開発環境:
OS:windows10 home
Eclipse:pleiades-4.7.2

Eclipseの「ファイル」→「新規」→「その他」→ 「Spring スターター・プロジェクト」
を選択して、新規プロジェクトを作成します。

1.構成

sample-hello
 └─src
    └─main
        ├─java
        │  └─com
        │      └─example
        │          └─demo
        │                  HeloController.java
        │                  SampleHelloApplication.java
        └─resources
            │  application.properties
            │  
            ├─static
            └─templates
                    index.html

2.html
htmlを作成します。

index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>Springboot Hello Sample</h1>
    <p>
      <span th:text="${message}"></span>!!!
    </p>
  </body>
</html>

3.Controller
Controllerは以下のように作成する。indexというStringを返すようにすると、
resources/templatesの下のindex.htmlを返します。

package com.example.demo;

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

@Controller
public class HeloController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("message", "Hello Springboot");
        return "index";
    }
}

4.実行してみます。
プロジェクトを右クリック→「実行」→「Spring boot アプリケーション」を選択します。
http://localhost:8080/にアクセスすると、以下のような画面が表示されます。