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

I have a Spring Boot (v1.3.6) single page application (angular2) and i want to forward all request to the index.html.

A request to http://localhost:8080/index.html is working (200 and i get the index.html) but http://localhost:8080/home is not (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,.. are working (200 and i get the correct file). Only /** to index.html is not working.

解决方案

You can also add a forwarding controller like:

@Controller

public class ForwardingController {

@RequestMapping("/{path:[^\\.]+}/**")

public String forward() {

return "forward:/";

}

}

The first part {path:[^\\.]+} matches one or more of any character other than .. This makes sure request for a file.ext doesn't get handled by this RequestMapping. If you need to support sub-paths to also be forwarded, put /** outside of the {...}.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值