springboot部署SSL证书及http重定向到https

springboot部署SSL证书及http重定向到https

部署SSL证书

application.properties中的代码

#443是https的端口
server.port=443
#部署SSL证书
http.port=80
server.ssl.key-store=classpath:SSL证书的名字
server.ssl.key-store-password=SSL证书的密码
server.ssl.key-store-type=PKCS12
server.ssl.enabled=true

在服务器中将SSL证书复制到jar包同一目录下

springboot的http80端口重定向至https443端口

Application中的代码

@SpringBootApplication
public class IfblogApplication {
    public static void main(String[] args) {
        SpringApplication.run(IfblogApplication.class, args);
    }
    /**
     * http80端口自动转发https443端口
     * @return
     */
    @Bean
    public TomcatServletWebServerFactory servletContainer() { //springboot2 新变化

        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(createHTTPConnector());
        return tomcat;
    }

    private Connector createHTTPConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        //同时启用http(80)、https(443)两个端口
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setPort(80);
        connector.setRedirectPort(443);
        return connector;
    }
}
上一篇:【MySQL基础】07:视图


下一篇:第一篇——React+dva+umi