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/myapp` then/myapp` is the context path.

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

package org.kodejava.servlet;

import javax.servlet.annotation.WebServlet;
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;

@WebServlet(urlPatterns = "/context-path")
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);
    }
}

You’ll get the following information in your browser:

Context Path: /webapp

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I get servlet request URL information?

In the code example below we will extract information regarding the HTTP (Hypertext Transport Protocol) from the request object (HttpServletRequest). We will extract the protocol used (http / https), server name and its assigned port number. We will also read our application context path, servlet path, path info and the query string. If we combine all the previously mentioned information we will get something equals to the value returned by request.getRequestURL() method.

Let’s check the code snippet below to see what method of the HttpServletRequest class that we can call to get the information regarding the HTTP request object that we can collect.

package org.kodejava.servlet;

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

@WebServlet(urlPatterns = "/url-info")
public class ServletUrlInformation extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Getting servlet request URL
        String url = request.getRequestURL().toString();

        // Getting servlet request query string.
        String queryString = request.getQueryString();

        // Getting request information without the hostname.
        String uri = request.getRequestURI();

        // Below we extract information about the request object path
        // information.
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int portNumber = request.getServerPort();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        String query = request.getQueryString();

        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.print("Url: " + url + "<br/>");
        pw.print("Uri: " + uri + "<br/>");
        pw.print("Scheme: " + scheme + "<br/>");
        pw.print("Server Name: " + serverName + "<br/>");
        pw.print("Port: " + portNumber + "<br/>");
        pw.print("Context Path: " + contextPath + "<br/>");
        pw.print("Servlet Path: " + servletPath + "<br/>");
        pw.print("Path Info: " + pathInfo + "<br/>");
        pw.print("Query: " + query);
    }
}

When you access this servlet using the following url http://localhost:8080/url-info?x=1&y=1, you’ll get the following output in your browser:

Url: http://localhost:8080/url-info
Uri: /url-info
Scheme: http
Server Name: localhost
Port: 8080
Context Path:
Servlet Path: /url-info
Path Info: null
Query: x=1&y=1

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I read servlet context initialization parameters?

package org.kodejava.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/context-init-param")
public class ContextInitParameter extends HttpServlet implements Servlet {

    public ContextInitParameter() {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // Get an instance of ServletContext
        ServletContext context = getServletContext();

        // To read context initialization parameter we can call context.getInitParameter() 
        // and pass the name of initialization parameter to be read. If the named
        // parameter does not exist the returned value will be null.
        //
        // In this example we read an initialization parameter called LOG.PATH
        String logPath = context.getInitParameter("LOG.PATH");
        writer.println("Log Path: " + logPath + "<br/>");

        // Reads all the name of servlet's initialization parameters. If the
        // servlet doesn't have any an empty enumeration will be returned.
        Enumeration<String> enumeration = context.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String paramName = enumeration.nextElement();
            String paramValue = context.getInitParameter(paramName);

            writer.println("Context Init Param: [" + paramName + " = " + paramValue +
                    "]<br/>");
        }
    }
}

The context initialization parameter (context-param) look something like this in the web.xml file:

<web-app>
    ...
    <context-param>
        <param-name>locale</param-name>
        <param-value>id_ID</param-value>
    </context-param>
    <context-param>
        <param-name>LOG.PATH</param-name>
        <param-value>F:/Logs</param-value>
    </context-param>
    ...
</web-app>

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I know session last access time?

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = "SessionLastAccessTime", urlPatterns = "/last-access-time")
public class SessionLastAccessTime extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Date date = new Date(session.getLastAccessedTime());

        PrintWriter writer = response.getWriter();
        writer.println("Last accessed time: " + date);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}

This servlet will return a result like:

Last accessed time: Mon Sep 27 06:43:03 CST 2021

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I get a notification when session attribute was changed?

Implementing the HttpSessionAttributeListener will make the servlet container inform you about session attribute changes. The notification is in a form of HttpSessionBindingEvent object. The getName() on this object tell the name of the attribute while the getValue() method tell about the value that was added, replaced or removed.

package org.kodejava.servlet;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        // This method is called when an attribute is added to a session.
        // The line below display session attribute name and its value.
        System.out.println("Session attribute added: ["
                + event.getName() + "] = [" + event.getValue() + "]");
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        // This method is called when an attribute is removed from a session.
        System.out.println("Session attribute removed: ["
                + event.getName() + "] = [" + event.getValue() + "]");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        // This method is invoked when an attribute is replaced in a session.
        System.out.println("Session attribute replaced: ["
                + event.getName() + "] = [" + event.getValue() + "]");
    }
}

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central