How do I send a cookie in Servlet?

A cookie is a piece of information sent to a browser by a Web Server. The browser then returns that information to the Web server. This is how some Web pages remember your previous visits; for example, an e-commerce website might use a cookie to remember which items you’ve placed in your online shopping cart. Cookies can also store user preference information, login data, etc.

Here is an example to send a cookie in the HTTP response object to the client browser.

package org.kodejava.servlet;

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

@WebServlet(name = "CookieServlet", urlPatterns = "/test-cookie")
public class WriteCookieExample extends HttpServlet {

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        // Send a cookie named username to the client. There are some others
        // properties that we can set before we send the cookie, such as comments,
        // domain name, max age, path, a secure flag, etc.
        Cookie cookie = new Cookie("username", "jduke");
        response.addCookie(cookie);
    }
}

Maven dependencies

<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.