1、申请阿里云/腾讯云证书
按照阿里云或者腾讯云去申请免费的一年证书即可,申请下来的目录结构如下:
Apache
IIS
Nginx
Tomcat
有目前主流服务器的证书文件,主要Nginx
和Tomcat
用的多,咱们用的是Springboot所以就使用Tomcat
下面的证书;
2、项目内配置证书
下面以application.properties
为例(别问我为什么不用.yml
)
阿里云和腾讯云的区别就是证书文件的后缀不同,阿里云是.pfx
,腾讯云是.jks
,所以配置稍微微有点区别,都不算区别;
(1)阿里云配置 .pfx
#项目端口号和请求路径
server.port=10006
server.servlet.context-path=/xxx-wx-server
#配置证书
server.ssl.key-store=classpath:xxxAbcxxx.com.pfx
server.ssl.key-store-password=xxxxxxxxxxxxxxxx
server.ssl.key-store-type=PKCS12
(2)腾讯云配置 .jks
#项目端口号和请求路径
server.port=10006
server.servlet.context-path=/xxx-wx-server
#配置证书
server.ssl.key-store=classpath:xxxAbcxxx.com.jks
server.ssl.key-store-password=xxxxxxxxxxxxxxxx
server.ssl.key-store-type=JKS
3、启动类代码补充
一般来说springboot启动类里面配置http重定向https的配置代码即可,再没有什么别的代码配置;
package com.xxx;
import java.net.InetAddress;
import java.net.UnknownHostException;
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.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/**
* 启动程序
*/
@SpringBootApplication
@ServletComponentScan
public class XxxApplication
{
public static void main(String[] args) throws UnknownHostException
{
ConfigurableApplicationContext application = SpringApplication.run(XxxApplication.class, args);
}
/**
* http重定向到https
* @return
*/
@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(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(8008);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(8088);
return connector;
}
}