Spring boot2.0 版本已經推出一月有餘,此次版本升級的幅度很大,不少在1.5版本的的配置屬性或類被重命名或者刪除,致使之前慣用的寫法再也不適用,其中就包括http請求重定向到https請求方法的變動。java
若是在搜索引擎上搜索springboot 支持http/https,大體能搜到的方法是這樣的spring
// 在某配置類中添加以下內容 // 監聽的http請求的端口,須要在application配置中添加http.port=端口號 如80 @Value("${http.port}") Integer httpPort; //正常啓用的https端口 如443 @Value("${server.port}") Integer httpsPort; @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @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; }
可是在Spring boot2.0中EmbeddedServletContainerFactory 已經被重命名爲TomcatServletWebServerFactory,致使上面這段代碼不可用,因此在2.0版本咱們只需把EmbeddedServletContainerFactory 重命名爲TomcatServletWebServerFactory就能夠了。修改後的代碼大體以下apache
// 在某配置類中添加以下內容 // 監聽的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; }