springboot轻松实现https
只需三步,轻松实现
1.申请ssl证书(腾讯云为例)
证书申请是免费的,可以联系阿里云或者腾讯云客服获取申请渠道
将申请到的证书jks(tomcat文件夹里)文件复制到资源文件目录下
2.修改配置类
3.修改启动类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
/**
* http重定向到https
* @return
*/
@Bean
public TomcatServletWebServerFactory servletContainer() {
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(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的默认端口号
connector.setPort(8081);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号,也就是项目配置的port
connector.setRedirectPort(443);
return connector;
}
}