1.生成SSL,这里说下腾讯云可以免费申请。
2.将xxxxxxx.pfx文件复制到resources目录中
3.在application.yml文件之配置如下:
server:
ssl:
key-store: xxxxxxxxx.pfx//这里的路径自己修改pfx结尾的文件
key-store-password: xxxxxxxxx
keyStoreType: PKCS12
port: 443 //如果本地安装了SVN,会占用443端口,请将svn的443端口改成8443.443和80一样,通过访问的时候不需要输入端口号
4.主程序BootApplication中添加
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
//main方法是原本就有的,需要添加的是下面2个方法
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(BootApplication.class, args);
String serverPort = context.getEnvironment().getProperty("server.port");
log.info("mblog started at http://localhost:" + serverPort);
}
@Bean
public ServletWebServerFactory servletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection securityCollection = new SecurityCollection();
securityCollection.addPattern("/*");
securityConstraint.addCollection(securityCollection);
context.addConstraint(securityConstraint);
}
};
factory.addAdditionalTomcatConnectors(redirectConnector());
return factory;
}
private Connector redirectConnector() {
Connector connector = new Connector(Http11NioProtocol.class.getName());
connector.setScheme("http");
connector.setPort(8100);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}