乐趣区

关于java:SpringBoot2X-同时支持http和https

一. 创立 springBoot 我的项目

二. 配置 ssl 证书

  1. 将证书放到我的项目的 resources 文件夹下,如下图所示
  2. 在 application.yml 文件中做如下配置(如果你的我的项目是 application.properties 能够批改后缀名为 yml 或者能够参考 yml 写法做响应的批改)
server:
  port: 6443
  ssl:
    key-store: classpath:springboot.p12
    key-store-password: 123456
    keyStoreType: PKCS12
    enabled: true

http:
  port: 6880

三. 创立 Tomcat 配置类

package com.example.demo.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author TM-majian
 * @version 1.0
 * @since 2021/5/7 19:21
 */
@Configuration
public class SSLConfig {@Value("${http.port}")
    private Integer port;

    @Bean
    public ServletWebServerFactory servletContainer() {TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(port);
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }

}

四. 创立 controller 测试

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author TM-majian
 * @version 1.0
 * @since 2021/5/7 19:19
 */
@RestController
public class TestController {@RequestMapping("/helloHttps")
        public String helloHttps(){return "hello https";}

}

五. 启动我的项目测试

  1. 本地测试

    通过控制台日志能够看到两个端口都已启动实现,浏览器拜访 http 连贯 http://localhost:6880/helloHttps

    拜访 https 连贯
    https://localhost:6443/helloH…
退出移动版