gpt4 book ai didi

java - 在 Spring Boot 2.0.4 中从 http 重定向到 https

转载 作者:行者123 更新时间:2023-12-02 00:25:39 25 4
gpt4 key购买 nike

我使用 Spring boot 2.0.4。我想为所有 url 模式配置从 http 到 https 的自动重定向。我在我的 application.yml 中添加了这一行:

server:
ssl:
enabled: true
key-alias: tomcat
key-store: "classpath:tomcat.keystore"
key-store-type: jks
key-store-password: 123456
key-password: 123456

然后我创建了 bean:

    @Bean
public TomcatServletWebServerFactory httpsRedirectConfig() {
return new TomcatServletWebServerFactory () {
@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);
}
};
}

但是,当我运行我的应用程序时,出现错误:

Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans : tomcatServletWebServerFactory,httpsRedirectConfig

怎么了?我该如何解决?谢谢。

最佳答案

尝试使用以下配置。

@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@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(redirectConnector());
return tomcat;
}

private Connector redirectConnector() {
Connector connector = new Connector(
TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}

关于java - 在 Spring Boot 2.0.4 中从 http 重定向到 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com