How does Cookies work in Servlets?
Cookies are small pieces of data stored on the client side, typically in the web browser, and sent to the server with every HTTP request. They are used to maintain state and user information between requests in web applications, which are inherently stateless. In Java Servlets, cookie are managed through the javax.servlet.http.Cookie class.
Cookies have several properties, including:
- Name : The name of the cookie.
- Value : The value associated with the cookie name.
- Domain : The domain to which the cookie is sent.
- Path : The specific path within the domain to which the cookie is sent.
- Max-Age : The lifespan of the cookie, in seconds. A positive value indicates the cookie will expire after the specified seconds, a zero value means the cookie should be deleted, and a negative value indicates the cookie is a session cookie and will be deleted when the browser is closed.
- Secure : If true, the cookie will only be sent over secure (HTTPS) connections.
- HttpOnly : If true, the cookie is inaccessible to JavaScript, enhancing security.
Table of Contents
Step 1: Setting a Cookie
To set a cookie, you create a Cookie object and add it to the HttpServletResponse object.
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Create a new cookie
Cookie userCookie = new Cookie("username", "JohnDoe");
// Set the cookie to expire in 1 hour
userCookie.setMaxAge(60 * 60);
// Add the cookie to the response
response.addCookie(userCookie);
response.setContentType("text/html");
response.getWriter().println("Cookie set with username.");
}
}
Step 2: Retrieving a Cookie
To retrieve a cookie, you get all cookie from the HttpServletRequest object and then search for the specific cookie by name.
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get all cookies from the request
Cookie[] cookies = request.getCookies();
String username = null;
// Loop through the cookie to find the one with name "username"
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
username = cookie.getValue();
break;
}
}
}
response.setContentType("text/html");
if (username != null) {
response.getWriter().println("Welcome back, " + username + "!");
} else {
response.getWriter().println("No username cookie found.");
}
}
}
Step 3: Deleting a Cookie
To delete a cookie, you create a new Cookie object with the same name and set its maxAge to zero.
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DeleteCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Create a new cookie with the same name
Cookie userCookie = new Cookie("username", "");
// Set the cookie to expire immediately
userCookie.setMaxAge(0);
// Add the cookie to the response
response.addCookie(userCookie);
response.setContentType("text/html");
response.getWriter().println("Username cookie deleted.");
}
}
Summary
- Setting a Cookie : Create a Cookie object, set its properties, and add it to the response.
- Retrieving a Cookie : Get all cookie from the request and search for the desired one by name.
- Deleting a Cookie : Create a new Cookie object with the same name, set its maxAge to zero, and add it to the response.
Cookie are a powerful way to maintain state and user information across multiple requests in a web application. They are widely used for session management, user preferences, and tracking user activities.