查了一堆资料,发现不是过时就是路径不对,记录一下。
我是从腾讯云下载了jks证书,查资料放入到根目录,然后配置.properties文件如下:
server.ssl.key-store=demo.jks
server.ssl.key-store-password=123456
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias:tomcat
server.port=443
部署到服务器的时候启动项目的时候一直报错,说443端口被占用,百思不得其解,后来上拉详细Log发现是证书路径找不到,再找找资料,把证书放在了/src/main/resources下面,并做如下配置:
server.ssl.key-store=classpath:demo.jks
终于能找到了,在启动类application中加入代码把http的请求自动转到https中去,代码如下:
@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(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
接着启动项目,输入域名后自动转入到https中。