1.生成證書html
使用jdk,jre中的keytool.exe生成自簽名的證書,須要配置JAVA_HOME和path環境變量,即jdk的環境變量。命令以下:spring
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650apache
而後能夠找到C:/用戶/用戶名/keystore.p12,複製到springboot項目根目錄tomcat
2.加入頁面和映射springboot
添加一個index.html頁面在resources/stastic下面app
並添加一個配置類MVCConfig ide
@Configuration
public class MVCConfig implements WebMvcConfigurer {post
public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("/index"); registry.addViewController("/index").setViewName("/index"); }
}
3.springboot 配置SSLcode
在application.properties中配置server
server.port=8080
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=123456
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; }