在springboot使用https協議的時候一到了一個坑,EmbeddedServletContainerFactory找不到,之前以爲是jar包的版本低了,結果發現是springboot2.X之後改了寫法。
如下:
// 在某配置類中添加如下內容
// 監聽的http請求的端口,需要在application配置中添加http.port=端口號 如80
@Value("${http.port}")
Integer httpPort;
//正常啓用的https端口 如443
@Value("${server.port}")
Integer httpsPort;
// springboot2 寫法
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector監聽的http的端口號
connector.setPort(httpPort);
connector.setSecure(false);
//監聽到http的端口號後轉向到的https的端口號
connector.setRedirectPort(httpsPort);
return connector;
}