java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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;

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();
    }
}