首先使用https需要一个server.keystore,生成教程可以
然后开始改动项目:
配置文件中填入server.keystore的信息
server.ssl.key-store=server.keystore
server.ssl.key-alias=tomcat
server.ssl.enabled=true
server.ssl.key-store-password=****
server.ssl.key-store-type=****
配置文件中配置两个访问用的端口
启动类代码设置http访问和https
package com.bootdo;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
})
@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.bootdo.*.dao")
@SpringBootApplication
@EnableCaching
@EnableScheduling
public class BootdoApplication {
private static final Logger log= LoggerFactory.getLogger(BootdoApplication.class);
@Value("${http.port}")
private Integer port;
@Value("${server.port}")
private Integer httpsPort;
public static void main(String[] args) {
SpringApplication.run(BootdoApplication.class, args);
}
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
// 如果要强制使用https,请松开以下注释
// SecurityConstraint constraint = new SecurityConstraint();
// constraint.setUserConstraint("CONFIDENTIAL");
// SecurityCollection collection = new SecurityCollection();
// collection.addPattern("/*");
// constraint.addCollection(collection);
// context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(createStandardConnector()); // 添加http
return tomcat;
}
// 配置http
private Connector createStandardConnector() {
// 默认协议为org.apache.coyote.http11.Http11NioProtocol
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setSecure(false);
connector.setScheme("http");
connector.setPort(port);
connector.setRedirectPort(httpsPort); // 当http重定向到https时的https端口号
return connector;
}
}