请选择 进入手机版 | 继续访问电脑版
在线投稿 文字标题 文字标题 文字标题 文字标题 文字标题
切换皮肤
1.申请证书
这里我选择的是阿里云的个人免费的证书
?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0323%2F759ac945p00q7mjc5000wd200u0004wg00zk005s.jpg

因为使用的是内置的Tomcat,所以下载Tomcat类型的
?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0323%2F32dfbe96p00q7mjc5000dd200ay00ipg00ay00ip.jpg
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"

回复

使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则


    Archiver|手机版|小黑屋|齐聚无忧 |网站地图

    Powered by Discuz! X3.4  © 2001-2013 Comsenz Inc.