หลังจาก Springboot 2.0 วิธีที่จะเปิดใช้งานโปรโตคอล HTTPS นั้นแตกต่างจากเมื่อ 1*ดังนั้นโพสต์รหัส
รหัสของฉันสามารถตรวจสอบได้ว่าจะเปิดใช้งานโปรโตคอล HTTPS ตามเงื่อนไข http2https ในพารามิเตอร์การกำหนดค่าหรือไม่ หากเปิดใช้งานโปรโตคอล HTTPS การเข้าถึงทั้งหมดไปยังโปรโตคอล HTTPS จะถูกถ่ายโอนไปยังโปรโตคอล HTTPS โดยอัตโนมัติ
1. เริ่มโปรแกรม
แพ็คเกจ com.wallimn.iteye.sp.asset; นำเข้า org.apache.catalina.context; นำเข้า org.apache.catalina.connector.connector; นำเข้า org.apache.tomcat.util.descriptor.web.securitycollection; นำเข้า org.apache.tomcat.util.descriptor.web.securityConstraint; นำเข้า org.springframework.beans.factory.annotation.value; นำเข้า org.springframework.boot.springapplication; นำเข้า org.springframework.boot.autoconfigure.springbootapplication; นำเข้า org.springframework.boot.autoconfigure.condition.conditionalonproperty; นำเข้า org.springframework.boot.web.embedded.tomcat.tomcatservletwebserverfactory; นำเข้า org.springframework.context.annotation.bean; /** * Springboot2.0 Starter * @author Wallimn, http://wallimn.iteye.com * */@springbootapplication คลาสสาธารณะ assetapplication {โมฆะคงที่สาธารณะหลัก (สตริง [] args) } // ถ้าค่าเริ่มต้นไม่ได้ใช้ 80 @Value ("$ {http.port: 80}") จำนวนเต็ม httpport; // พอร์ต https ที่เปิดใช้งานตามปกติคือ 443 @Value ("$ {server.port}") จำนวนเต็ม httpsport; // springboot2 วิธีการเขียน @bean @conditionalonproperty (name = "edition.http2https", มีค่า = "true", matchifmissing = false) public tomcatservletwebserverfactory servletcontainer () PostProcessContext (บริบทบริบท) {SecurityConstraint ข้อ จำกัด = ใหม่ SecurityConstraint (); Constraint.SetUserConstraint ("เป็นความลับ"); คอลเลกชัน SecurityCollection = New SecurityCollection (); collection.addpattern ("/*"); Constraint.addcollection (คอลเลกชัน); Context.addConstraint (ข้อ จำกัด ); - tomcat.addadditionaltomcatconnectors (httpconnector ()); กลับ Tomcat; } @Bean @ConditionAlOnProperty (name = "เงื่อนไข. http2https", มีค่า = "true", matchifmissing = false) ตัวเชื่อมต่อสาธารณะ httpconnector () {system.out.println ("เปิดใช้งาน HTTP "+this.httpsport); ตัวเชื่อมต่อตัวเชื่อมต่อ = ตัวเชื่อมต่อใหม่ ("org.apache.coyote.http11.http11nioprotocol"); connector.setscheme ("http"); // หมายเลขพอร์ตของ http ที่ฟังโดย connector.setport (httpport); connector.setSecure (เท็จ); // หมายเลขพอร์ตของ https ที่คุณหันไปหลังจากฟังหมายเลขพอร์ตของ https เชื่อมต่อ Setredirectport (httpsport); ตัวเชื่อมต่อกลับ; -2. ไฟล์กำหนดค่า
1. การกำหนดค่าเมื่อใช้โปรโตคอล HTTP
Server.port = 80
2. การกำหนดค่าเมื่อใช้โปรโตคอล HTTPS และ HTTP
server.port = 443 server.ssl.key-store = classpath: keystore.p12 server.ssl.key-store-password = server-password server.ssl.keystoretype = pkcs12 server.ssl.keyalias = เงื่อนไขของคุณ
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น