Finding your application's URL with only a ServletContext

It is not recommended to dynamically prepare the URL at run time, especially based on ServletRequest. This is primarily because you have no idea of the URL that users would be using to access the application - the application server could be behind a web server, a firewall or a load balancer. To keep it short, one cannot predict network topologies.

Your current technique of fetching the URL from the property file is good enough to resolve the said issue. Maybe you should look at providing an administrative console to manage the URL appearing in mails, especially if there is an admin console in place, or if there are related options that should go into one.

Edit: My last point echoes what Tony has spoken of.


Why just not have a setup web page that comes up the first time the application is run if the configuration file does not exist (in WEB-INF folder for example. Using ServletContext, you can call getRealPath and get the real path of a File and see if it exists(). If it does, redirect to the app start page, if it does not, open the admin page).

The best you cam do with ServletContext is read some settings from web.xml, and get the context path, only the HttpRequest can give you the FQ URL.


I think you can use something like:

String host = InetAddress.getLocalHost().getCanonicalHostName();
String appUrl = String.format("http://%s:%s%s", host, port, contextPath);

with port and contextPath from ServletContext.