Spring Mvc和Spring Boot配置Tomcat支持Https

时间:2023-12-31 22:23:08

SpringBoot配置支持https

spring boot因为是使用内置的tomcat,所以只需要一些简单的配置即可。

1.首先打开命令行工具,比如cmd,输入以下命令
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

2.然后在你的根目录下面会看到一个.p12的文件,如下图所示:

3.将它移到你的spring boot项目中的resources目录下

4.最后在application.properties中添加以下配置:

server.port=8888
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=123456(此处密码为第一步中创建.p12文件时你输入的口令)
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat

5.最后启动你的spring boot项目即可用https的方式访问你的接口了。

用户访问http自动跳转到https,支持post方法

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; @Configuration
public class HttpConnectorConfig { // 在某配置类中添加如下内容
// 监听的http请求的端口,需要在application配置中添加http.port=端口号 如80
@Value("${http.port}")
Integer httpPort; //正常启用的https端口 如443
@Value("${server.port}")
Integer httpsPort; // 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.addMethod("post"); //添加post方法
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(httpPort);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(httpsPort);
return connector;
} }

---------------------
作者:颜艺学长
来源:CSDN
原文:https://blog.csdn.net/hwangfantasy/article/details/78403570
版权声明:本文为博主原创文章,转载请附上博文链接!