我有一个Web应用程序,用户可以在自己的Java Web服务器(例如Tomcat)上部署该应用程序。 Web应用程序的Java端需要报告Web应用程序本身的URL(例如http://aServer.com:8080/MyApp或https://blah.blahSever/MyApp)。但是,由于许多用户使用端口转发和其他网络技术,因此Web应用程序经常报告错误的名称。如何在Java 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类的获得接近我想要的,但由于我们使用的是服务器别名和的ProxyPass在我们的Apache2服务器,从InetAddress类值实际值的服务器而不是别名。
我能想到的唯一技术就是用户在属性文件中提供属性,Web应用程序在启动时读取该属性。如果该属性已设置,则此值用于返回完整的Web应用程序路径(例如serverUrl = https://blah.blahServer/MyApp)。这项技术可行,但涉及更多的客户部署工作。
有没有人有任何想法,我可以如何实现更优雅的解决方案?
感谢, 菲尔
将地址放入系统属性中并使用它。如果您将其放在不同的服务器上,请修改该属性。如果该属性未设置,则使应用程序拒绝启动。 – Kayaman
你尝试过'request.getRequestURL()'吗? –
@Mustafa Genc - 不幸的是,getRequestUrl只是简单地返回:http:// localhost:8080/MyApp/- 这是很好和完整的(它包括http和端口和Web应用程序的名称),但不幸的是返回“localhost”! – Phil