#https //使用keytool生成本地证书 ,keytool是jdk自带的生成key工具,别名为tomcat keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 #-----上面那段话直接执行就行,Windows进去jdk目录底下。 #application.properties #配置https server.port=8443 #.keystore放在了src/main/resources里面,默认是隐藏的,可以从盘符下看 server.ssl.key-store=classpath:keystore.p12 #用jdk生成key时的口令 server.ssl.key-store-password=123456 server.ssl.keyStoreType:PKCS12 #key的别名 server.ssl.keyAlias:tomcat #配置从定向 #以下就是配置重定向的代码 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.beans.factory.annotation.Value; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @ClassName: HttpsConfig.java * @Description: TODO(用一句话描述做什么) * * @author liu pei * @version V 1.0 * @Date 2019年3月4日 上午11:19:03 */ @Configuration public class HttpsConfig { // 在某配置类中添加如下内容 // 监听的http请求的端口,需要在application配置中添加http.port=端口号 如80 @Value("${http.port}") Integer httpPort; // 正常启用的https端口 如443 @Value("${server.port}") Integer httpsPort; // springboot2 写法 @Bean public TomcatServletWebServerFactory 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); } }; tomcat.addAdditionalTomcatConnectors(httpConnector()); return tomcat; } @Bean public Connector httpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); // Connector监听的http的端口号 connector.setPort(httpPort); connector.setSecure(false); // 监听到http的端口号后转向到的https的端口号 connector.setRedirectPort(httpsPort); return connector; } }