「Spring Boot 」webプロジェクトにhello worldを表示する方法

環境
Windows10 64bit
Spring Boot 2.6.2
Spring Tool Suite 4

操作方法
1.プロジェクトを作成します
(1). 「ファイル」->「新規(N)」->「Springスターター・プロジェクト」をクリックします。
(2). 「名前」の欄にプロジェクト名「sbtest」を入力し「次へ」をクリックします。
(3). 以下にチェックを入れます。「次へ」をクリックします。
「テンプレート・エンジン」->「Thymeleaf」
「Web」->「Spring Web」
「開発ツール」→「Spring Boot DevTools」
(4). 完了をクリックします。

2.クラスを作成します
(1) パッケージ「src/main/java/com.example.demo」の箇所で右クリックして、「新規(N)」->「クラス」をクリックします。
(2) 「名前」の欄にクラス名の「TestController」を入力して完了ボタンを押します。
パッケージ名 com.example.demo
TestController.javaクラスに以下のコードを追加します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class TestController {
@GetMapping("/cft")
public String funA(Model model) {
model.addAttribute("target", "hello world, study skill become smart");
return "arkgame";
}
}
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class TestController { @GetMapping("/cft") public String funA(Model model) { model.addAttribute("target", "hello world, study skill become smart"); return "arkgame"; } }
package com.example.demo;

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

@Controller
public class TestController {

      @GetMapping("/cft")
      public String funA(Model model) {

            model.addAttribute("target", "hello world, study skill become smart");
            return "arkgame";
      }
}

3.htmlファイルを作成します
「src/main/resources/tempates」フォルダで右クリックして、「新規(N)」->「ファイル」をクリックします。
「arkgame.html」を記入して完了ボタンを押下します
以下のコードを追加します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>hello</title>
</head>
<body>
<p th:text="${moji}"></p>
</body>
</html>
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>hello</title> </head> <body> <p th:text="${moji}"></p> </body> </html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8" />
    <title>hello</title>
  </head>
  <body>
    <p th:text="${moji}"></p>
  </body>
</html>

4.動作確認
4.1 プロジェクト「sbtest」を右クリックします
4.2 「実行(R)」->Spring Boot アプリケーション」をクリックします。
4.3 ブラウザのURL欄に以下のURLを入力して実行します
http://localhost:8080/cft
画面に「hello world, study skill become smart」が表示されます

Spring Boot

Posted by arkgame