Implementing Cookie using Servlets

A cookie is a piece of data passed between a Web server and a Web browser. The Web server sends a cookie that contains data it requires the next time the browser accesses the server. This is one way to maintain state between a browser and a server.

The CookieServlet (See exaample) demonstrates a servlet which gets and sets a cookie stored at a client. Initially, the browser may not have sent the cookie as part of the request, (for example, the first time it is called), so we just initialize a local calledCount variable to 0. If we are able to get this cookie from the request, we set the local calledCount to the value of the cookie.

The servlet first tries to get the calledCount by iterating through the cookies it received as part of the request. If no cookie contains the calledCount item, then the servlet initializes the calledCount value to 0. This value is then incremented, and a new cookie instance is created for calledCount and added to the response.

If we call this servlet from a URL, we find that the first time we call it, the calledCount is 0. Subsequent calls to the same servlet from this Web browser will show that we keep incrementing the counter, and storing it into the cookie sent back to the browser.

This is one way by which we can maintain state between the Web browser and the server. The major drawback with cookies is that most browsers enable the user at the client machine to deactivate (not accept) cookies.

Example- State tracking using cookies
package itso.servjsp.servletapi;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int calledCount = 0;
PrintWriter out = res.getWriter();
out.println("<H2>Servlet Cookie Example:</H2><HR>");
if (getReqCookie(req, out, "calledCount") == null)
calledCount = 0;
calledCount = new Integer(getReqCookie(req, out,
out.print("The value of the cookie calledCount sent in on the request: ");
if (calledCount == 0) out.println
("null - value not sent in on request<HR>");
else out.println(calledCount + "<HR>");
Cookie cookie = new Cookie("calledCount",
new Integer(calledCount).toString());
out.println("The value of the cookie calledCount set on the response: " +
private String getReqCookie(HttpServletRequest req, PrintWriter out,
String name) {
Cookie[] cookies = req.getCookies();
if (cookies != null && cookies.length > 0) {
for(int i=0; i<cookies.length; i++) {
if (cookies[i].getName().equals(name))
return (cookies[i].getValue());
return null;
Share this article :
Copyright © 2012. Best Online Tutorials | Source codes | Programming Languages - All Rights Reserved