SpringBoot同时支持HTTP和HTTPS

834 阅读1分钟

一、applicatio.yml配置

applicatio.yml

# 开发环境配置
server:
  # 服务器的HTTP端口,默认为8080
  port: 8443
#  ssl:
#    key-store: classpath:5519331_www.xxx.cn.jks
#    key-password: xxxxxxxx
#    key-store-type: jks
  ssl:
    key-store: classpath:5519331_www.xxx.cn.pfx
    key-store-password: xxxxxxxx
    keyStoreType: PKCS12
  #    enabled: true
  servlet:
    # 应用的访问路径
    context-path: /
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    max-threads: 800
    # Tomcat启动初始化的线程数,默认值25
    min-spare-threads: 30

二、重定向

@Configuration
public class SSLConfig {
    @Bean
    public TomcatServletWebServerFactory servletContainer() { //springboot2 新变化

        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {

            @Override
            protected void postProcessContext(Context context) {

                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }

    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);//http端口
        connector.setSecure(true);//设置为false重定向容易出错,建议设置为true
        connector.setRedirectPort(443);
        return connector;
    }
}

觉得好,就一键三连呗(点赞+收藏+关注)