1.生成證書
使用jdk,jre中的keytool.exe生成自簽名的證書,需要配置JAVA_HOME和path環境變量,即jdk的環境變量。命令如下:
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
然后可以找到C:/用戶/用戶名/keystore.p12,復制到springboot項目根目錄
2.加入頁面和映射
添加一個index.html頁面在resources/stastic下面
並添加一個配置類MVCConfig
@Configuration
public class MVCConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index");
registry.addViewController("/index").setViewName("/index");
}
}
3.springboot 配置SSL
在application.properties中配置
server.port=8080 #SSL https證書配置 server.ssl.key-store=keystore.p12 server.ssl.key-store-password=123456 #行業標准PKCS12 server.ssl.key-store-type=PKCS12 server.ssl.key-alias=tomcat
現在就可以訪問https://localhost:8080/index了
4.http轉向https
在MVCConfig加入如下代碼
/*配置http自動轉為https*/
@Bean
public ServletWebServerFactory servletWebServerFactory(){
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");//機密的
SecurityCollection securityCollection = new SecurityCollection();
securityCollection.addPattern("/*");
securityConstraint.addCollection(securityCollection);
context.addConstraint(securityConstraint);
}
};
factory.addAdditionalTomcatConnectors(httpConnector());
return factory;
}
@Bean
public Connector httpConnector(){
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8888);
connector.setSecure(false);
connector.setRedirectPort(8080);
return connector;
}
記住在springboot2以上,沒有了TomcatEmbeddedServletContainerFactory,變成了TomcatServletWebServerFactory
然后訪問http://localhost:8888/index會轉向https://localhost:8080/index

