一、新建spring boot 的web工程
创建项目
完成后,
新建一个controller
package com.https.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class demoController {
@GetMapping("/test")
public String test(){
return "hello springboot";
}
}
为了配置方便把application.properties改为application.yml
运行项目
正确后进入第二步
二、生成证书
打开一个存储文件的目录
输入cmd回车,输入这段代码
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
解释一下
1.-storetype 指定密钥仓库类型
2.-keyalg 生证书的算法名称,RSA是一种非对称加密算法
3.-keysize 证书大小
4.-keystore 生成的证书文件的存储路径
5.-validity 证书的有效期
根据提示输入相应信息
然后在当前目录会生成一个文件keystore.p12
复制文件到项目路径下,不要复制错了
配置application.yml文件
server:
ssl:
key-store: keystore.p12
key-store-password: 123456
key-store-type: PKCS12
key-alias: tomcat
port: 8081
key-store-password 这个是你在上面这里输入的密码
注意输入时默认自己看不到,我刚刚输入了123456,所以那个属性配置123456
配置启动类
package com.https.demo;
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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.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(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(8080);
connector.setSecure(true); //设置true,同时支持http和https,两个不同的端口
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(8081);
return connector;
}
}
启动项目,先尝试http访问,http://localhost:8080/test
再试试https访问,https://localhost:8081/test
注意http和https访问的端口不同,因为上面启动类中设置了,自己可以改动
到这里,点击高级,然后点继续
也是成功了的,证书问题,因为自己生成的证书不安全,可以找其他方式解决,这个我不太会,希望大神留言
报错排查
我的Springboot版本2.4.0,正常情况2.0.0以上版本下是没问题的,如果爆红
尝试加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.4.0</version>
</dependency>
然后
还是不行的话就是Springboot版本的问题或者,IDEA生成的项目不太对,去官网创建一个