Spring Boot单页应用程序-将每个请求转发到index.html [英] Spring boot single page application - forward every request to index.html
问题描述
我有一个Spring Boot(v1.3.6)单页应用程序(angular2),我想将所有请求转发到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
.
对 http://localhost:8080/index.html 的请求有效(200和i获取index.html),但 http://localhost:8080/home 不是(404).
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
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
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
不起作用.
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:/";
}
}
第一部分{path:[^\\.]+}
与.
以外的任何一个或多个字符匹配.这确保了file.ext
的请求不会被此RequestMapping处理.如果需要支持也转发子路径,请将/**
放在{...}
之外.
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 {...}
.
这篇关于Spring Boot单页应用程序-将每个请求转发到index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!