SpringBoot2.X 同时支持http和https

coder_J

一.创建springBoot项目

  1. image.png
  2. image.png
  3. image.png
  4. image.png

二.配置ssl证书

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

http:
  port: 6880

三.创建Tomcat配置类

image.png

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测试

image.png

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. 本地测试
    image.png
    通过控制台日志可以看到两个端口都已启动完成,浏览器访问http连接http://localhost:6880/helloHttps
    image.png
    访问https连接
    https://localhost:6443/helloH...
    image.png
阅读 77
6 声望
2 粉丝
0 条评论
你知道吗?

6 声望
2 粉丝
宣传栏