zoukankan      html  css  js  c++  java
  • SpringBoot配置http和https

    修改application.yml配置

    将原来的http改为https,application.yml配置文件中server添加相关的ssl配置

    # Tomcat
    server:
      tomcat:
        uri-encoding: UTF-8
        max-threads: 1000
        min-spare-threads: 30
      port: 8443 #原来是http的8080
      connection-timeout: 5000ms
      servlet:
        context-path: /
      ssl: #添加的ssl自签名证书
        key-store: classpath:keystore.jks #注意路径要配置正确
        key-store-password: lovespring
        key-alias: lovespring
        key-password: lovespring
    
    http: # 新加一个http的端口号配置
      port: 8080
    

    注意,如果ssl配置不正确,SpringApplication启动后,会报端口号被占用,使用netstat -ano|findStr 8443一看,还真有两个进程在使用tcp的8443端口 :(。其实是ssl配置不正确导致的,特地记录一下。

    修改Application代码

    
        @Bean
        public ServletWebServerFactory servletContainer() {
            TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
                @Override
                protected void postProcessContext(Context context) {
                    // 如果要强制使用https,请松开以下注释
                    // SecurityConstraint constraint = new SecurityConstraint();
                    // constraint.setUserConstraint("CONFIDENTIAL");
                    // SecurityCollection collection = new SecurityCollection();
                    // collection.addPattern("/*");
                    // constraint.addCollection(collection);
                    // context.addConstraint(constraint);
                }
            };
            tomcat.addAdditionalTomcatConnectors(createStandardConnector()); // 添加http
            return tomcat;
        }
    
        // 配置http
        private Connector createStandardConnector() {
            // 默认协议为org.apache.coyote.http11.Http11NioProtocol
            Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
            connector.setSecure(false);
            connector.setScheme("http");
            connector.setPort(port);
            connector.setRedirectPort(httpsPort); // 当http重定向到https时的https端口号
            return connector;
        }
    
        @Value("${http.port}")
        private Integer port;
    
        @Value("${server.port}")
        private Integer httpsPort;
    

    注意,SpringBoot版本不一样,代码也不一样,主要是TomcatServletWebServerFactory 这个类是2.0.x才有的。其它版本可以在官方示例链接中切换分支版本查看。

    参考

    https://www.cnblogs.com/lianggp/p/8136540.html
    官方示例



    作者:Jamling
    链接:https://www.jianshu.com/p/4ce077b15a2c
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    C++获取时间函数
    平滑算法:三次样条插值(Cubic Spline Interpolation)
    为什么想要交谈?
    c++日常小问题
    看板娘
    世界碰撞算法原理和总结(sat gjk)
    转载c++默认初始化文章--google翻译
    从4行代码看右值引用(转载 《程序员》2015年1月刊)
    c++模板特例化 函数模板(非法使用显式模板参数 )
    InverseTransformPoint 函数问题
  • 原文地址:https://www.cnblogs.com/xiadongqing/p/13042101.html
Copyright © 2011-2022 走看看