Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the server name in a Java Web Application

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

like image 672
Phil Avatar asked Jan 31 '14 14:01

Phil


2 Answers

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.

like image 196
Joeri Hendrickx Avatar answered Sep 28 '22 12:09

Joeri Hendrickx


This solved the issue for me:

InetAddress.getLocalHost().getHostName();
like image 45
Vasudev Avatar answered Sep 28 '22 14:09

Vasudev