This section describe you how to get the contextPath of web application.



In this section we will learn about how to get the contextPath of a web application from HttpServletRequest object.

An application server may host more than one web application. ContextPath of a web application is the name of the application in the URI just after the port number followed by a /(black slash). In a Servlet you can get the contextPath using the HttpServletRequest object. In a JSP page you can get the contextPath in two ways. In a first method you can use the implicit request object and in the second method you can use JSP EL.

We will illustrate this concept using a simple example. We will use Eclipse to compile and the Tomcat 7 to deploy the application.


We will understand this concept with a simple example. We will give here a simple example which will demonstrate you how to get the contextPath in Servlet as well as in JSP. Here we are going to give a simple dynamic project into which we will create a Servlet into which we will use the HttpServletRequest object to get the contextPath. We will also create the JSP page to get the contextPath. In the JSP page we will use both of the methods of getting contextPath i.e. using JSP EL and implicit object request.

Directory Structure

package net.roseindia;

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

public class ContextPathExample extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
		PrintWriter out = response.getWriter();
		String contextPath = request.getContextPath();
		out.println("Context Path = "+contextPath);


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
<!-- <display-name>contextPathExample</display-name>-->



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Context Path Example</title>
Context Path Using implicit request object = "<%=request.getContextPath() %>"
Context Path Using JSP EL = "${pageContext.request.contextPath}"


When you will compile and deploy the example and execute the Servlet then the output will be as follows :

When you will compile and deploy the JSP page then the output will be as follows :

Download Source Code