第一步
(若要部署到服务器建议在服务器上)使用Java JDK自带生成SSL证书的工具keytool
keytool -genkeypair -alias "tomcat" -keyalg "RSA" -keysize 2048 -keystore "tomcat.keystore"
第二步
项目配置证书
将生成的tomcat.keystore放到resources下
第三步
application.properties 或 application.yml 配置文件中配置相关https内容
server.port=8081
# 开启https,配置跟证书对应
server.ssl.enabled=true
server.ssl.key-store=classpath:tomcat.keystore
# server.ssl.key-store-type=JKS
server.ssl.key-store-type=JKS
# 密码
server.ssl.key-store-password=123456
# springboot2.x不需要配置
server.ssl.key-password=123456
# 别名
server.ssl.key-alias=tomcat
application.yml :
server:
# 服务器的HTTP端口,默认为8080
port: 8081
ssl:
key-store: classpath:tomcat.keystore
key-store-password: 123456
keyStoreType: JKS
keyAlias: tomcat
第四步
配置http协议跳转https
在启动类里加入配置如下:
/**
* http重定向到https
* @return
*/
@Bean
public ServletWebServerFactory 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(9998);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号,也就是项目配置的port
connector.setRedirectPort(8081);
return connector;
}