我们可以配置http访问某个端口,自动跳转至https端口。例如,配置80端口,当用户通过  http://127.0.0.1:80/  访问时,会自动跳转至配置的https://127.0.0.1:8443。


@SpringBootApplication
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }

    @Bean
    //配置http某个端口自动跳转https
    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(80);
        connector.setSecure(false);
        //跳转的https端口
        connector.setRedirectPort(8443);
        return connector;
    }
}

 

最后修改于 2019-06-14 15:20:09
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇