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 “”.

package org.kodejava.example.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

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

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.

Leave a Reply