Java – Finding your application’s URL with only a ServletContext


I'm writing a Java web app using Spring MVC. I have a background process that goes through the database and finds notifications that must be e-mailed to my users. These e-mail messages need to include hyperlinks to the application. This seems like a fairly common pattern for a web app, but I'm having trouble.

How do I derive my application's fully qualified URL, with server name and context path? I don't have access to any of the methods in HttpServletRequest because I'm running this as a background process, not in response to a web request. The best I can do is get access to ServletContext.

Currently I'm putting the base URL into a configuration file and reading it at startup, but this application is going to be licensed and deployed to customers' application servers, and if possible I'd like them not to have to configure this manually.

Best Solution

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.

Related Question