Understanding Cookies: Concepts, HTTP Transmission, and Java Servlet/JSP Implementation
This article explains what cookies are, how they are represented and transmitted in HTTP, their lifecycle, common attributes, and demonstrates practical usage with Java's Cookie API, JSP pages, and servlet code to achieve automatic login and session management.
Cookies are small text files stored on the client that contain key‑value pairs such as name=jack . They enable browsers to remember information like login status, so a user who has previously logged into a site (e.g., Bilibili or CSDN) can be recognized without re‑entering credentials.
The browser receives cookies from the server via the Set‑Cookie header in an HTTP response. When making subsequent requests, the browser includes all cookies whose Path matches the request URL, concatenated as Cookie: name1=value1; name2=value2 .
Cookie attributes include:
Name : the cookie's identifier.
Value : the stored data.
Path : the URL path for which the cookie is sent.
Expires : the expiration timestamp; after this the cookie is invalid.
Size : the length of the cookie string.
Cookies can be session (kept in memory and discarded when the browser closes) or persistent (saved on disk until the expiration time or manual deletion).
In Java, the javax.servlet.http.Cookie class provides methods such as:
new Cookie(String name, String value) – create a cookie.
getName() and getValue() – retrieve its name and value.
setMaxAge(int seconds) – define lifetime (‑1 for session, 0 to delete, positive for seconds).
setPath(String path) – limit the cookie to a specific URL scope.
Typical servlet operations are:
response.addCookie(Cookie cookie) – send a cookie to the client.
request.getCookies() – obtain all cookies sent by the client.
A simple JSP login page can be written as:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head><title>登录</title></head>
<body>
<form action="${pageContext.request.contextPath}/main" method="post">
用户名:<input type="text" name="username" value="<%=request.getAttribute("username")%>"><br>
密码:<input type="password" name="password" value="<%=request.getAttribute("password")%>"><br>
<input type="submit" value="登录">
</form>
</body>
</html>The corresponding servlet that reads existing cookies, forwards to the JSP, and creates new cookies after a successful login looks like:
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/cookieLogin")
public class CookieLogin extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("username", "");
request.setAttribute("password", "");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
request.setAttribute("username", cookie.getValue());
}
if ("password".equals(cookie.getName())) {
request.setAttribute("password", cookie.getValue());
}
}
}
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
@WebServlet("/main")
public class MainServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("root".equals(username) && "root".equals(password)) {
Cookie usernameCookie = new Cookie("username", username);
Cookie passwordCookie = new Cookie("password", password);
int threeDays = 60 * 60 * 24 * 3;
usernameCookie.setMaxAge(threeDays);
passwordCookie.setMaxAge(threeDays);
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
response.getWriter().write("
登录成功~~~~
");
} else {
response.getWriter().write("
登录失败....
");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}After a successful login, the browser stores the username and password cookies. When the user revisits the login page (even after closing the browser), the servlet reads these cookies and pre‑fills the form, achieving automatic login.
In summary, cookies are a fundamental mechanism for preserving state between client and server, enabling features such as auto‑login, session tracking, and user preferences. Proper use of cookie attributes and lifecycle management is essential for secure and reliable web applications.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.