0
0

More than 1 year has passed since last update.

Springbootで「HelloWorld」

Last updated at Posted at 2021-06-21

Springbootで「HelloWorld」を表示する

開発環境

  • Windows 10 Home 64bit
  • Eclipse Version: 2021-03 (4.19.0)
  • Java 11

Springbootでプロジェクトを追加する

ファイル → 新規 → Springスターター・プロジェクト

image.png
プロジェクト名を決める
デフォルトロケーションを使用
* 型:Gradle
* Javaバージョン:11
* パッケージリング:Jar
* 言語:Java

で次へ
image.png

依存関係選択
  • Thymeleaf
  • Spring web

を選択して完了
image.png

このような階層構造でJavaファイルが生成される
image.png

プロジェクト上で右クリック → 実行 → Spring boot App
コンソールにこのように表示されたら、作成成功!
image.png

HTMLファイルの作成

プロジェクト上で右クリック → 新規 → その他 → HTMLファイル
image.png

今回【test.html】というファイル名で作成
親フォルダーを入力または選択は:TestHello/src/main/resources/templates
をパスで指定して新規作成

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h1>Hello World!</h1>
ようこそ、Springbootの世界へ

</body>
</html>

いったん上記のよう<title>にタイトルと、<body>にテキストを記述

クラスファイルの作成

プロジェクト上で右クリック → 新規 → クラス
【TestController】というクラス名で作成
image.png

このような構成で.Javaファイルが作成されます。
image.png

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 //ClassにControllerのアノテーション
public class TestController {
    //RequestMappingのアノテーション
    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String test(Model model) {
        return "test"; //"test"は表示したいHTMLの名前(拡張子不要)
    }
}

上記のようにコードを記述

実行とブラウザに表示

保存したら
プロジェクト上で右クリック → 実行 → Spring boot App

ブラウザでhttp://localhost:8080/にアクセスして、テキストが表示されるか確認
image.png

Controllerからテキストを渡す

HTMLのコードに
xmlns:th="http://www.thymeleaf.org"(Thymeleafの属性)
th:text = "${テキスト}"を加える。後述のControllerのコードで
ここにデータ名が渡される。
どちらもHTMLのタグ内に記述する

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title >test</title>
</head>
<body>
<h1 th:text = "${title}">HelloWorld!</h1>
ようこそ、Springbootの世界へ!
</body>
</html>

Controllerのファイルには
model.addAttribute("title","テキスト");を加える
引数のテキストがth:textに渡される
その際HTMLにテキストがあっても上書きされる

public class TestController {
    //RequestMappingのアノテーション
    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String test(Model model) {

        model.addAttribute("title", "th:textで出力した場合はHTMLは上書きになる" );//Controllerから送りたいテキスト

        return "test"; //"test"は表示したいHTMLの名前(拡張子不要)
    }
}

image.png

以上

Thymeleafを使いこなせるように頑張って、また続き書きます

0
0
1

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