现如今越来越多的网站都开启了https,https为何如此受重视就不再赘述了,本文主要讲采用spring boot技术栈的项目如何同时支持http和https。
网上关于这个话题的讨论和文章实际上不少,但真正能够成功运行起来的并不多,就更别说那些只是简单的复制粘贴浪费人时间的垃圾教程,话不多说,下面进入正题。
spring boot之所以如此流行,除了强大的整合能力,其近乎于零配置的开发体验也是一个重要因素。具体到对https的支持,如果项目只是需要开启https的话开发者实际上都不需要写任何代码,只需要在application.properties做简单的几行配置就能分分钟完成任务。不过要同时支持的话其实也很简单,只需要写少量的代码。
首先上配置,在application.properties加入以下内容:
server.port=1376
#配置SSL
https.ssl.enable=true
#填写resources目录下的证书名,这里仅做演示之用
https.ssl.key-store=newhua.com.pfx
#以下填写自己的证书密码,这里仅做演示之用
https.ssl.key-store-password=123456
https.ssl.keyStoreType=PKCS12
https.ssl.port=8443
至此配置工作就完成了,接下来上代码:
@SpringBootApplication
public class StartApplication {
@Value("${https.ssl.port}")
private Integer tomcatSSLPort;
@Value("${https.ssl.enable}")
private boolean sslEnabled;
@Value("${https.ssl.key-store}")
private String tomcatSSLKeyStore;
@Value("${https.ssl.key-store-password}")
private String keystorePassword;
@Value("${https.ssl.keyStoreType}")
private String keystoreType;
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createSSLConnector());
return tomcat;
}
private Connector createSSLConnector() {
try {
File keystore = new ClassPathResource(tomcatSSLKeyStore).getFile();
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setPort(tomcatSSLPort);
connector.setSecure(true);
connector.setScheme("https");
connector.setAttribute("SSLEnabled", true);
connector.setAttribute("sslProtocol", "TLS");
connector.setAttribute("clientAuth", false);
connector.setAttribute("keystoreFile", keystore.getAbsolutePath());
connector.setAttribute("keystoreType", keystoreType);
connector.setAttribute("keystorePass", keystorePassword);
connector.setAttribute("keyPass", keystorePassword);
return connector;
} catch (IOException ex) {
ex.printStackTrace();
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
}
就是这么简单!然后启动spring boot,如果控制台显示Tomcat started on port(s): 8080(http) 8443 (https) with context path ''就代表项目已经同时支持了http和https。可以尝试分别以http和https访问相同的uri进行测试。
注:本文采用的spring boot版本为v2.1.5.RELEASE。
相关报道:
- 寺库宣布与Spring建立战略合作伙伴关系2019-05-07
要闻推荐
今日视点
热点专题
- 新闻排行
- 评测排行