Java.Servlet.What are the methods for working with cookies provided in servlets?

🧠 In Servlets, you work with cookies using the javax.servlet.http.Cookie class.

Here’s the full list of the main methods for working with cookies:


🎯 Methods of the Cookie Class

MethodPurposeExample
getName()Get the cookie namecookie.getName()
getValue()Get the cookie valuecookie.getValue()
setValue(String value)Set/change the cookie valuecookie.setValue("newValue")
getDomain()Get the domain for the cookiecookie.getDomain()
setDomain(String pattern)Set the domain (e.g., .example.com)cookie.setDomain(".example.com")
getPath()Get the path for which the cookie is validcookie.getPath()
setPath(String uri)Set the path (e.g., /shop)cookie.setPath("/shop")
getMaxAge()Get the lifetime of the cookie in secondscookie.getMaxAge()
setMaxAge(int expiry)Set how long the cookie should live (in seconds)cookie.setMaxAge(3600)
getSecure()Check if cookie is sent only over HTTPScookie.getSecure()
setSecure(boolean flag)Force cookie to be sent only over HTTPScookie.setSecure(true)
isHttpOnly()Check if cookie is HttpOnlycookie.isHttpOnly()
setHttpOnly(boolean isHttpOnly)Set cookie as HttpOnly (inaccessible to JS)cookie.setHttpOnly(true)
toString()Get cookie info as a Stringcookie.toString()

🛠️ Other Important Servlet Methods for Working with Cookies

From HttpServletResponse:
(Used for sending cookies to the client)

MethodPurpose
addCookie(Cookie cookie)Add a cookie to the response

From HttpServletRequest:
(Used for reading cookies sent by the client)

MethodPurpose
getCookies()Returns an array of Cookie objects from the request

🚀 Full Mini Example:

Setting a cookie:

Cookie cookie = new Cookie("userName", "Alice");
cookie.setMaxAge(60 * 60); // 1 hour
cookie.setPath("/"); // Make cookie available for entire app
cookie.setSecure(true); // Send only over HTTPS
cookie.setHttpOnly(true); // Prevent JavaScript access
response.addCookie(cookie);

Reading cookies:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        if ("userName".equals(cookie.getName())) {
            String value = cookie.getValue();
            // Use value
        }
    }
}

Deleting a cookie:

Cookie cookie = new Cookie("userName", "");
cookie.setMaxAge(0); // 0 means delete immediately
cookie.setPath("/");
response.addCookie(cookie);

⚡ Quick Practical Tips:

TipWhy
Always set a path (setPath("/"))Otherwise, cookie might not be visible to all your pages
Use setHttpOnly(true) for sensitive cookiesImproves security (prevent XSS attacks)
Use setSecure(true) if your app uses HTTPSPrevents cookie leakage over HTTP
Remember cookies are small!Browsers limit cookie size (~4KB) and number of cookies

🔥 Quick Memory Trick:

Cookies in servlets = Create (addCookie), Read (getCookies), Delete (setMaxAge(0)).” 🎯

This entry was posted in Без рубрики. Bookmark the permalink.