我有一个要从Spring Boot应用程序提供的Angular 4(ES6)应用程序。我的Angular应用程序有一个index.html,当http://localhost:8080的地址被点击时,Spring Boot知道要映射到index.html文件,该文件在Angular中被映射为“/search”。

但是,我还有另一条称为“adminlogin”的路由,可以通过该路由访问

http://localhost:8080/adminLogin

但是在这种情况下,它命中了我的Spring Boot应用程序,该应用程序没有映射,然后引发了错误。

如何获取http://localhost:8080/adminLogin的地址以转到Angular应用程序?

最佳答案

我的SpringBoot 2和Angular6应用程序有类似的问题。我实现了WebMvcConfigurer接口(interface)以覆盖addResourceHandlers()方法,并在spring Controller 中找不到映射时重定向到index.html。这可以在Spring boot 1.5.x中扩展(现已弃用)WebMvcConfigurerAdaptor类来完成。在以下stackoverflow线程中对此进行了详细讨论:https://stackoverflow.com/a/46854105/2958428
我使用target/classes/static(以前为outputPath)中的angular.json字段将构建的角度应用程序放置在此位置.angular-cli.json中。
这是示例代码:

@Configuration
public class MyAppWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        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");
                }
            });
    }
}

07-24 09:39
查看更多