最近都在用https了,可是咱们创立一个springboot的我的项目还是用http,明天咱们来看一下怎么将http变成https。。。

1. 生成证书

这里咱们须要应用jdk自带的keytool命令生成证书并复制到咱们我的项目的
目录下。

1.1 关上CMD

关上咱们装置的jdk的bin目录:

1.2 应用keytool命令生成证书

应用keytool命令生成证书:

keytool -genkey -alias server(别名) -keypass 123456(别名明码) -keyalg RSA(算法) -keysize 1024(密钥长度) -validity 365(有效期,天单位) -keystore D:/keys/server.keystore(指定生成证书的地位和证书名称) -storepass 123456(获取keystore信息的明码)

依据本人的理论状况依照此格局进行生成即可:

查看指标文件夹发现证书曾经生成结束!

2. 新建springboot我的项目

2.1 pom.xml

这里咱们只是引入web即可

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>

2.2 application.yml

server:  ssl:    # 证书门路    key-store: classpath:server.keystore    # 与申请时输出统一    key-alias: server    enabled: true    key-store-type: JKS    #与申请时输出统一    key-store-password: 123456    # 浏览器默认端口 和 80 相似,https默认的端口号为443  port: 443

2.3 HttpsConfig配置文件

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.web.embedded.tomcat.TomcatServletWebServerFactory;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * <p> * HTTPS 配置类 * </p> * * @author www.zhouzhaodong.xyz * @date Created in 2020/9/17 14:30 */@Configurationpublic class HttpsConfig {    /**     * 这里须要查看application.yml外面的端口号配置     * 配置 http(80) -> 强制跳转到 https(443)     */    @Bean    public Connector connector() {        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");        connector.setScheme("http");        connector.setPort(80);        connector.setSecure(false);        connector.setRedirectPort(443);        return connector;    }    @Bean    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {            @Override            protected void postProcessContext(Context context) {                SecurityConstraint securityConstraint = new SecurityConstraint();                securityConstraint.setUserConstraint("CONFIDENTIAL");                SecurityCollection collection = new SecurityCollection();                collection.addPattern("/*");                securityConstraint.addCollection(collection);                context.addConstraint(securityConstraint);            }        };        tomcat.addAdditionalTomcatConnectors(connector);        return tomcat;    }}

2.3 创立一个HttpsController

/** * 控制器 * @author www.zhouzhaodong.xyz * @date Created in 2020/9/17 14:30 */@RestControllerpublic class HttpsController {    @RequestMapping("/")    public String https(){        return "success";    }}

3. 进行测试

启动我的项目,浏览器拜访 http://localhost 将主动跳转到 https://localhost并显示内容:

集体博客地址:

http://www.zhouzhaodong.xyz

我的项目GitHub地址为:

https://github.com/zhouzhaodo...