Getting The Context Path (Without a HttpRequest)

Web programmers know that they shouldn’t go writing JSPs with the Context Path hard coded in them.

If you do the following:

<a href="/MyApp/path/to/controller/home.htm> Home </a>

You’ll notice that as soon as you decide to deploy your web application using a different name than “MyApp” then none of your links will work anymore.
To avoid this you need to get the context path from the HttpRequest object as follows:

<a href="<%=request.getContextPath() %>/path/to/controller/home.htm>

or by using a JSTL tag:

<a href="<c:url value="/path/to/controller/home.htm"/>"> Home </a>

What happens when you are rendering HTML in your Java code and you don’t have access to a HttpRequest object for whatever reason?

You can of course define a global property somewhere and update it whenever the application name changes. A nicer solution however would be to have the servlet context set the property automatically at startup.

To achieve this you will need to define a ServletContextListener:

public class ContextRootListener implements ServletContextListener {

	public void contextDestroyed(final ServletContextEvent event) {
	   // Do nothing

	public void contextInitialized(ServletContextEvent event) {


Note: ServletContextInfo is my property container class. It contains static getters and setters in this example.

Then you’ll need to register it as a listener in your web.xml.


After this is complete you can get the context root at anytime using the static ServletContextInfo.getContextPath() method.

Tags: , ,

Comments are closed.