I have a Web Application that users deploy on their own Java Web Servers (e.g. Tomcat). The Java side of Web Application needs to report the URL of the Web Application itself (e.g. http://aServer.com:8080/MyApp or https://blah.blahSever/MyApp). However since a number of users use port-forwarding and other network techniques, the Web Application often reports the wrong name.
I have tried the following techniques but often they don't actually produce what the user requires.
Note (request is an 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
The use of InetAddress gets close to what I want but since we are using Server Aliases and ProxyPass in our Apache2 server, the value from InetAddress is the actual values of the server rather than the Alias.
The only technique I can think of to get round this, is that the user provides a property in a properties file, which the Web Application reads on startup. If the property is set, this value is used to return the full web application path (e.g. serverUrl = https://blah.blahServer/MyApp) . This technique would work, but involves more deployment work for my customers.
Does anyone have any ideas as to how I can achieve a more elegant solution?
Thanks, Phil
Check the 'host' request header. Most client add that header to indicate the host they're trying to contact.
This is the same header that's used for VirtualHosts, so it's pretty standard. It's also obligatory in HTTP1.1 requests.
In fact, you cannot get the value purely from the server side, since it's possible that the user has defined its own hostname for your server.
request.getHeader("Host")
If your server is behind an apache reserve proxy, use the ProxyPreserveHost directive to make sure the Host header is kept intact. I'm sure other reverse proxies have similar options.
This solved the issue for me:
InetAddress.getLocalHost().getHostName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With