1、到阿里云购买正式证书,并进行下载,放到springboot的resource同级目录,如

image

2、配置文件进行配置application.properties

image

3、主程序进行https的配置,如下:

image

其中StartAppHttps类为:

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.CommandLineRunner;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;

import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;

import org.springframework.context.annotation.Bean;

@SpringBootApplication

@EnableAutoConfiguration

public class StartAppHttps implements CommandLineRunner {

@Bean

public EmbeddedServletContainerFactory servletContainer() {

TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {

@Override

protected void postProcessContext(Context context) {

//Due to CONFIDENTIAL and /*, this will cause Tomcat to redirect every request to HTTPS.

//You can configure multiple patterns and multiple constraints if you need more control over what is and is not redirected.

SecurityConstraint constraint = new SecurityConstraint();

constraint.setUserConstraint("CONFIDENTIAL");

SecurityCollection collection = new SecurityCollection();

collection.addPattern("/*");

constraint.addCollection(collection);

context.addConstraint(constraint);

}

};

tomcat.addAdditionalTomcatConnectors(httpConnector());

return tomcat;

}

@Bean

public Connector httpConnector() {

Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");

//Set the scheme that will be assigned to requests received through this connector

//@param scheme The new scheme

connector.setScheme("http");

//Set the port number on which we listen for requests.

// @param port The new port number

connector.setPort(80);

//Set the secure connection flag that will be assigned to requests received through this connector.

//@param secure The new secure connection flag

//if connector.setSecure(true),the http use the http and https use the https;else if connector.setSecure(false),the http redirect to https;

connector.setSecure(false);

//redirectPort The redirect port number (non-SSL to SSL)

connector.setRedirectPort(443);

return connector;

}

@Override

public void run(String... args) throws Exception {

// TODO Auto-generated method stub

}

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐