申请、下载SSL证书
-
腾讯云,阿里云都支持免费证书,这里我用的是阿里云 -
步骤如下:
修改application.properties文件
- 将.jks文件与application.properties同级
- 在application.properties文件中添加以下几行配置信息
server.port=443
server.custom.httpPort=80
#自定义启动banner文件的路径
#============================== https配置 ========================================
server.ssl.key-store=classpath:daishu.jks
server.ssl.key-store-password=
server.ssl.key-store-type=JKS
编写HttpsConfig类
package com.daishu.bbs.config;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author : xuzhennan @Project : daishu @Package : com.daishu.bbs.config
* @email : xuzhennan@58.com
* @date : 2021年12月07日 下午4:46
*/
@Configuration
public class HttpsConfig {
@Value("${server.custom.httpPort}")
private Integer httpPort;
@Value("${server.port}")
private Integer port;
/** 访问80端口跳转433 */
@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
// Connector监听的http的端口号
connector.setPort(httpPort);
connector.setSecure(false);
// 监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(port);
return connector;
}
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
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(connector);
return tomcat;
}
}
查看演示效果
演示效果点击这里
|