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; }