springboot 1.x同时支持http&https

本文详细介绍了如何在SpringBoot中配置HTTPS,包括设置端口、密钥库文件、密钥库密码、密钥密码等关键步骤,并展示了如何通过@Bean注解创建SSL连接器,以及在启动类中注入HTTPS相关参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、yml

server:
  port: 8181

https:
  port: 8282
  ssl:
    key-store: classpath:sample.jks
    key-store-password: secret
    key-password: password

2、启动类添加

@Value("${https.port}")
private Integer port;

@Value("${https.ssl.key-store-password}")
private String key_store_password;

@Value("${https.ssl.key-password}")
private String key_password;
  
@Value("${https.ssl.key-store}")
private String key;

@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 {
    connector.setScheme("https");
    connector.setSecure(true);
    connector.setPort(port);
    protocol.setSSLEnabled(true);
    protocol.setKeystoreFile(key);
    protocol.setKeystorePass(key_store_password);
    protocol.setKeyPass(key_password);
    return connector;
  }
  catch (IOException ex) {
    throw new IllegalStateException("can't access keystore: [" + "keystore"
        + "] or truststore: [" + "keystore" + "]", ex);
  }
}

springboot 2.x

@Bean
  public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    tomcat.addAdditionalTomcatConnectors(createSslConnector()); // 添加http
    return tomcat;
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值