1.證書申請(自行選購)
2.下載證書
3.解壓下載壓縮包
4.將.pfx文件放至springboot項目resources目錄下
applicatio.yml中添加配置
5.設置http自動重定向https(8082端口->443端口):
在SpringApplication啓動類中加入以下代碼:(注意網上有些代碼中的EmbeddedServletContainerFactory找不到是因爲springboot2.X之後改了寫法)
//攔截所有請求
@Bean
public ServletWebServerFactory 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(httpConnector());
return tomcat;
}
//配置http轉https
@Bean
public Connector httpConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
//Connector監聽的http的端口號
connector.setPort(8082);
connector.setSecure(false);
//監聽到http的端口號後轉向到的https的端口號
connector.setRedirectPort(443);
return connector;
}
6.已測