title: How to get the server name in a Java Web Application
body: <p>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. <a href="http://aServer.com:8080/MyApp" rel="noreferrer">http://aServer.com:8080/MyApp</a> or <a href="https://blah.blahSever/MyApp" rel="noreferrer">https://blah.blahSever/MyApp</a>). However since a number of users use port-forwarding and other network techniques, the Web Application often reports the wrong name.</p>
  
  <p>I have tried the following techniques but often they don't actually produce what the user requires. </p>
  
  <p>Note (request is an HttpServletRequest) </p>
  
  <pre><code>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
  </code></pre>
  
  <p>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.</p>
  
  <p>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 = <a href="https://blah.blahServer/MyApp" rel="noreferrer">https://blah.blahServer/MyApp</a>) . This technique would work, but involves more deployment work for my customers.</p>
  
  <p>Does anyone have any ideas as to how I can achieve a more elegant solution?</p>
  
  <p>Thanks,
  Phil</p>