스프링 부트 및 커스텀404 에러 페이지
Spring Boot 어플리케이션에서 커스텀에러 페이지를 설정하려고 합니다.예를 들어 404의 경우 어플리케이션 설정에 다음 Bean을 추가했습니다.
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
}
};
}
또한 다음과 같은 심플한 Tymeleaf 템플릿을 작성했습니다.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>404 Not Found</title>
<meta charset="utf-8" />
</head>
<body>
<h3>404 Not Found</h3>
<h1 th:text="${errorCode}">404</h1>
<p th:utext="${errorMessage}">Error java.lang.NullPointerException</p>
<a href="/" th:href="@{/}">Back to Home Page</a>
</body>
</html>
그것을 더해서 and and and and and and and and and and and and and and 。/resources/templates/밖에 안 요.404번입니다.
404 페이지를 올바르게 셋업하려면 어떻게 해야 하나요?또한 커스텀 에러 페이지에는 정적 페이지뿐만 아니라 템플릿을 사용할 수 있습니까?
Spring Boot 1.4.x 에서는 커스텀에러 페이지를 추가할 수 있습니다.
는, 「」에 을 합니다.HTML 에러 페이지를 표시하려면 , 다음의 파일에 파일을 추가합니다.
/error는 정적 에 추가)이거나을 사용하여 수 .오류 페이지는 정적 HTML(즉, 정적 리소스 폴더 아래에 추가)이거나 템플릿을 사용하여 빌드할 수 있습니다.파일 이름은 정확한 상태 코드 또는 시리즈 마스크여야 합니다.예를 들어 404를 정적 HTML 파일에 매핑하려면 폴더 구조는 다음과 같습니다.
src/ +- main/ +- java/ | + <source code> +- resources/ +- public/ +- error/ | +- 404.html +- <other public assets>
당신은 Tymeleaf를 사용하고 있고, Tymeleaf는 컨트롤러 없이도 오류를 처리할 수 있습니다.
, 이 은 「Tymeleaf」, 「Tymeleaf」로 할 가 있습니다.error.html
아래 배치해야 합니다.src/main/resources > templates > error.html

페이지에 error 라고 하는 붙여진 할 필요가 를 들어, 「 error 」라고 하는 에러입니다.src/main/resources/templates/error/404.html.
새로운 Error Page(Http Status).NOT_FOUND, "/404.html")
★★★/404.html는 템플릿명이 아닌 리다이렉트 URL 경로를 나타냅니다.템플릿을 사용할 것을 고집하고 있기 때문에 이 명령어를 처리하는 컨트롤러를 작성해야 합니다./404.html 당신의 그고를 표현합니다.404.html에 살다src/main/resources/templates:
@Controller
public class NotFoundController {
@RequestMapping("/404.html")
public String render404(Model model) {
// Add model attributes
return "404";
}
}
또한 다음과 같은 보기 전용 렌더-er 컨트롤러를 View 컨트롤러로 대체할 수 있습니다.
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/404.html").setViewName("404");
}
}
또한 커스텀 에러 페이지에는 정적 페이지뿐만 아니라 템플릿을 사용할 수 있습니까?
네, 가능합니다.그러나 Not Found 페이지는 보통 정적이며 Plain Old HTML 대신 템플릿을 사용하는 것은 그다지 의미가 없습니다.
말은 필요 .EmbeddedServletContainerCustomizer대응하는 에러 페이지(404 의 경우는 404.html 등)를 퍼블릭 디렉토리에 넣는 것만으로 충분합니다(@brunoid 로 지정).
일반적인 ,, 용, 용, 용, 용, 용, 도, 습, 습, 습, 습, also, also, also, also, also, also, also, also, also a,error.html응용 프로그램에서 오류 또는 예외가 발생할 때마다 표시되는 페이지입니다.
간단한 예(Freemarker의 경우) -
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div class="jumbotron alert-danger">
<h1>Oops. Something went wrong</h1>
<h2>${status} ${error}</h2>
</div>
</div>
</body>
</html>
그러면 적절한 오류 상태와 해당 오류 메시지가 표시됩니다.또한 Spring Boot을 사용하고 있기 때문에 오류 페이지에 표시되는 상태 및 오류 메시지를 항상 덮어쓸 수 있습니다.
질문에서 제시한 것처럼 Tymeleaf를 사용하는 경우 이전 답변과 유사한 템플릿을 사용할 수 있지만, Freemarker가 아닌 Tymeleaf에 적합합니다.스타일링에 부트스트랩도 추가했습니다.
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Error Page</title>
<link href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
<script src="/webjars/jquery/3.2.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron alert-danger">
<h1>Oops... something went wrong.</h1>
<h2 th:text="${status + ' ' + error}"></h2>
</div>
</div>
</body>
</html>
이 코드를 다음 파일에 저장해야 합니다.error.htmlTymeleaf 템플릿 디렉토리에 저장합니다.동작하기 위해서 컨트롤러를 추가할 필요는 없습니다.
클래스 경로에 Tymeleaf가 있는지 확인하거나 아래 코드를 추가하고 프로젝트를 다시 가져옵니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
새로 추가해야 합니다.
@Controller
public class MyErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
if(statusCode == HttpStatus.NOT_FOUND.value()) {
return "error404";
}
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "error500";
}
}
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
여기에 이미지 설명을 입력합니다.Spring Boot Application 에서는 매우 간단합니다.Spring Boot은 우리에게 모든 것을 해주었다.
1) 경로 src/main/resources/templates에서 이름이 'error'인 폴더를 만듭니다.
2) 다음으로 이 폴더에 html 파일을 생성하여 '404.html'로 저장합니다.
당신은 여기서 모든 일을 했어요.
[스프링 부트(Spring Boot)]404 page not found 에러가 발생하면 이 페이지가 자동으로 표시됩니다.
주의: 이 작업을 수행하기 전에 POM에 Tymeleaf 저장소를 추가했는지 확인하십시오.xml
Tymeleaf는 컨트롤러 없이 오류를 처리할 수 있습니다. 리소스 폴더에 error.html을 생성합니다.
언급URL : https://stackoverflow.com/questions/37398385/spring-boot-and-custom-404-error-page
'programing' 카테고리의 다른 글
| Asp에서 Ajax를 사용하여 파일을 업로드하고 있습니다.넷코어 (0) | 2023.03.26 |
|---|---|
| TypeScript Import/as vs Import/require? (0) | 2023.03.26 |
| Angular ng-include에 매개 변수 전달 (0) | 2023.03.06 |
| JSON 문자열에서 기존 개체 인스턴스로 데이터 오버레이 (0) | 2023.03.06 |
| 64비트 값을 JSON 경유로 송신하려면 어떻게 해야 합니까? (0) | 2023.03.06 |