http转向https

很多时候我们在地址栏输入的是http,但是会自动转向到https,要实现这个功能,我们需要配置TomcatServletWebServerFactory 书上讲的是 EmbeddedServletContainerFactory, 但是现在已经不用了。
直接贴代码吧,我也是代码上试验的

 1 @Bean
 2 public TomcatServletWebServerFactory servletContainer() {
 3     TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
 4         @Override
 5         protected void postProcessContext(Context context) {
 6             SecurityConstraint securityConstant = new SecurityConstraint();
 7             securityConstant.setUserConstraint("CONFIDENTIAL");
 8             SecurityCollection securityCollection = new SecurityCollection();
 9             securityCollection.addPattern("/*");
10             securityConstant.addCollection(securityCollection);
11             context.addConstraint(securityConstant);
12         }
13     };
14 
15     tomcat.addAdditionalTomcatConnectors(httpConnector());
16     return tomcat;
17 }
18 
19 @Bean
20 public Connector httpConnector() {
21     Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
22     connector.setScheme("http");
23     connector.setPort(8080);
24     connector.setSecure(false);
25     connector.setRedirectPort(8443);
26     return connector;
27 }

此时访问 http://localhost:8080 就会自动转到 https://localhost:8443

posted @ 2023-01-08 22:49  倾听-静轩水月  阅读(27)  评论(0编辑  收藏  举报