Spring Boot容器配置,使用内置Tomcat并添加HTTPS

Spring Boot容器配置,使用内置Tomcat并添加HTTPS

1.Tomcat

spring boot项目可以内置Tomcat,Jetty等容器。

2.HTTPS

使用java的工具keytool生成一个数字证书,命令如下:

keytool -genkey -alias southwind0 -keyalg RSA -keysize 2048 -keystore sw.pl2 -validity 1000

这就生成了一个别名是southwind0、使用RSA算法加密、密钥长度2048、密钥存放位置当前目录下sw.pl2、密钥有效期1000天的数字证书,在cmd中需要填写信息,设置口令为sw12346。之后将sw.pl2放到根目录,在application.properties中配置如下:

由于spring boot同时不支持http和https,所以我们需要添加一个http跳转https。

HttpJumpConfig.java

package com.sw.demo.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 HttpJumpConfig {
    @Bean
    TomcatServletWebServerFactory servletContainer(){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context){
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL"); //confidential
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };

        factory.addAdditionalTomcatConnectors(httpConnector());
        return factory;
    }

    private Connector httpConnector(){
        //访问http的80端口,跳转到8088
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(80);
        connector.setSecure(true);
        connector.setRedirectPort(8088);
        return connector;
    }
}

测试如下:

https://127.0.0.1:8088/welcome

http://127.0.0.1/welcome

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

午夜安全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值