How do I get web application context path in JSP?

This example show you how to obtain web application context path in JSP using Expression Language (EL) feature of JSP. To get the context path we can utilize the pageContext, it is an implicit object that available on every JSP pages. From this object you can get access to various object such as:

  • servletContext
  • session
  • request
  • response

To get the context path value you will need to read it from the request.contextPath object. This contextPath can be useful for constructing a path to you web resources such as CSS, JavaScript and images. Some libraries that you’ll need to enable the JSP Expression Language (EL) in your JSP Pages, which usually already included in a Servlet container such as Apache Tomcat including:

  • javax.servlet-api-3.0.1
  • javax.servlet.jsp-api-2.3.1
  • javax.servlet.jsp.jstl-api-1.2.1

First let’s create the index.jsp file.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
    <title>JSP - Context Path</title>

Web Application Context Path = ${pageContext.request.contextPath}

And here is you web.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>

  <!-- Config here. -->


Web Application Context Path
JSP context path example

How do I get web application context path?

The context path always comes first in a request URI. The path starts with a “/” character but does not end with a “/” character. When I have a web application with the URL like http://localhost:8080/myapps then /myapps is the context path.

For servlets in the default (root) context, this method returns "" (empty string).

package org.kodejava.example.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

public class ContextPathDemo extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        // HttpServletRequest.getContextPath() returns the portion 
        // of the request URI that indicates the context of the 
        // request.
        String contextPath = req.getContextPath();

        PrintWriter pw = res.getWriter();
        pw.print("Context Path: " + contextPath);

Register your servlet in the web.xml file and map it to the ctxpath as the url-pattern. Let say you’ve deployed your servlet into a web application named webapp then you can access your servlet using the following url: http://localhost:8080/webapp/ctxpath.

You’ll get the following information in your browser:

Context Path: /webapp