In this tutorial, we will learn how to save and read the HTTP session state in a cookie using Servlets. By utilizing cookies, we can persist session information on the client-side, allowing us to maintain session state even if the user closes the browser or navigates away from the website. This technique can be beneficial in scenarios where session management needs to be independent of server-side storage or when working with stateless architectures. So, let’s get started!
What is a Cookie ?
A cookie is a small piece of data that is stored on the client-side (typically in the user’s web browser) by a web server. It is used to remember specific information about the user or their interactions with a website. Cookies are commonly used for session management, personalization, tracking user preferences, and maintaining stateful information.
A cookie consists of several components:
- Name: Each cookie has a unique name that identifies it.
- Value: The value represents the actual data stored in the cookie.
- Domain: The domain specifies which domain the cookie is valid for. Only websites under the specified domain can access the cookie.
- Path: The path indicates the URL path on the domain for which the cookie is valid. Cookies will be sent to the server only if the requested URL matches the specified path.
- Expiration: Cookies have an expiration date or time after which they are no longer considered valid. Once expired, the browser automatically removes the cookie.
- Secure: If the secure flag is set, the cookie will only be sent over secure connections (HTTPS).
- HttpOnly: The HttpOnly flag restricts access to the cookie through JavaScript. It helps prevent cross-site scripting (XSS) attacks.
Here is an example of how a cookie might look:
Name: sessionID Value: abc12345 Domain: example.com Path: / Expiration: Thu, 16 Jun 2023 12:00:00 GMT Secure: true HttpOnly: true
How to Set Cookies
In the following example we will show how to set some information using a Cookie in a Servlet and later retrieve this information from another Servlet.
@WebServlet(name = "CookieServlet", urlPatterns = {"/CookieServlet"}) public class SetCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Cookie cookie = new Cookie("userId","ABX123456"); cookie.setHttpOnly(true); cookie.setMaxAge(24 * 60 * 60); // Set cookie to expire after 24 hours response.addCookie(cookie); try { out.println("Cookie Set by Servlet!"); } finally { out.close(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
As you can see, in order to create a Cookie you can use the constructor of javax.servlet.http.Cookie object passing both the name and value. Next, we set call the setMaxAge and setHttpOnly methods and finally we add the Cookie to the Reponse.
Setting HTTPOnly in a Cookie
The method cookie.setHttpOnly(true)
sets the HttpOnly flag for a cookie.
The HttpOnly flag is an additional security feature for cookies. When the HttpOnly flag is set to true
, it restricts access to the cookie from client-side JavaScript. In other words, the cookie cannot be accessed or modified by JavaScript code running in the browser.
The purpose of setting the HttpOnly flag is to mitigate the risk of cross-site scripting (XSS) attacks. XSS attacks occur when an attacker injects malicious scripts into a web page, which can then access cookies containing sensitive information. By setting the HttpOnly flag, you prevent JavaScript-based code from accessing the cookie, thereby reducing the vulnerability to XSS attacks.
How to read Cookies
You can read Cookies from the HTTP’s request object, via the getCookies method:
Cookie[] cookies = request.getCookies();
You can iterate over the Cookie array to obtain each cookie and print out its contents. Here’s how to do it:
Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String name = cookie.getName(); String value = cookie.getValue(); System.out.println("Cookie Name: " + name); System.out.println("Cookie Value: " + value); } }
How to delete the Cookies from the Request
To delete all Cookies simply loop over the array of Cookies and setMaxAge to 0. For example:
Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { cookie.setMaxAge(0); response.addCookie(cookie); } }