由于HTTPS具有良好的安全性,在开发中得到了越来越广泛的应用。对于个人而言,一个HTTPS证书的价格还是有点贵,幸好jdk中有免费生成证书的管理工具。
1.生成证书
在/jdk/bin目录下打开命令行,输入下面的命令1
keytool -genkey -alias tomcat -keyalg RSA -keystore F:\xpp.p12 -validity 365
解析1
2
3
4
51. -genkey 表示要创建一个新的密钥
2. -alias 表示keystore的别名
3. -keyalg 表示使用的加密算法RSA,是一种非对称加密算法
4. -keystore 表示密钥生成的位置
5. -validity 表示密钥的有效时间,单位为天
执行完命令,会在F盘下生成一个xpp.p12文件
2.项目中配置https
使用我们之前创建的SpringBoot基础项目,IDEA中创建SpringBoot项目
2.1 将xpp.p12文件复制到项目的resources
目录下
2.2 application.properties中配置属性
1 | server.ssl.key-store=classpath:xpp.p12 |
server.ssl.key-store-password为命令行中要你输入两次的密码,记得修改成你自己的.
启动项目
控制台打印信息,由之前的http变成了https
访问
继续访问之前的http://localhost:8080/hello/speak
,已经访问不了了
换成https://localhost:8080/hello/speak
再次访问,可能会弹出什么不信任的信息,不用管,点击直接访问。则得到了我们想要的结果数据。
3.重定向
希望访问http的8000端口,则重定向到https的8080端口
创建一个config
包,并在该包下创建一个TomcatConfig
类TomcatConfig
类代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45package com.xpp.demo01.comfig;
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;
/**
* @author by liangliping
* @Classname TomcatConfig
* @Description TODO
* @Date 2019\4\30 0030 11:42
*/
public class TomcatConfig {
TomcatServletWebServerFactory tomcatServletWebServerFactory(){
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
protected void postProcessContext(Context context) {
super.postProcessContext(context);
SecurityConstraint securityConstraint=new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection=new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
factory.addAdditionalTomcatConnectors(createTomcatConnector());
return factory;
}
private Connector createTomcatConnector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8000);
connector.setSecure(false);
connector.setRedirectPort(8080);
return connector;
}
}
启动项目,访问http://localhost:8000/hello/speak
,发现跳转到了https://localhost:8080/hello/speak