Spring boot同时支持http和https访问

Spring boot同时支持http和https访问

  • Spring boot版本:1.5.8.RELEASE

修改配置文件

application.properties中添加配置

1
2
3
4
server.port = 8443
server.ssl.key-store = classpath:sample.jks
server.ssl.key-store-password = secret
server.ssl.key-password = password

  • 证书文件可以自己生成,这里使用官方例子中的证书文件:点击下载
  • 证书放在resources文件夹下,与application.properties同级
  • 这样配置意味着应用程序将不再支持8080端口上的普通HTTP连接器
  • Spring boot不支持通过配置application.properties来实现同时使用http和https两种连接方式

程序内配置添加https连接器

不修改application.properties,在Spring boot入口添加下面的配置代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
}

private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource("keystore").getFile();
File truststore = new ClassPathResource("keystore").getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
return connector;
}
catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}

这样配置8080的主端口为http访问,8843端口为https访问,可以同时使用http和https两种连接方式,参考官网

但是jar包启动时报错,找不到证书文件了,因为在文件在jar里面!

jar包内路径问题暂时未找到解决办法,所以推荐用下面的方案

程序内配置添加http连接器

application.properties中添加配置

1
2
3
4
5
6
server.http.port = 8080

server.port = 8443
server.ssl.key-store = classpath:sample.jks
server.ssl.key-store-password = secret
server.ssl.key-password = password

添加下面的配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 开启多个连接器(同时支持http和https)
* @author chenbin
*/
@Configuration
public class MultiConnectorsConfiguration {
@Value("${server.http.port}")
private Integer httpPort;

@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(httpPort);
return connector;
}

}

这样配置8443的主端口为https访问,8080端口为http访问,参考官方例子
jar包运行也OK,问题解决!添加http连接器的配置较为简单,推荐用这种方式。

文章目录
  1. 1. Spring boot同时支持http和https访问
    1. 1.0.1. 修改配置文件
    2. 1.0.2. 程序内配置添加https连接器
    3. 1.0.3. 程序内配置添加http连接器