Spring Bootで独自のエラー画面を表示したい
エラー画面がほしい
システムの画面はちょっと困る
やること
・EmbeddedServletContainerCustomizerを実装する
・ErrorControllerクラスを作成する
・Viewを作成する
EmbeddedServletContainerCustomizer実装
Customizer.java
package com.example.error; import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.web.servlet.ErrorPage; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; @Component public class Customizer implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403")); container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404")); } }
※@Componentを付与して対応
エラー用
ErrorController.java
package com.example.controller.error; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.http.HttpStatus; @Controller public class ErrorController { @RequestMapping(value = "/403", method = RequestMethod.GET) @ResponseStatus(HttpStatus.NOT_FOUND) public String forbidden() { return "errorpage/403"; } @RequestMapping(value = "/404", method = RequestMethod.GET) @ResponseStatus(HttpStatus.NOT_FOUND) public String notFound() { return "errorpage/404"; } }
※エラーページを指定する
エラー画面
errorpage/403.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> </head> <body> 403 Forbidden </body> </html>
errorpage/404.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> </head> <body> 404 Not Found </body> </html>
単純にtemplates配下にerrorディレクトリ作成するだけでも対応できるかも…
画面