springboot2 同时支持http https,http跳转https

参考:https://www.fengyunxiao.cn/

① springboot2 同时支持 http 和 https(http 不跳到 https)
【如果 http 需要强制跳转到 https ,请看②】

  1. 将 www.fengyunxiao.cn.jks 放到 resources 目录
  2. 修改 application.yml,修改 port 和 ssl
server:
  port: 443
  ssl:
    key-store: classpath:www.fengyunxiao.cn.jks
    key-store-password: 123123
    key-store-type: JKS
    key-alias: www.fengyunxiao.cn
  1. 修改 MainApplication(也就是 springboot 入口的 xxxApplication 类)
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setPort(80);
    connector.setRedirectPort(443);
    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
}

② springboot2 同时支持 http 和 https(http 强制跳到 https)

  1. 将 www.fengyunxiao.cn.jks 放到 resources 目录
  2. 修改 application.yml,修改 port 和 ssl
server:
  port: 443
  ssl:
    key-store: classpath:www.fengyunxiao.cn.jks
    key-store-password: 123123
    key-store-type: JKS
    key-alias: www.fengyunxiao.cn
  1. 修改 MainApplication(也就是 springboot 入口的 xxxApplication 类)
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
	    @Override
	    protected void postProcessContext(Context context) {
	        SecurityConstraint constraint = new SecurityConstraint();
	        constraint.setUserConstraint("CONFIDENTIAL");
	        SecurityCollection collection = new SecurityCollection();
	        collection.addPattern("/*");
	        constraint.addCollection(collection);
	        context.addConstraint(constraint);
	    }
	};
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setPort(80);
    connector.setRedirectPort(443);
    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
}

你可能感兴趣的:(springboot2)