SpringBoot开发之《兼容http和https同时访问》

小程序开发后台时,必须要以https才能访问,贼难受!配置一下即可解决。

第一步我们在springboot的application中配置如下代码

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;

@SpringBootApplication
public class SellApplication implements EmbeddedServletContainerCustomizer {

public static void main(String[] args) {
SpringApplication.run(SellApplication.class, args);
}


//拦截所有请求
@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的
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(443);
}
}
第二步我们在springboot的application.properties中配置如下代码

server.port=443
server.ssl.key-store=classpath:1624137_www.aimeimao.com.cn.pfx
server.ssl.key-store-password=8tCUBJsH
server.ssl.keyStoreType=PKCS12

注释:

1.server.port   端口号

2.server.ssl.key-store  证书文件

3.server.ssl.key-store-password  证书密码

4.server.ssl.keyStoreType     证书类型

 

配置以上步骤即可完成行云流水的操作!

posted @ 2019-01-24 15:02  初见(全栈成长中)  阅读(702)  评论(0编辑  收藏  举报