您好,登錄后才能下訂單哦!
SpringBoot2.0之后,啟用https協議的方式與1.*時有點兒不同,貼一下代碼。
我的代碼能夠根據配置參數中的condition.http2https,確定是否啟用https協議,如果啟用https協議時,會將所有http協議的訪問,自動轉到https協議上。
一、啟動程序
package com.wallimn.iteye.sp.asset; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; /** * SpringBoot2.0啟動程序 * @author wallimn,http://wallimn.iteye.com * */ @SpringBootApplication public class AssetApplication { public static void main(String[] args) { SpringApplication.run(AssetApplication.class, args); } //如果沒有使用默認值80 @Value("${http.port:80}") Integer httpPort; //正常啟用的https端口 如443 @Value("${server.port}") Integer httpsPort; // springboot2 寫法 @Bean @ConditionalOnProperty(name="condition.http2https",havingValue="true", matchIfMissing=false) 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 @ConditionalOnProperty(name="condition.http2https",havingValue="true", matchIfMissing=false) public Connector httpConnector() { System.out.println("啟用http轉https協議,http端口:"+this.httpPort+",https端口:"+this.httpsPort); 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; }}
二、配置文件
1.使用http協議時的配置
server.port=80
2.使用https及http協議時的配置
server.port=443 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=your-password server.ssl.keyStoreType=PKCS12 server.ssl.keyAlias=your-cert-alias condition.http2https=true http.port=80
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。