这里我选择的是阿里云的个人免费的证书
因为使用的是内置的Tomcat,所以下载Tomcat类型的
将证书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);
}
}
可能会出现下面的错误
Address already in use: bind
解决办法
以windows系统为例,查看当前端口被哪个进程占用了(进入到CMD中)
netstat -ano|findstr "443"
然后找到进程ID,使用任务管理器结束此进程即可。
如果对你有帮助,还请点个赞,点个关注