【发布时间】:2014-01-31 14:09:46
【问题描述】:
我有一个用户部署在他们自己的 Java Web 服务器(例如 Tomcat)上的 Web 应用程序。 Web 应用程序的Java 端需要报告Web 应用程序本身的URL(例如http://aServer.com:8080/MyApp 或https://blah.blahSever/MyApp)。然而,由于许多用户使用端口转发和其他网络技术,Web 应用程序经常报告错误的名称。
我尝试了以下技术,但通常它们实际上并不能产生用户需要的东西。
注意(请求是一个HttpServletRequest)
request.getLocalAddr(); // Returns: 127.0.0.1
request.getLocalName(); // Returns: localhost
request.getServerName(); // Returns: localhost
request.getServerPort(); // Returns: 8080
request.getContextPath(); // Returns: /MyApp
request.getScheme(); // Returns: http
InetAddress.getLocalHost().getHostName(); // Returns: serverXXX-XXX-XXX-XX.xxxx-xxxxxxx.net
InetAddress.getLocalHost().getHostAddress(); // Returns: xxx.xxx.xxx.xxx (ip address)
InetAddress.getLocalHost().getCanonicalHostName(); // Returns: serverXXX-XXX-XXX-XX.xxxx-xxxxxxx.net
InetAddress 的使用接近我想要的,但由于我们在 Apache2 服务器中使用服务器别名和 ProxyPass,所以来自 InetAddress 的值是服务器的实际值而不是别名。
我能想到的解决这个问题的唯一技术是,用户在属性文件中提供一个属性,Web 应用程序在启动时读取该属性。如果设置了该属性,则此值用于返回完整的 Web 应用程序路径(例如 serverUrl = https://blah.blahServer/MyApp)。这种技术可行,但需要为我的客户做更多的部署工作。
有人对我如何实现更优雅的解决方案有任何想法吗?
谢谢, 菲尔
【问题讨论】:
-
将地址放在系统属性中并使用它。如果您将其放在不同的服务器上,请修改该属性。如果未设置该属性,则使应用拒绝启动。
-
你试过
request.getRequestURL()吗? -
@Mustafa Genc - 不幸的是 getRequestUrl 只是简单地返回:localhost:8080/MyApp - 这很好且完整(它包括 http 和端口以及 Web 应用程序名称),但不幸的是返回“localhost”!
-
@Kayaman - 我认为您的方法可能是我所采用的方法!
-
@Phil 这绝对是最简单(而且效果很好,除非你经常切换域名)的方法。
标签: java web-applications