Skip to main content


Showing posts from January, 2011

Calculating Domain URL in Java Web Applications

When you are developing web applications, its obvious that you’ll write code to generate paths for resources like images, stylesheets, scripts, etc. You can do this by simply using relative paths. In your JSP application, you can do this using ‘getContextPath()’ method of ‘HttpServletRequest’ object.
Lets see what this method gives you. It returns a String value, the returned string will always have a leading ‘/’ character and will never have a trailing ‘/’. This method returns an empty string when you deploy your application as ROOT context and returns the subdomain context when deployed as subdomain.
For example, if you name your WAR file as ‘myExample.war’ and deploy it in TOMCAT [by placing the WAR file in ‘webapps’ directory]. The ‘getContextPath()’ method will return ‘/myExample’.
In your JSP page, if you’ve a image tag pointing to an image resource and you want it to work even when deployed as subdomain you can do that by using this ‘getContextPath()’ method as used below.