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:

mycoolapp.war
  +-resources
    +-images
    | +-logo.jpg
    +-css
    | +-common.css
    | +-login.css
    +-js
      +-jquery.min.js

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


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.


The method that has worked best for me so far is by using JSP’s 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" %>


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


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

Leave a Reply