基于SpringBoot实现的https

本文介绍了如何在SpringBoot项目中实现HTTPS,包括生成SSL证书、项目配置、配置类和properties文件设置,以及运行后的效果展示,提供了完整的项目源码供下载参考。

1.生成SSL证书(需要具有JDK环境)

keytool -genkeypair -alias tomcat -keyalg RSA -keystore E:\tomcat.key

//其中-alias是证书的别名,RSA是加密算法,-keystore后是输出证书的路径所在

 

2.项目结构图

3.配置类

package com.chq.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServletConfig {

	// springboot2 写法
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }
 
    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(8888);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(8443);
        return connector;
    }
	
}

4.配置文件application.properties

server.port=8443
server.servlet.context-path=/brother
server.tomcat.max-threads=800
server.tomcat.accept-count=30000
server.tomcat.min-spare-threads=20
server.tomcat.max-connections=30000
#    证书路径
server.ssl.key-store=tomcat.key
server.ssl.key-store-type=JKS
server.ssl.key-alias=tomcat
#    配置密码,就是在生成证书的时候输入的密码
server.ssl.key-store-password=Chq123456

4.然后运行,浏览器输入http://localhost:8888/brother/hello/test就会转发到https://localhost:8443/brother/hello/test

5.效果图:

6.完整项目:https://gitee.com/rbrother/HttpsProject.git

7.项目git下来后,记得转为maven项目.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值