spring boot 2.0以上版本 配置https,并且输入http自动转为https

1、生成证书

keytool -genkey -alias tomcat  -storetype PKCS12 -keyalg RSA -keysize 2048  -keystore keystore.p12 -validity 3650

spring boot 2.0以上版本 配置https,并且输入http自动转为https_第1张图片

会生成 keystore.p12文件;

2、将keystore.p12拷贝到项目的resource下

3、在application.xml中添加如下配置:

#server:
#  port: 9090
#  servlet:
#    session:
#      timeout: 30m #30分钟,测试的话时间不能太短,否则不准。m是分钟单位,s是秒的单位,h是小时的单位,不写单位的话默认是毫秒
server:
  port: 8085
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: 123456
    keyStoreType: PKCS12
    keyAlias: tomcat
  servlet:
    session:
      timeout: 30m #30分钟,测试的话时间不能太短,否则不准。m是分钟单位,s是秒的单位,h是小时的单位,不写单位的话默认是毫秒:

配置完成,此处已经可以进行https访问了

4、http转https

大多用户习惯输入http,在用户输入http的时候自动将http转换为https

则需要在,Applicaton.java中添加如下代码

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.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;

/**
 * 启动类

 */
@SpringBootApplication
public class ServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServerApplication.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(8080);
        connector.setSecure(false);
        //跳转的https端口
        connector.setRedirectPort(8085);
        return connector;
    }
}

备注:只有springboot2.0以上版本才可以这样配置

你可能感兴趣的:(框架集成)