Understanding Cookie Issuance and Retrieval with Real Code (Java × JavaScript)
In Part 1, we covered what cookies are.
In Part 2, we explored when cookies are stored and sent by browsers.
In Part 3, we’ll work with actual, runnable code to understand how cookies are handled in practice.
We’ll cover:
- Issuing cookies in Java (Servlet)
- Issuing cookies in JavaScript
- Reading cookies in Java (Servlet)
- Reading cookies in JavaScript
1. Issuing Cookies in Java (Servlet)
Based on my experience, issuing cookies in Java typically follows this flow:
- Create a cookie with new Cookie
- Set attributes such as Path, MaxAge, HttpOnly, and Secure
- Optionally set Domain
- Send it using response.addCookie()
Example: Cookie Issuance Code
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("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie tokenCookie = new Cookie("cookieName", "abcd1234");
tokenCookie.setPath("/");
tokenCookie.setMaxAge(60 * 60);
tokenCookie.setHttpOnly(true);
tokenCookie.setSecure(false);
tokenCookie.setDomain("localhost");
response.addCookie(tokenCookie);
response.setContentType("text/plain; charset=UTF-8");
response.getWriter().println("Cookie has been issued.");
}
}
Note:
In some browsers, cookies with Domain=localhost may not be stored correctly.
If that happens, omit the Domain attribute and rely on Path instead.
About Domain Configuration
Local environment
→ localhost or 127.0.0.1Production environment
→ Passed via environment variables
(e.g., System.getenv("COOKIE_DOMAIN"))
Incorrect domain settings often cause:
- Cookies being stored but not sent
- Cookies being sent but not readable
2. Issuing Cookies in JavaScript
In JavaScript, cookies are set via string assignment:
document.cookie = "key=value; Path=/; Max-Age=seconds; attributes...";
Example:
document.cookie = "cookieName=abcd1234; Path=/; Max-Age=86400; Secure";
Important notes:
- HttpOnly cannot be set from JavaScript
- Secure cookies are sent only over HTTPS
3. Reading Cookies in Java (Servlet)
Java retrieves cookies using request.getCookies().
Helper method example:
private Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
for (Cookie c : cookies) {
if (c.getName().equals(name)) {
return c;
}
}
return null;
}
Usage:
Cookie tokenCookie = getCookie(request, "cookieName");
if (tokenCookie != null) {
String token = tokenCookie.getValue();
System.out.println("Login token = " + token);
}
4. Reading Cookies in JavaScript
document.cookie returns all cookies as a single string:
cookieName=abcd1234; example=test; example1=test1
Parsing function example:
function getCookie(name) {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(name + "=")) {
return cookie.substring(name.length + 1);
}
}
return null;
}
Usage:
const token = getCookie("cookieName");
console.log("cookieName:", token);
HttpOnly cookies cannot be accessed from JavaScript.
5. Common Pitfalls in Local Development
① Secure and http://localhost
Secure cookies are sent only over HTTPS.
Local development often uses HTTP, causing cookies not to be sent.
For development, Secure=false is recommended.
If Secure=true is required in production, always test with HTTPS locally.
② SameSite=None requires Secure=true
Most modern browsers require Secure when SameSite=None is used.
③ Different ports mean different sites
localhost:3000 and localhost:8080 do not share cookies.
④ Different Path or Domain means a different cookie
Same cookie name with different Path or Domain creates separate cookies.
⑤ Browser-specific differences
Cookie visibility and tooling differ by browser, making cross-browser testing essential.
6. Summary
- Java issues cookies via new Cookie → attribute settings → response.addCookie
- Same name with different Path or Domain creates separate cookies
- JavaScript sets cookies via document.cookie
- HttpOnly cookies are invisible to JavaScript
- Local development is tricky due to Secure, SameSite, and port differences
- Browser behavior must always be considered
A Critical Security Note
Cookies are easily manipulated on the client side:
- Values can be modified
- Expiration can be extended
- Domain and Path can be changed
- Cookies can be deleted or added
- JavaScript can read/write non-HttpOnly cookies
Therefore, cookies must never be trusted as authentication proof.
Dangerous designs:
- Storing user_id directly in cookies
- Treating the existence of a cookie as authentication
A proper design requires:
- Cookies carry signed tokens (e.g., JWT)
- Authentication is verified server-side
- Token forgery is impossible even if cookies are modified
- Proper use of HttpOnly, Secure, and SameSite
Top comments (0)