【发布时间】:2012-09-06 22:03:50
【问题描述】:
我正在尝试最小化我的 webapp 的配置,我想要删除的一件事是端口号映射:
- http: 80 -> https: 443
- http: 9080 -> https: 9443
由于配置已经存在于 conf/server.xml 中,我不想在我的应用程序中复制这些设置。不得不更改(并记住更改)多个配置文件是一件痛苦的事。此外,应用程序不应该关心它被部署到什么环境/容器中,只要它支持 http 和 https。
我在 web.xml 中配置了以下内容,但除了重定向之外,我还需要能够构建 https URL:
<security-constraint>
<web-resource-collection>
<web-resource-name>secure</web-resource-name>
<url-pattern>/https/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
上面的代码块告诉 servlet 容器将 http 请求重定向到它的 https 对应物。显然,Tomcat 知道请求来自哪个连接器,在 server.xml 中查找该连接器的“redirectPort”属性并使用该连接器构建 https URL。
根据这些先前/相关的问题,似乎没有标准或特定于 tomcat 的方式来获取请求的相应 https 端口:
- Tomcat: how to get the secure port number in Java?
- get server name and port number of JSP page for HTTPS
TL;DR:我的问题是,你有什么想法可以为不安全的请求获取相应的 https 端口号,而无需在 webapp 中明确配置它们?
我的一个想法是使用与当前请求相同的端口号,从 webapp 向自身发起一个 http 调用到安全约束后面的路径,并从响应中解析重定向位置。当然,响应应该被缓存。有没有更直接的方法?
编辑:添加了 answer 以及该想法的代码。
【问题讨论】:
标签: java jakarta-ee tomcat servlets