Looking Up Context Path On a JSP Page

Supposed you have a cool web application running on http://mycompany.com/mycoolapp and you have few static resources such as CSS, images and javascripts under resources folder:

    | +-logo.jpg
    | +-common.css
    | +-login.css

One common issue that appear is you can’t simply reference these static resources using relative path from your JSP page like this:

<img src="resources/images/logo.jpg"/>

Although in many cases it works fine, but if you have multi level URLs like http://mycompany.com/mycoolap/login, http://mycompany.com/mycoolap/users/1234 the relative path would be different for each, which means your code isn’t reusable.

Putting a slash “/” in front of the path to make it semi-absolute isn’t always a good idea either because if the context-path name changes all your references are broken.

<img src="/mycoolapp/resources/images/logo.jpg"/>

The method that has worked best for me so far is by using JSP’s <c:set ..> tag. First ensure you have declared the jstl core tag at the top of your JSP page, and create a “root” variable like this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="root" value="${pageContext.request.contextPath}"/>

Now the JSP variable “root” always refers to your context path, you can use it to reference your static resource like this:

<img src="${root}/resources/images/logo.jpg"/>

One thought on “Looking Up Context Path On a JSP Page

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s