SpringBoot 2.6で404エラー画面を表示するサンプル
環境
Windows10 64bit
Spring Boot 2.6.2
Spring Tool Suite 4
JDK 11
使用例
1.コントローラのクラス(TestController.java)
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class TestController {
//ファイルパスはcft
@GetMapping("/cft")
public String funA() {
//cftフォルダのindex.html
return "cft/index";
}
}
2.正常なページ画面(src\main\resources\templates\cft\index.html)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>トップページ</title> </head> <body > テストページ画面 </body> </html>
3.エラーを表示する画面(src\main\resources\templates\error.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>404エラーページ</title>
</head>
<body>
<p>時刻:</td><td th:text="${timestamp}"></p>
<p>エラー:</td><td th:text="${errors}"></p>
<p>トレース:</td><td th:text="${trace}"></p>
<p>パス:</td><td th:text="${path}"></p>
<p>ステータス:</td><td th:text="${status}"></p>
<p>エラー:</td><td th:text="${error}"></p>
<p>例外:</td><td th:text="${exception}"></p>
<p>メッセージ:</td><td th:text="${message}"></p>
</body>
</html>
4.動作確認
プロジェクトを右クリックして、「実行(R)」->「Spring Boot アノテーション」をクリックします
正常の場合
http://127.0.0.1:8080/cft/
画面に「テストページ画面」が表示されます
エラー画面が存在しない場合
http://127.0.0.1:8080/cft/dd
画面に以下の内容が表示されます
時刻:Thu Jan 13 19:57:33 JST 2022 エラー: トレース: パス:/cft/dd ステータス:404 エラー:Not Found 例外: メッセージ:No message available