Spring Boot 单页应用程序 - 将每个请求转发到 index.html

新手上路,请多包涵

我有一个 Spring Boot (v1.3.6) 单页应用程序 (angular2),我想将所有请求转发到 index.html

http://localhost:8080/index.html 的请求正在运行(200,我得到了 index.html),但 http://localhost:8080/home 不是(404)。

Runner.class

 @SpringBootApplication
@ComponentScan({"packagea.packageb"})
@EnableAutoConfiguration
public class Runner {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext run = SpringApplication.run(Runner.class, args);
    }
}

WebAppConfig.class

 @Configuration
@EnableScheduling
@EnableAsync
public class WebAppConfig extends WebMvcConfigurationSupport {

    private static final int CACHE_PERIOD_ONE_YEAR = 31536000;

    private static final int CACHE_PERIOD_NO_CACHE = 0;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.setOrder(-1);
        registry.addResourceHandler("/styles.css").addResourceLocations("/styles.css").setCachePeriod(CACHE_PERIOD_ONE_YEAR);
        registry.addResourceHandler("/app/third-party/**").addResourceLocations("/node_modules/").setCachePeriod(CACHE_PERIOD_ONE_YEAR);
        registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(CACHE_PERIOD_NO_CACHE);
        registry.addResourceHandler("/systemjs.config.js").addResourceLocations("/systemjs.config.js").setCachePeriod(CACHE_PERIOD_NO_CACHE);
        registry.addResourceHandler("/**").addResourceLocations("/index.html").setCachePeriod(CACHE_PERIOD_NO_CACHE);
    }

}

styles.css , /app/third-party/xyz/xyz.js ,.. 正在工作(200,我得到了正确的文件)。只有 /**index.html 不起作用。

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

阅读 504
1 个回答

您还可以添加转发控制器,例如:

 @Controller
public class ForwardingController {
    @RequestMapping("/{path:[^\\.]+}/**")
    public String forward() {
        return "forward:/";
    }
}

第一部分 {path:[^\\.]+} 匹配除 . 之外的任何字符中的一个或多个。这确保了对 file.ext 的请求不会被此 RequestMapping 处理。如果您需要支持子路径也被转发,请将 — 放在 — {...} /** 之外。

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

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