最近想在自己项目中添加支持htts但是找了几个感觉写的不是那么清楚,然后自己结合别人的总结了一下,具体实现如下:
1.用jdk自带的生成证书
先在d盘下新建一个keys文件夹,在到jdk的bin目录下(C:\Program Files\Java\jdk1.8.0_121\bin),粘贴下面命令:keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore D:/keys/kf.keystore -storepass 123456
2.然后把生成的kf.keystore粘贴到项目的resources文件下
3.在application.properties中配置HTTPS
#server.port: 8083(可以在这里制定端口,我是在yml文件下制定了)
server.ssl.key-store: classpath:kf.keystore
server.ssl.key-store-password: 123456
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias:tomcat
4.在application里面添加
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@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(initiateHttpConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8083);
return connector;
}
到此启动项目,成功配置https