由于Spring Boot中通过编码开启HTTPS服务比较复杂,所以官方推荐通过编码开启HTTP服务,而通过配置开启HTTPS服务。

Spring Boot的application.yml中添加如下配置,开启HTTPS服务

server:
port: 16062
ssl:
key-store: classpath:config/test.jks
key-store-password: 123456
key-password: 123456

其中的jks证书文件可以利用JDK工具keytool.exe(JDK bin目录下)生成:

keytool -genkeypair -alias test -keyalg RSA -validity 3650 -keystore test.jks

验证上一步生成的证书:

keytool -list -v -keystore test.jks

导出公钥证书(可选):

keytool -export -alias test -keystore test.jks -rfc -file test.cer

客户操作系统上配置该公钥证书为可信证书后,可消除浏览器由于无法验证私自颁发的证书真实性而产生的HTTPS警告。

Application.java中编写如下代码,开启HTTP服务

@SpringBootApplication
public class SampleTomcatTwoConnectorsApplication { @Bean
public Integer port() {
return SocketUtils.findAvailableTcpPort();
} @Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
} private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(port());
return connector;
} public static void main(String[] args) throws Exception {
SpringApplication.run(SampleTomcatTwoConnectorsApplication.class, args);
}
}
04-07 04:32