在我们的应用程序中,我们希望将angular2前端部署到spring引导后端(进入src / main / resources / static),但要删除url中的#并使用angular2默认的PathLocationStrategy。
答案 0 :(得分:4)
只是想分享我是如何做到的,希望它有助于某人: (SpringBoot 1.3.3,Angular2.beta15,angular2-seed)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new Angular2PathLocationStrategyCustomizer();
}
private static class Angular2PathLocationStrategyCustomizer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container){
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/"));
}
}
}
答案 1 :(得分:1)
以下是您需要遵循的三个步骤:
实现自己的TomcatEmbeddedServletContainerFactory bean并设置RewriteValve
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
...
import org.apache.catalina.valves.rewrite.RewriteValve;
...
@Bean TomcatEmbeddedServletContainerFactory servletContainerFactory() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setPort(8080);
factory.addContextValves(new RewriteValve());
return factory;
}
将rewrite.conf文件添加到应用程序的WEB-INF目录中,并指定重写规则。这是一个示例rewrite.conf内容,我在角应用程序中使用它来利用角度的PathLocationStrategy(基本上我只是将所有内容重定向到index.html,因为我们只是使用spring boot来服务静态网页内容):
RewriteCond %{REQUEST_URI} !^.*\.(bmp|css|gif|htc|html?|ico|jpe?g|js|pdf|png|swf|txt|xml|svg|eot|woff|woff2|ttf|map)$
RewriteRule ^(.*)$ /index.html [L]
从路由声明中删除useHash(或将其设置为false):
RouterModule.forRoot(routes)
或
RouterModule.forRoot(routes, {useHash: false})