1
1

More than 3 years have passed since last update.

IntelliJでJava SpringBootのWebページを作成

Posted at

はじめに

IntelliJでJava SpringBootのプロジェクトを作成で作成したアプリケーションにTymeleafを使ってWebページの作成を行います。

手順

build.gradleの編集

spring-boot-starter-thymeleafを追加します。

build.gradle
dependencies {
    // SpringBoot
    implementation "org.springframework.boot:spring-boot-starter-web"
    testImplementation "org.springframework.boot:spring-boot-starter-test"
    implementation "org.springframework.boot:spring-boot-starter-thymeleaf"

Controllerを変更

Controllerを変更し、返却値をテンプレート名(index)に変更します。

package com.ykdevs.SpringBootTest.app;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "index";
    }
}

ページを作成

src/main/resources/templates にindex.htmlを作成します。

スクリーンショット 2021-09-05 1.22.40.png

スクリーンショット 2021-09-05 1.23.05.png

index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>テストページ</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello World!!
</body>
</html>

アプリケーションを起動

スクリーンショット 2021-09-05 1.25.19.png

変数を表示できるように変更

引数にModelクラスを指定して、addAttributeで値を指定します。

package com.ykdevs.SpringBootTest.app;

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

@Controller
public class IndexController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("name", "山田 太郎");
        return "index";
    }
}

テンプレートを編集

index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>テストページ</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'こんにちは, ' + ${name} + 'さん!'" />
</body>
</html>

アプリケーションを起動

スクリーンショット 2021-09-05 1.30.22.png

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