SpringBoot配置http和https


修改application.yml配置

將原來的http改為https,application.yml配置文件中server添加相關的ssl配置

# Tomcat server: tomcat: uri-encoding: UTF-8 max-threads: 1000 min-spare-threads: 30 port: 8443 #原來是http的8080 connection-timeout: 5000ms servlet: context-path: / ssl: #添加的ssl自簽名證書 key-store: classpath:keystore.jks #注意路徑要配置正確 key-store-password: lovespring key-alias: lovespring key-password: lovespring http: # 新加一個http的端口號配置 port: 8080 

注意,如果ssl配置不正確,SpringApplication啟動后,會報端口號被占用,使用netstat -ano|findStr 8443一看,還真有兩個進程在使用tcp的8443端口 :(。其實是ssl配置不正確導致的,特地記錄一下。

修改Application代碼


    @Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { // 如果要強制使用https,請松開以下注釋 // SecurityConstraint constraint = new SecurityConstraint(); // constraint.setUserConstraint("CONFIDENTIAL"); // SecurityCollection collection = new SecurityCollection(); // collection.addPattern("/*"); // constraint.addCollection(collection); // context.addConstraint(constraint); } }; tomcat.addAdditionalTomcatConnectors(createStandardConnector()); // 添加http return tomcat; } // 配置http private Connector createStandardConnector() { // 默認協議為org.apache.coyote.http11.Http11NioProtocol Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); connector.setSecure(false); connector.setScheme("http"); connector.setPort(port); connector.setRedirectPort(httpsPort); // 當http重定向到https時的https端口號 return connector; } @Value("${http.port}") private Integer port; @Value("${server.port}") private Integer httpsPort; 

注意,SpringBoot版本不一樣,代碼也不一樣,主要是TomcatServletWebServerFactory 這個類是2.0.x才有的。其它版本可以在官方示例鏈接中切換分支版本查看。

參考

https://www.cnblogs.com/lianggp/p/8136540.html
官方示例



作者:Jamling
鏈接:https://www.jianshu.com/p/4ce077b15a2c
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM