天天看点

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

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 {...}.