我正在开发一个应用程序,该应用程序的后端为Spring Boot,前端为angular 6。我将所有前端文件构建到Spring Boot的静态文件夹中。在所有情况下,无论是(type=Internal Server Error, status=500)
错误还是(type=Not Found, status=404)
错误,我都希望我的应用程序不显示“ Whitelabel错误页面”,而是将用户重定向到静态文件夹中的index.html 文件。通过将以下代码添加到我的 WebMvcConfigurer :
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
registry.addResourceHandler("/**/*")
.addResourceLocations("classpath:/static/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath,
Resource location) throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
: new ClassPathResource("/static/index.html");
}
});
}
但是对于500个错误代码无法达到相同的结果。例如,当我在地址栏中键入带有特殊字符的url时,会出现以下错误:
**Whitelabel Error Page**
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Oct 23 13:56:11 IRST 2018
There was an unexpected error (type=Internal Server Error, status=500).
The request was rejected because the URL contained a potentially malicious String ";"
但是,如果我输入了一些不带特殊字符的错误网址,则会将我重定向到“ index.html”文件。
我还尝试将这些行添加到我的 WebMvcConfigurer 中,但这也不起作用:
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/notFound").setViewName("forward:/static/index.html");
registry.addViewController("/login").setViewName("forward:/static/index.html");
registry.addViewController("/error").setViewName("forward:/static/index.html");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error"));
};
}
答案 0 :(得分:0)
不需要更多代码,您可以在静态目录中创建一个名为“ public”的文件夹,然后在该名为“ 500.html”或“ 404.html”的创建文件之后在此名为“ error”的文件夹中创建目录或错误目录中的http_code.html现在可以重定向这些文件。