spring mvc 捕获所有路由但只有未知路由

Leo*_*ley 4 spring spring-mvc angularjs spring-boot

我有一个前端带有 angular 的 Spring Boot 应用程序。

我在 html5 模式下使用 ui-router,我希望 spring 在所有未知路由上呈现相同的 index.html。

// Works great, but it also overrides all the resources
@RequestMapping
public String index() {
    return "index";
}

// Seems do be the same as above, but still overrides the resources
@RequestMapping("/**")
public String index() {
    return "index";
}

// Works well but not for subdirectories. since it doesn't map to those
@RequestMapping("/*")
public String index() {
    return "index";
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是我怎样才能创建一个回退映射但允许通过资源?

Leo*_*ley 5

我发现的最简单的方法是实现自定义 404 页面。

@Configuration
public class MvcConfig {

    @Bean
    public EmbeddedServletContainerCustomizer notFoundCustomizer(){
        return new NotFoundIndexTemplate();
    }

    private static class NotFoundIndexTemplate implements EmbeddedServletContainerCustomizer {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Neil McGuigan 提出了 HandlerInterceptor,但我无法理解它将如何实现。我不会很高兴看到这将如何实现,因为使用 html5 历史推送状态的单页应用程序将需要这种行为。而且我还没有真正找到解决这个问题的任何最佳实践。