Springboot2.0 设置本机https访问
软件背景:springboot2.0.4
-
生成证书秘钥
JDK中keytool是一个证书管理工具,可以生成自签名证书
具体生成如下图:【由于之前已经生成了别名为 tomcat的 tomcat.key 了,所以这里别名改成了springboot】
2、将生成好的证书copy到项目中,位置如下图:
3、修改application.yml 配置
http:
port: 80
server:
port: 443
tomcat:
max-threads: 800
accept-count: 30000
min-spare-threads: 20
max-connections: 30000
ssl:
key-store: tomcat.key
key-store-type: JKS
key-alias: tomcat
key-store-password: 123456
具体每个配置的值可以参考:
org.springframework.boot.autoconfigure.web.ServerProperties.Tomcat
org.springframework.boot.web.server.Ssl
4、修改springboot 项目启动类 xxxApplication 类
package com.johnny.laonongmin;
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.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.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.johnny")
@MapperScan("com.johnny.laonongmin.mapper")
public class LaonongminWebApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(LaonongminWebApplication.class);
// 在某配置类中添加如下内容
// 监听的http请求的端口,需要在application配置中添加http.port=端口号 如80
@Value("${http.port}")
private Integer httpPort;
//正常启用的https端口 如443
@Value("${server.port}")
private Integer httpsPort;
public static void main(String[] args) {
SpringApplication.run(LaonongminWebApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@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(createHttpConnector());
return tomcat;
}
public Connector createHttpConnector() {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("httpPort:{},httpsPort:{}",httpPort,httpsPort);
}
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
// Connector监听的http的端口号
connector.setPort(httpPort);
connector.setSecure(false);
// 监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(httpsPort);
return connector;
}
}
5、浏览器访问