首页 > 解决方案 > 当 URL 在 Spring Boot 中包含潜在的恶意字符串时重定向到 index.html

问题描述

我正在开发一个应用程序,它的后端是 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"));
    };
}

标签: springangularspring-boot

解决方案


不需要更多代码,您可以在静态目录中创建一个名为“public”的文件夹,并在创建名为“500.html”或“404.html”或 http_code 的文件之后在该文件夹中创建名为“error”的目录。 html 在错误目录中,现在您可以重定向这些文件。


推荐阅读