In web development, a session refers to the sequence of interactions between a client (browser) and a server, starting from the moment the browser accesses the site until it is closed. Managing state during these interactions is crucial because the HTTP protocol is stateless.
The two primary technologies for session management are Cookies and Sesssions:
- Cookies: Data is stored on the client's local machine. This reduces storage load on the server but poses security risks, as users can modify or delete cookies.
- Sessions: Data is stored on the server side. This offers better security but increases server resource consumption.
Sending Cookies to the Client
To store data on the client, the server creates a Cookie object and adds it to the resposne. Key considerations include setting the persistence duration and the access path.
If a persistence time is not set, the cookie remains in the browser's memory and is destroyed when the browser closes (session-level cookie). Setting a positive lifespan persists the cookie to the disk. To delete a cookie, the server can send a cookie with the same name and path but a lifespan of zero.
public class CookieDispatchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Initialize a cookie with a key-value pair
// Note: Both name and value must be strings
Cookie itemCookie = new Cookie("product", "smartphone_x");
// Set persistence time in seconds (e.g., 2 minutes)
// This writes the cookie to the client's disk
itemCookie.setMaxAge(120);
// Define the URL path where the cookie should be sent
// If omitted, the cookie applies to the resource path where it was created
itemCookie.setPath("/myApp/dispatch");
// Attach the cookie to the HTTP response
resp.addCookie(itemCookie);
// Logic to delete a cookie (override with max-age 0)
// Cookie toDelete = new Cookie("product", "");
// toDelete.setPath("/myApp");
// toDelete.setMaxAge(0);
// resp.addCookie(toDelete);
}
}
Retrieving Cookeis from the Client
When a client sends a request, any stored cookies matching the domain and path are included in the request headers. The server retrieves these using request.getCookies().
public class CookieReceiverServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Retrieve the array of cookies from the request
Cookie[] cookieJar = req.getCookies();
if (cookieJar != null) {
for (Cookie c : cookieJar) {
// Search for a specific cookie by name
if ("product".equals(c.getName())) {
System.out.println("Value found: " + c.getValue());
break;
}
}
}
}
}
Practical Example: Tracking Last Access Time
This example demonstrates how to record and display the user's last visit time. It checks for an existing cookie representing the previous visit time, displays it, and then updates the cookie with the current timestamp.
public class VisitHistoryServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
// Retrieve existing cookies
Cookie[] cookies = req.getCookies();
String lastVisit = null;
if (cookies != null) {
for (Cookie c : cookies) {
if ("historyTime".equals(c.getName())) {
lastVisit = c.getValue();
}
}
}
// Display logic
if (lastVisit == null) {
resp.getWriter().write("Welcome, this is your first visit.");
} else {
resp.getWriter().write("Your last visit was: " + lastVisit);
}
// Create or update the cookie with current time
String currentTime = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Cookie timeCookie = new Cookie("historyTime", currentTime);
timeCookie.setMaxAge(180); // Persist for 3 minutes
resp.addCookie(timeCookie);
}
}