Code Snippets: How to get the web application context path from within JSP

Often in JSP we find ourselves creating links to other pages within our web application.  The below code allows us to easily get the web application context path from within a JSP file.

${pageContext.request.contextPath}

Utilizing JSTL we could also set this value to a variable so that we have a short hand method for getting the context path.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="cp" scope="session"
        value="${pageContext.request.contextPath}" />

This enables you to use ${cp} to output the context path.

// Code Snippets // JSP //

Comments & Questions

Add Your Comment