配置spring boot 将404重定向到单页app

新手上路,请多包涵

我想配置我的 Spring Boot 应用程序以将任何 404 not found 请求重定向到我的单页应用程序。

例如,如果我正在调用不存在的 localhost:8080/asdasd/asdasdasd/asdasd ,它应该重定向到 localhost:8080/notFound

问题是我有一个单页反应应用程序,它在根路径中运行 localhost:8080/ 。所以spring应该重定向到 localhost:8080/notFound 然后转发到 / (保持路由)。

原文由 Vovan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 687
2 个回答

这应该可以解决问题:为 404 添加一个错误页面,该页面路由到 /notFound ,并将其转发到您的 SPA(假设条目在 /index.html 上):

 @Configuration
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/notFound").setViewName("forward:/index.html");
    }

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
                    "/notFound"));
        };
    }

}

原文由 Ralf Stuckert 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是完整的 Spring Boot 2.0 示例:

 @Configuration
public class WebApplicationConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/notFound").setViewName("forward:/index.html");
}

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
    return container -> {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
                "/notFound"));
    };
  }

}

原文由 Jay Steven Hamilton 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题