最近想在自己項目中添加支持htts但是找了幾個感覺寫的不是那么清楚六荒,然后自己結(jié)合別人的總結(jié)了一下另玖,具體實(shí)現(xiàn)如下:
1.用jdk自帶的生成證書
先在d盤下新建一個keys文件夾着绊,在到j(luò)dk的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