プロジェクトの作成
Gradle プロジェクト
| 名前 | HelloWorld |
| タイプ | Gradle-Grooby |
| パッケージング | Jar |
| Javaバージョン | 21 |
| 言語 | Java |

Maven プロジェクト
| 名前 | HelloWorld |
| タイプ | Maven |
| パッケージング | Jar |
| Javaバージョン | 21 |
| 言語 | Java |

依存関係は、次の3つ選択します。
- Spring Boot(開発者ツール)
- Thymeleaf(テンプレートエンジン)
- Spring Web(Web)
※Spring Web(Web)が Spring MVC です。
コントローラーの作成
src/main/javaフォルダを選択し、右クリック→新規→クラスでクラスを作成します。
| パッケージ | com.example.demo.controller |
| 名前 | HelloController |
HelloController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("hello")
public class HelloController {
@GetMapping
public String index() {
return "index";
}
@GetMapping("/greeting")
public String hello() {
return "hello";
}
@GetMapping("/about")
public String about() {
return "about";
}
@GetMapping("/sub")
public String sub() {
return "sub/sub";
}
} ビューの作成
ディレクトリ構成
- src/main/resources
- templates
- sub
- sub.html
- about.html
- hello.html
- index.html
- sub
- templates
src/main/resources→templatesをフォルダを選択し、 右クリック→新規→ファイルをクリックしHTMLファイルを作成します。
templatesの中にindex.html、hello.html、about.htmlの3つのファイルを作成します。
index.html
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>Index Page</h1>
<ul>
<li><a th:href="@{/hello}">index</a></li>
<li><a th:href="@{/hello/greeting}">hello</a></li>
<li><a th:href="@{/hello/about}">about</a></li>
</ul>
</body>
</html> hello.html
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>Hello World!!</h1>
</body>
</html> about.html
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>About Page</h1>
</body>
</html> フォルダで分ける場合は、templatesを選択し、右クリック→新規→フォルダでsubというフォルダを作成します。
作成したフォルダの中に、sub.htmlを作成します。
sub.html
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>sub page</h1>
</body>
</html> リンク先URL
- index.html → http://localhost:8080/hello
- hello.html → http://localhost:8080/hello/greeting
- about.html → http://localhost:8080/hello/about
- sub/sub.html → http://localhost:8080/hello/sub