Springboot-http请求转https

application.properties配置

证书放到resources栏目下和application.properties同级
# 文件路径
server.ssl.key-store= classpath:
# 密钥口令
server.ssl.key-store-password:
# 密钥类型
server.ssl.key-store-type:

启动类

@Bean
    public TomcatServletWebServerFactory servletContainer() {

        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);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }

    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        // http端口
        connector.setPort(8080);
        connector.setSecure(false);
        // https端口
        connector.setRedirectPort(8081);
        return connector;
    }

页面访问

可以直接访问 https://127.0.0.1:8081
或访问 http://127.0.0.1:8080 会跳转到 https://127.0.0.1:80801

你可能感兴趣的:(SpringBoot)