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" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Context Path</title>
</head>

<body>
    Web Application Context Path = ${pageContext.request.contextPath}
</body>
</html>

And here is you web.xml configuration file:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>JSP Examples</display-name>
</web-app>

Web Application Context Path

JSP context path example

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

2 Comments

  1. Dear Wayan Saryada,

    I am really happy to read this and appreciate it. Could you suggest me with example.

    I have http://localhost:8085/call4admission/admin/home/home.jsp. I want to change this url to
    http://localhost:8085/call4admission/admin or http://localhost:8085/call4admission/admin/home how to do?

    Kindly Help me.
    Ranjan Kumar Gochhayat

    Reply

Leave a Reply