Iri*_*kos 3 java spring custom-error-pages thymeleaf
我已经设法构建静态错误页面并使用这个 bean 重定向到它们:
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (optiuniEnvironment.equals("development")) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/404.html");
container.addErrorPages(error401Page, error404Page, error500Page);
}
}
};
}
Run Code Online (Sandbox Code Playgroud)
但是,现在我想构建一个使用控制器功能的自定义页面。
所以在我的控制器中,我有类似的东西
@RequestMapping("/404.html")
String pageNotFound(Model model, HttpServletRequest request)
{
return "404";
}
Run Code Online (Sandbox Code Playgroud)
并希望在遇到 HttpStatus 404 时重定向到它。
我相信答案是配置 DispatcherServlet,但不确定。有任何想法吗?谢谢!
(如果可能,请使用基于 java 的配置,而不是 xml)
您可以使用以下方法处理这些错误:
@ExceptionHandler(NoHandlerFoundException.class)
public String handle404Exception(NoHandlerFoundExceptionex) {
//do whatever you want
return "viewName";
}
Run Code Online (Sandbox Code Playgroud)
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(NoHandlerFoundException.class)
public String handle404Exception(NoHandlerFoundExceptionex) {
//do whatever you want
return "viewName";
}
}
Run Code Online (Sandbox Code Playgroud)
如果使用 Spring Boot,请在中设置以下属性 application.properties
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
Run Code Online (Sandbox Code Playgroud)
@Bean
public ErrorPageRegistrar errorPageRegistrar(){
return new CustomErrorPageRegistrar();
}
private static class CustomErrorPageRegistrar implements ErrorPageRegistrar {
// Register your error pages and url paths.
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
}
}
Run Code Online (Sandbox Code Playgroud)
并为相应的 url 定义您的控制器端点(例如 /400)