Show List

Servlet Cookies

Servlet Cookies are small pieces of data that can be stored on the client-side and used to maintain stateful interactions with a web application. Cookies are stored as key-value pairs and can be accessed by both the client and server.

Here is an example of how to create and read a cookie in a servlet:

java
Copy code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a new cookie Cookie cookie = new Cookie("username", "john"); cookie.setMaxAge(60 * 60 * 24); // set cookie to expire in 1 day response.addCookie(cookie); // Read the cookie Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals("username")) { String username = c.getValue(); // Do something with the username } } } }

In this example, we first create a new cookie using the Cookie class and set its name to "username" and value to "john". We also set the cookie's maximum age to 1 day using the setMaxAge() method.

Next, we add the cookie to the response using the addCookie() method. This sends the cookie to the client's browser, which will store it and send it back to the server on subsequent requests.

Finally, we read the cookie from the request using the getCookies() method, which returns an array of cookies sent by the client. We then loop through the array and look for a cookie with the name "username". If we find the cookie, we can retrieve its value using the getValue() method and use it for further processing.

You can also remove a cookie by setting its maximum age to 0, which will cause the client's browser to delete the cookie. Here's an example:

java
Copy code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Remove the cookie Cookie cookie = new Cookie("username", ""); cookie.setMaxAge(0); response.addCookie(cookie); }

In this example, we create a new cookie with an empty value and set its maximum age to 0. This effectively deletes the cookie from the client's browser.

In summary, Servlet Cookies are a useful mechanism for maintaining stateful interactions with a web application, and they can be easily created, read, and deleted using the methods provided by the Cookie class.


    Leave a Comment


  • captcha text