第一步:生成证书
在smd中输入
keytool -genkeypair -genkey -alias yushan -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore C:\Users\fanjunwei\Desktop\zhengshu.keystore -storepass 123456 -dname "CN=(192.168.0.111),OU=(gupo),O=(gupo),L=(hangzhou),ST=(zhejiang),C=(CN)"
生成证书
注:keypass和storepass 最好一致,否则会在tomc启动时出现错误
如下:
- java.security.UnrecoverableKeyException: Cannot recover key
- at sun.security.provider.KeyProtector.recover(KeyProtector.java:311)
- at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:121)
- at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:38)
- at java.security.KeyStore.getKey(KeyStore.java:763)
- at com.jn.test.TestCA.test_01(TestCA.java:18)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:597)
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true" secure="true" URIEncoding="UTF-8" useBodyEncodingForURI="true">
<SSLHostConfig certificateVerification="optional">
<Certificate certificateKeystoreFile="D:/xiajian/java/apache-tomcat-8.5.8/conf/zhengshu.keystore" certificateKeystorePassword="123456" certificateKeyAlias="yushan"/>
</SSLHostConfig>
</Connector>
第三步:配置tomcat的web.xml在末尾的</welcome-file-list>后加上
<!--强制HTTP转HTTPS -->
<security-constraint>
<web-resource-collection>
<web-resource-name>OPENSSL</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!--禁用tomcat不安全的http方法 -->
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>HEAD</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint></auth-constraint>
</security-constraint>
这样做以后启动tomcat以后,就可以访问https://localhost:8443了
但启动项目后,无法达到效果
第四步:修改项目中服务器的url 如你原来是http://localhost:8443就需要改为https://localhost:8443这样才能正常运行项目