本文中使用Spring boot 2.0.4 版本
一、配置Http 与 Https 同时启用
第一步修改application.yml 文件
port:443
ssl:
key-store:
classpath:viviendg.com.jks
key-password: ******
key-store-password: ******
http:
port: 80
第二步增加配置Bean 同时启用http与https
//80 与443端口同时启用
@Value("${http.port}")
private Integer port;
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
// 添加http
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
// 配置http
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(port);
return connector;
}
二 HTTP 跳转 HTTPS
除了正常在application.yml中配置ssl相关信息还需要增加Bean配置。另外需要注意以下Bean配置只适用于spring boot 2.0 及以上版本。1.5版本请参考链接
/**
* 访问80端口跳转433
* */
@Bean
public Connectorconnector(){
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 TomcatServletWebServerFactorytomcatServletWebServerFactory(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;
}
以上两种方式个人更倾向使用第二种即http跳转https。
网友评论