1.申請(qǐng)證書(shū)
這里我選擇的是阿里云的個(gè)人免費(fèi)的證書(shū)
因?yàn)槭褂玫氖莾?nèi)置的Tomcat,所以下載Tomcat類(lèi)型的
2.配置項(xiàng)目
將證書(shū)XXXX.pfx文件放到項(xiàng)目的resources目錄,接著修改Application.yml文件
server:
port: 443
ssl:
key-store: classpath:XXXX.pfx
key-store-password: 證書(shū)密碼
keyStoreType: PKCS12
接著修改啟動(dòng)類(lèi),添加如下內(nèi)容,接著啟動(dòng)項(xiàng)目
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 {
//攔截所有請(qǐng)求
@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轉(zhuǎn)https
@Bean
public Connector httpConnector() {
Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
//Connector監(jiān)聽(tīng)的http的端口號(hào)
connector.setPort(80);
connector.setSecure(false);
//監(jiān)聽(tīng)到http的端口號(hào)后轉(zhuǎn)向到的https的端口號(hào)
connector.setRedirectPort(443);
return connector;
}
//這里設(shè)置默認(rèn)端口為443,即https的,如果這里不設(shè)置,會(huì)https和http爭(zhēng)奪80端口
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(443);
}
}
3.可能出現(xiàn)的問(wèn)題
可能會(huì)出現(xiàn)下面的錯(cuò)誤
Address already in use: bind
解決辦法
以windows系統(tǒng)為例,查看當(dāng)前端口被哪個(gè)進(jìn)程占用了(進(jìn)入到CMD中)
netstat -ano|findstr "443"
然后找到進(jìn)程ID,使用任務(wù)管理器結(jié)束此進(jìn)程即可。
如果對(duì)你有幫助,還請(qǐng)點(diǎn)個(gè)贊,點(diǎn)個(gè)關(guān)注