Springbootで「HelloWorld」を表示する
開発環境
- Windows 10 Home 64bit
- Eclipse Version: 2021-03 (4.19.0)
- Java 11
Springbootでプロジェクトを追加する
ファイル → 新規 → Springスターター・プロジェクト
プロジェクト名を決める
デフォルトロケーションを使用
* 型:Gradle
* Javaバージョン:11
* パッケージリング:Jar
* 言語:Java
依存関係選択
- Thymeleaf
- Spring web
プロジェクト上で右クリック → 実行 → Spring boot App
コンソールにこのように表示されたら、作成成功!
HTMLファイルの作成
プロジェクト上で右クリック → 新規 → その他 → HTMLファイル
今回【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】というクラス名で作成
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/にアクセスして、テキストが表示されるか確認
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の名前(拡張子不要)
}
}
以上
Thymeleafを使いこなせるように頑張って、また続き書きます