Servlet Cookies

 A Servlet in Java is a server-side program that handles client requests and responses in a web application. Cookies in a servlet are typically used for storing small pieces of data on the client’s browser, which can later be retrieved when needed. A cookie is a small piece of information sent from the server to the client's browser, which stores it and sends it back with subsequent requests.

Below is a basic example of how to work with cookies in a Java Servlet:

Steps:

  1. Set a Cookie (Sending from the server to the client)
  2. Read a Cookie (Retrieving the cookie from the client on subsequent requests)

Example Servlet for Cookies:

1. Setting a Cookie in the Servlet:

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import javax.servlet.annotation.*; @WebServlet("/SetCookieServlet") public class SetCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the writer to send response PrintWriter out = response.getWriter(); // Create a cookie with a name and value Cookie userCookie = new Cookie("username", "john_doe"); // Set the cookie to expire in 30 minutes (1800 seconds) userCookie.setMaxAge(1800); // Add the cookie to the response response.addCookie(userCookie); // Output the response out.println("<html><body>"); out.println("<h2>Cookie has been set!</h2>"); out.println("<p>Cookie 'username' set with value 'john_doe'.</p>"); out.println("</body></html>"); } }

2. Reading a Cookie in the Servlet:

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import javax.servlet.annotation.*; @WebServlet("/GetCookieServlet") public class GetCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the writer to send response PrintWriter out = response.getWriter(); // Retrieve all cookies from the request Cookie[] cookies = request.getCookies(); if (cookies != null) { boolean cookieFound = false; // Loop through the cookies to find the 'username' cookie for (Cookie cookie : cookies) { if ("username".equals(cookie.getName())) { String username = cookie.getValue(); out.println("<html><body>"); out.println("<h2>Cookie Found!</h2>"); out.println("<p>Welcome back, " + username + "!</p>"); out.println("</body></html>"); cookieFound = true; break; } } if (!cookieFound) { out.println("<html><body>"); out.println("<h2>No 'username' cookie found.</h2>"); out.println("</body></html>"); } } else { out.println("<html><body>"); out.println("<h2>No cookies found.</h2>"); out.println("</body></html>"); } } }

Key Points:

  • Setting a Cookie: You use response.addCookie(Cookie cookie) to send the cookie from the server to the client. You can also set expiration time using cookie.setMaxAge(int seconds).
  • Reading a Cookie: You retrieve cookies with request.getCookies(), which returns an array of Cookie objects. You can then iterate through them to find a specific cookie.
  • Cookie Expiration: A cookie will expire after the time specified in setMaxAge. If you set it to 0, the cookie is deleted.
  • Cookie Attributes: You can set additional attributes like path, domain, secure flag, and HttpOnly flag.

Notes:

  • Cookies are stored on the client's browser, and they can be viewed or deleted by the user. Therefore, they are not meant to store sensitive or large amounts of data.
  • If the browser does not have cookies enabled, the servlet will not be able to store or retrieve cookies.

Comments