springboot 配置兼容 https和http 访问

该文展示了如何在SpringBoot1.4.0版本中配置HTTPS和HTTP服务,使用Tomcat容器,通过pfx文件设置SSL,并提供了自签名证书的生成方法。
springboot版本

<!-- 继承springBoot默认值 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
</parent>
package cn.com.xxx;

import com.itextpdf.text.io.StreamUtil;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;

@SpringBootApplication
@ComponentScan(basePackages={"cn.com.xxxx.*","com.xxxx.*"})
public class MainApplication {

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

    // 这是spring boot 1.5.X以下版本的 添加了这个
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addAdditionalTomcatConnectors(createStandardConnector()); // 添加http
        return tomcat;
    }

    // 配置http
    private Connector createStandardConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(port);
        return connector;
    }

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
//        new StreamUtil();
    }

}

配置文件里的配置
server.port=8018
server.ssl.key-store=classpath:server.pfx
server.ssl.key-store-password=xxxx
server.ssl.keyStoreType=PKCS12

http.port=8019 

 tomcat正常启动后:控制台 会打印 https(8018) 和(http)8019

在界面通过https://localhost:8018和http://localhost8019 都可以访问

如果不想购买证书,也可以使用自签名的证书,看这里:通过openssl生成pfx证书-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值