How do I delete a cookie in Servlet?

The Servlet API doesn’t provide a direct way to delete a cookie in a Servlet application. If you want to delete a cookie you have to create a cookie that have the same name with the cookie that you want to delete and set the value to an empty string. You also need to set the max age of the cookie to 0. And then add this cookie to the servlet’s response object.

Let’s see the code example below:

package org.kodejava.servlet;

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

@WebServlet(name = "DeleteCookieServlet", urlPatterns = "/deleteCookie")
public class DeleteCookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //
        // To delete a cookie, we need to create a cookie that have the same
        // name with the cookie that we want to delete. We also need to set
        // the max age of the cookie to 0 and then add it to the Servlet's
        // response method.
        //
        Cookie cookie = new Cookie("username", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}

Maven dependencies

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

Maven Central

How do I obtain ServletContext of another application?

The ServletContext.getContext(String uripath) enable us to access servlet context of another web application deployed on the same application server. A configuration need to be added to enable this feature.

In the example below we will forward the request from the current application to the /otherapp/hello.jsp page. We place a string in the request object attribute of the current application and going to show it in the hello.jsp page.

package org.kodejava.servlet;

import javax.servlet.RequestDispatcher;
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;
import java.io.IOException;

@WebServlet(urlPatterns = {"/context"})
public class GetAnotherContextServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get ServletContext of another application on the same Servlet
        // container. This allows us to forward request to another application
        // on the same application server.
        ServletContext ctx = request.getServletContext().getContext("/otherapp");

        // Set a request attribute and forward to hello.jsp page on another 
        // context.
        request.setAttribute("MESSAGE", "Hello There!");
        RequestDispatcher dispatcher = ctx.getRequestDispatcher("/hello.jsp");
        dispatcher.forward(request, response);
    }
}

To enable this feature in Tomcat we need to enable the crossContext attribute by setting the value to true, the default value is false. Update the server.xml file to add the following configuration inside the <Host> node.

<Context path="/webapp" debug="0" reloadable="true" crossContext="true"/>

Maven dependencies

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

Maven Central

How do I define a filter using @WebFilter annotation?

The following example show you how to create a servlet filter using the @WebFilter annotation. We will create a simple filter that will check whether an attribute is exists in the http session object. If no attribute found this filter will redirect user into a login page.

package org.kodejava.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", description = "Session Checker Filter")
public class SessionCheckerFilter implements Filter {
    private FilterConfig config = null;

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
        config.getServletContext().log("Initializing SessionCheckerFilter");
    }

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain)
            throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //
        // Check to see if user's session attribute contains an attribute
        // named AUTHENTICATED. If the attribute is not exists redirect
        // user to the login page.
        //
        if (!request.getRequestURI().endsWith("login.jsp") &&
                request.getSession().getAttribute("AUTHENTICATED") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
        chain.doFilter(req, res);
    }

    public void destroy() {
        config.getServletContext().log("Destroying SessionCheckerFilter");
    }
}

Before the birth of @WebFilter annotation as defined in the Servlet 3.0 Specification. To make the filter functional we must register it in the web.xml file by using the filter and the filter-mapping element. And once it active it will collaborate with the other filters in the filter chain for the current servlet context.

Maven dependencies

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

Maven Central

How do I define a servlet with @WebServlet annotation?

Annotations is one new feature introduces in the Servlet 3.0 Specification. Previously to declare servlets, listeners or filters we must do it in the web.xml file. Now, with the new annotations feature we can just annotate servlet classes using the @WebServlet annotation.

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
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(
        name = "HelloAnnotationServlet",
        urlPatterns = {"/hello", "/helloanno"},
        asyncSupported = false,
        initParams = {
                @WebInitParam(name = "name", value = "admin"),
                @WebInitParam(name = "param1", value = "value1"),
                @WebInitParam(name = "param2", value = "value2")
        }
)
public class HelloAnnotationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.write("<html><head><title>WebServlet Annotation</title></head>");
        out.write("<body>");
        out.write("<h1>Servlet Hello Annotation</h1>");
        out.write("<hr/>");
        out.write("Welcome " + getServletConfig().getInitParameter("name"));
        out.write("</body></html>");
        out.close();
    }
}

After you’ve deploy the servlet you’ll be able to access it either using the /hello or /helloanno url.

The table below give brief information about the attributes accepted by the @WebServlet annotation and their purposes.

ATTRIBUTE DESCRIPTION
name The servlet name, this attribute is optional.
description The servlet description and it is an optional attribute.
displayName The servlet display name, this attribute is optional.
urlPatterns An array of url patterns use for accessing the servlet, this attribute is required and should at least register one url pattern.
asyncSupported Specifies whether the servlet supports asynchronous processing or not, the value can be true or false.
initParams An array of @WebInitParam, that can be used to pass servlet configuration parameters. This attribute is optional.
loadOnStartup An integer value that indicates servlet initialization order, this attribute is optional.
smallIcon A small icon image for the servlet, this attribute is optional.
largeIcon A large icon image for the servlet, this attribute is optional.

Maven dependencies

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

Maven Central

How do I create zip file in Servlet for download?

The example below is a servlet that shows you how to create a zip file and send the generated zip file for user to download. The compressing process is done by the zipFiles method of this class.

For a servlet to work you need to configure it in the web.xml file of your web application which can be found after the code snippet below.

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@WebServlet(urlPatterns = "/zipservlet")
public class ZipDownloadServlet extends HttpServlet {
    public static final String FILE_SEPARATOR = System.getProperty("file.separator");

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // The path below is the root directory of data to be
            // compressed.
            String path = getServletContext().getRealPath("data");

            File directory = new File(path);
            String[] files = directory.list();

            // Checks to see if the directory contains some files.
            if (files != null && files.length > 0) {

                // Call the zipFiles method for creating a zip stream.
                byte[] zip = zipFiles(directory, files);

                // Sends the response back to the user / browser. The
                // content for zip file type is "application/zip". We
                // also set the content disposition as attachment for
                // the browser to show a dialog that will let user 
                // choose what action will he do to the content.
                ServletOutputStream sos = response.getOutputStream();
                response.setContentType("application/zip");
                response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");

                sos.write(zip);
                sos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Compress the given directory with all its files.
     */
    private byte[] zipFiles(File directory, String[] files) throws IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(baos)) {
            byte[] bytes = new byte[2048];

            for (String fileName : files) {
                String path = directory.getPath() +
                        ZipDownloadServlet.FILE_SEPARATOR + fileName;
                try (FileInputStream fis = new FileInputStream(path);
                     BufferedInputStream bis = new BufferedInputStream(fis)) {

                    zos.putNextEntry(new ZipEntry(fileName));

                    int bytesRead;
                    while ((bytesRead = bis.read(bytes)) != -1) {
                        zos.write(bytes, 0, bytesRead);
                    }
                    zos.closeEntry();
                }
            }

            zos.close();
            return baos.toByteArray();
        }
    }
}

Maven dependencies

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

Maven Central

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