Springboot同时支持http和https访问
在Spring Boot中,要同时支持HTTP和HTTPS访问,你需要配置两个连接器,一个用于HTTP(默认端口8080),另一个用于HTTPS(需要指定端口,如443或者其他)。以下是配置的示例代码:
import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConnectorConfig {
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(8080);
return connector;
}
}
此外,确保你已经配置了SSL,并且有有效的SSL证书和私钥。Spring Boot会自动处理HTTPS请求,只要你在application.properties
或application.yml
中设置了SSL相关的属性,如下所示:
server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=yourpassword
server.ssl.key-password=yourkeypassword
或者使用YAML格式:
server:
port: 8443
ssl:
key-store: classpath:keystore.jks
key-store-password: yourpassword
key-password: yourkeypassword
确保keystore.jks
文件位于项目的类路径下,并替换yourpassword
和yourkeypassword
为你的密钥库和密钥的实际密码。
这样配置后,你的Spring Boot应用将同时支持HTTP和HTTPS访问,其中HTTP默认端口8080,HTTPS默认端口8443。
评论已关闭