「Hello world!!」を画面に表示する・・
まず必ずはじめにやるのはこれですよね。
Thymeleaf を使います
jsp ではなく Thymeleaf を使います。
SpringBoot で jsp は非推奨とのことです。
Spring Boot Features上記リンクの7.1.10. Template Engines に下記が記述されています。
If possible, JSPs should be avoided. There are several known limitations when using them with embedded servlet containers.
ということで jsp ではなく Thymeleaf を使います。
pom.xml に追加です。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Controller を作成する
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/index")
public String index(Model model) {
return "hello";
}
}
@Controller | Controller クラスに付与する。 |
@RequestMapping | クラス、メソッドに付与可能。 URLマッピング。 リクエストメソッドやパラメータの指定などなど。 |
@GetMapping | メソッドに付与可能。 @RequestMappingよりも短く、可読性が高い。 GETで受け取るときはこちら。 |
@PostMapping | メソッドに付与可能。 POSTの場合はこちら。 |
class の配置場所を間違えると404エラーになるので注意です。
SpringBoot で使用する全ての class ファイルは、mainメソッド(SpringApplication.run)している class と同一package か配下の階層に配置します。

今回は DemoApplication.java に mainメソッド(SpringApplication.run) があるのでこの package 以下に配置します。
html を作成する
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>hellooooooo</title>
</head>
<body>
<h1>Hello world!!</h1>
</body>
</html>
/demo/src/main/resources/templates/ 配下に作成します。
単純に「Hello world!!」を表示するだけの画面になります。
画面を表示する

http://localhost:8080/hello/index
にアクセスして「Hello world!!」が表示されました!
コメント