SpringBoot2.0 支持 https 访问
买了dapideng.com,自然要上https。
其实在之前的博客中,也早有提及配置证书的事儿,只不过这次变成了springboot,它内置了tomcat容器,和把项目打包放在tomcat下面不太一样了。
证书是阿里云申请的免费证书,放到resource目录下面,是以pfx结尾的文件。
在application.properties添加如下配置:
server.port=443
server.ssl.enabled=true
server.ssl.key-store=classpath:2046023_www.dapideng.com.pfx
server.ssl.key-store-password=c6503VGY
server.ssl.keyStoreType=PKCS12
在Application中注入以下两个Bean,这也是springboot更新至2.0版本之后,变更的部分。百度,或者谷歌出来的大部分配置都是基于1.5版本的。
@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
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(connector);
return tomcat;
}
执行maven命令,打包。
maven clean package
传到服务器上,执行命令,让服务在后台启动。
nohup java -jar demo.jar &
Done,perfect~ 👏👏
本作品采用《CC 协议》,转载必须注明作者和本文链接
本文由telami 创作,采用CC BY 3.0 CN协议 进行许可,可自由转载、引用,但需署名作者且注明。