【发布时间】:2019-03-27 14:25:55
【问题描述】:
我正在开发一个应用程序,它以 spring boot 作为后端,angular 6 作为前端。我将所有前端文件构建到 Spring Boot 的静态文件夹中。在所有情况下,无论是(type=Internal Server Error, status=500) 错误还是(type=Not Found, status=404) 错误,我都希望我的应用不显示“Whitelabel 错误页面”,而是将用户重定向到 index.html 静态文件夹中的文件。我可以通过将以下代码添加到我的 WebMvcConfigurer 中来实现 404 错误代码:
@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 ";"
但如果我输入了一些没有特殊字符的错误 url,我会被重定向到“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"));
};
}
【问题讨论】:
标签: spring angular spring-boot