1.生成SSL证书(需要具有JDK环境)
keytool -genkeypair -alias tomcat -keyalg RSA -keystore E:\tomcat.key
//其中-alias是证书的别名,RSA是加密算法,-keystore后是输出证书的路径所在

2.项目结构图

3.配置类
package com.chq.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.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletConfig {
// springboot2 写法
@Bean
public TomcatServletWebServerFactory 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(8888);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(8443);
return connector;
}
}
4.配置文件application.properties
server.port=8443
server.servlet.context-path=/brother
server.tomcat.max-threads=800
server.tomcat.accept-count=30000
server.tomcat.min-spare-threads=20
server.tomcat.max-connections=30000
# 证书路径
server.ssl.key-store=tomcat.key
server.ssl.key-store-type=JKS
server.ssl.key-alias=tomcat
# 配置密码,就是在生成证书的时候输入的密码
server.ssl.key-store-password=Chq123456
4.然后运行,浏览器输入http://localhost:8888/brother/hello/test就会转发到https://localhost:8443/brother/hello/test
5.效果图:

6.完整项目:https://gitee.com/rbrother/HttpsProject.git
7.项目git下来后,记得转为maven项目.

本文介绍了如何在SpringBoot项目中实现HTTPS,包括生成SSL证书、项目配置、配置类和properties文件设置,以及运行后的效果展示,提供了完整的项目源码供下载参考。
1364

被折叠的 条评论
为什么被折叠?



