1.申請證書
這里我選擇的是阿里云的個人免費的證書

因為使用的是內置的Tomcat,所以下載Tomcat類型的

2.配置項目
將證書XXXX.pfx文件放到項目的resources目錄,接著修改Application.yml文件
server:
port: 443
ssl:
key-store: classpath:XXXX.pfx
key-store-password: 證書密碼
keyStoreType: PKCS12
接著修改啟動類,添加如下內容,接著啟動項目
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.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
public class MxemApplication implements EmbeddedServletContainerCustomizer {
//攔截所有請求
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@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;
}
//配置http轉https
@Bean
public Connector httpConnector() {
Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
//Connector監聽的http的端口號
connector.setPort(80);
connector.setSecure(false);
//監聽到http的端口號后轉向到的https的端口號
connector.setRedirectPort(443);
return connector;
}
//這里設置默認端口為443,即https的,如果這里不設置,會https和http爭奪80端口
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(443);
}
}
3.可能出現的問題
可能會出現下面的錯誤
Address already in use: bind
解決辦法
以windows系統為例,查看當前端口被哪個進程占用了(進入到CMD中)
netstat -ano|findstr "443"
然后找到進程ID,使用任務管理器結束此進程即可。
如果對你有幫助,還請點個贊,點個關注