Cookies serve as a facility for servers to send information to a client. This information is then housed on the client, from which the server can later retrieve the information. In this article, we will study the concept of saving client state with cookies using Java Servlets. I’ll walk you through an end to end example where you will store and retrieve data using cookies.
To delete a cookie, you can use the setMaxAge method of the Cookie class. Using a method argument of zero, the cookie on the client side will be effectively deleted. This is demonstrated in CookieCrumbDeleterServlet.java which is shown in Listing 4.
import java
.io.IOException; import java.io.PrintWriter; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax .servlet .http .HttpServletRequest; import javax .servlet .http .HttpServletResponse; public class CookieCrumbDeleterServlet extends HttpServlet implements Servlet { public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies = request.getCookies(); String cookieExtract = null; Cookie cookieToDelete = null; for (int i = 0; i < cookies.length; i++) { if (cookies[i] .getName() .equals("FavoriteCookieType")) { cookieToDelete = cookies[i]; // mark for deletion by client by setting max age to zero cookieToDelete .setMaxAge( 0); } } // add the cookie to the response back to the client response.addCookie( cookieToDelete); response.setContentType( "text/html"); PrintWriter out = response.getWriter(); out.println( " " + ""); out.println( " <H2>I just deleted your cookie.</H2>"); out.println(""); } public void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Listing 3: CookieCrumbDeleterServlet.java
Conclusion
Giving your clients a “memory” is a highly needed feature in many web applications. One can leverage techniques such as persisting to a database, but in many cases, one can leverage the facility of cookies which most popular browsers support. A word of caution though, many browsers give users the option to block cookies (see Figure below of Microsoft Internet Explorer’s Advanced Privacy Settings).
Figure 7: Internet Explorer Allows Users the Ability to Block Cookies
Consequently, when one designs their web applications and considers the user of cookie technology, they should take the ability for clients to block cookies and delete cookies into major consideration.