springboot项目jar包配置https

2022-07-16 12:07:50

1.阿里云申请ssl(免费)
在这里插入图片描述
2.把下载证书放到resources目录下在这里插入图片描述

3.spring boot注入TomcatServletWebServerFactory,监听http重定向到https

package com.cn.uniapi.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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * http强制跳转https
 */
@Configuration
public class Http2Https {

    @Value("${server.port}")
    private int sslPort;//https的端口

    @Value("${server.http-port}")
    private int httpPort;//http的端口

    @Bean
    public TomcatServletWebServerFactory servletContainerFactory() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                //设置安全性约束
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                //设置约束条件
                SecurityCollection collection = new SecurityCollection();
                //拦截所有请求
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        //设置将分配给通过此连接器接收到的请求的方案
        connector.setScheme("http");

        //true: http使用http, https使用https;
        //false: http重定向到https;
        connector.setSecure(false);

        //设置监听请求的端口号,这个端口不能其他已经在使用的端口重复,否则会报错
        connector.setPort(httpPort);

        //重定向端口号(非SSL到SSL)
        connector.setRedirectPort(sslPort);

        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}

4.配置application.properties

###配置https
#HTTP端口
server.port=443
server.http-port=8082

#开启https,配置跟证书一一对应
server.ssl.enabled=true
#指定证书
server.ssl.key-store=classpath:证书
server.ssl.key-store-type=PKCS12
#别名
#server.ssl.key-alias=证书名字
#密码
server.ssl.key-password=证书密码
server.ssl.key-store-password=证书密码

端口被占用解决

1.win+r  输入cmd
2.查询端口占用情况     netstat -ano|findstr "8081"(比如8081)
3.结束进程   taskkill /f /pid 3468(3468指的是pid)

借阅资料
https://www.cnblogs.com/huanzi-qch/p/12133872.html

  • 作者:xcLeigh
  • 原文链接:https://blog.csdn.net/weixin_43151418/article/details/122269507
    更新时间:2022-07-16 12:07:50