javax.servlet.http.Cookie :-


  • A cookie is a name/value (String/String) pair exchanged between client and server.
  • Cookies are created at server side and send to client by embeding them in response object. Cookies are stored at client side.
  • A cookie named JSESSIONID is automatically created by web container for each client, whenever client request comes for the first time. JSESSIONID will be unique of each client.
  • Container embeds JSESSIONID in response object and send back to client. For the next subsequent requests of the client, this JSESSIONID will be send as part of client request,to identify client uniquely.
  • In addition to this cookie, we can also make additional cookies by using javax.servlet.http.Cookie class.
  • By default a cookies exists as long as session. Cookies are destroyed as client shut down the web browser. We can make cookies availabel even after client quits the browser by using setMaxAge() method of cookie.
Note - Exchange of cookies between client and server is automatic, we do not have to do anything with that.



Cookie's methods -

Some important methods of Cookie' s are as follows -
Method name with return type Description
1- public void setMaxAge(int expiry_time) - This method is used to set the time interval (in seconds) for which cookie's exists. Specifying a negative value means cookie will exists until client quits browser.
2- public int getMaxAge() This method return the time interval for which cookie will exists. Default value will be -1, which indicates that cookie will expire as client close the web browser.
3- public String getName() This method returns the name of cookie on which it is called.
4- public void setValue(String newVal) This method is used to set a new value to a cookie.
5- public String getValue() This method is returns the value of the cookie on which it is called.


1- Creating Cookie's -

Cookie class provides the following constructor to create cookies -
public Cookie(String Cookie_name, String Cookie_value)
It creates a cookie with name and value specified by Cookie_name and Cookie_value respectively. 
For example -
Cookie c1 = new Cookie("UserName", "Admin");   
It will creates a cookie with name - UserName and value - Admin. 

2- Setting expiry time for cookie -

    c1.setMaxAge(60*60);
// c1 cookie will expire in 60*60(seconds) = 1 hour

3- Sending Cookie to client -

To send cookies to client we need to embed them in response object. HttpServletResponse provide a method named addCookie() that is used to embed cookie into response object.
Syntax -
public void addCookie(Cookie cookie_Object)  
Add the cookie specified by cookie_Object in response object
For example -
response.addCookie(c1);    

4- Getting cookies from client request -

To get all the cookies from client HttpServletRequest provides method named getCookies().
Syntax -
public Cookie[] getCookies() 
It returns all the cookies availabel in request object.   

For example -
Cookie ck[] = request.getCookies();

for(Cookie c : ck)
{
 out.println("Cookie name is - "+ c.getName());
 out.println("Cookie value is - "+ c.getValue());
}    

Example 1-

This basic example will show you, how to create cookies, how to send them to client, and how to access cookies from client.

1- index.html or index.jsp - This will be your default page.
<!DOCTYPE html>

<html>
    <head>
        <title>Cookie Demo_1</title>
    </head>
    <body>
        <form method="post" action="AddCookie">
            <table border="1px">
                <tr>
                    <td>Enter Cookie Name -</td>
                    <td><input type="text" name="t1"></td>
                </tr>
                <tr>
                    <td>Enter Cookie Value -</td>
                    <td><input type="text" name="t2"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="AddCookie"></td>
                    <td><a href="ShowCookie">Show Cookies</a></td>
                </tr>
                
            </table>
             
        </form>
    </body>
</html>    

2- Create a package named servs and within servs create the following servlets -
AddCookie Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class AddCookie extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            String nm = request.getParameter("t1");
            String val = request.getParameter("t2");
            Cookie c1 = new Cookie(nm, val);  //create cookie with specified name and value.
            c1.setMaxAge(60*60); // Cookie will expire after 1 hour.
            response.addCookie(c1);  // embed cookie in response object. 
            response.sendRedirect("index.html"); // go back to index.html page.
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

ShowCookie Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowCookie extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            Cookie ck[] = request.getCookies();
            for(Cookie c: ck)
            {
                out.println("Cookie name - "+c.getName()+"<br>");
                out.println("Cookie value - "+c.getValue()+"<br>");
            }
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

3- web.xml - Add the following code in web.xml file -
<web-app>
    <servlet>
        <servlet-name>AddCookie</servlet-name>
        <servlet-class>servs.AddCookie</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ShowCookie</servlet-name>
        <servlet-class>servs.ShowCookie</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddCookie</servlet-name>
        <url-pattern>/AddCookie</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ShowCookie</servlet-name>
        <url-pattern>/ShowCookie</url-pattern>
    </servlet-mapping>
</web-app>    

4- Now run your project and it will show you default page, enter cookie name and value, and press AddCookie button -



Request will go to AddCookie servlet, It wil create cookie and embed cookie in servlet response and send back to client.
Now click on ShowCookie and it will show you the name and value of cookie entered by you -



Example 2 -

This example will ask for username and password and store them in cookies if user enter correct username and password and RememberMe checkbox is clicked. And use them for automatic login if user does not logout or cookies does not expire.
(Like in facebook, if you exit from your facebook account without proper logout, and after sometime again enter facebook url, it will redirect you to your home page without asking username and password.)

1- index.html or index.jsp -
<!DOCTYPE html>
<html>
    <head>
        <title>CookieDemo_2</title>
    </head>
    <body>
          <form method="get" action="LoginCheck">
            <table border="1px">
                <tr>
                    <td>Enter UserName -</td>
                    <td><input type="text" name="t1"></td>
                </tr>
                <tr>
                    <td>Enter Password -</td>
                    <td><input type="password" name="t2"></td>
                </tr>
                <tr>
                    <td>Remember Me -</td>
                    <td><input type="checkbox" name="t3" value="yes"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login"></td>
                    <td><input type="reset" value="Reset"></td>
                </tr>
                
            </table>
             
        </form>
    </body>
</html>    

2- Create a package named servs and within servs create the following servlets -
LoginCheck Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginCheck extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession();
            
            String nm = request.getParameter("t1");
            String ps = request.getParameter("t2");
            String rem = request.getParameter("t3");
            if(nm.equals("admin") && ps.equals("123"))
            {
                session.setAttribute("User", nm);
                session.setMaxInactiveInterval(60*60*24);
                if(rem != null)
                {
                    Cookie c1 = new Cookie("username", nm);
                    Cookie c2 = new Cookie("password", ps);
                    c1.setMaxAge(60*60*24);
                    c2.setMaxAge(60*60*24);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                response.sendRedirect("Home");
            }
            else
            {
                out.println("<h1 style = 'color:red'>Wrong username or password</h1>");
                RequestDispatcher rdp = request.getRequestDispatcher("index.html");
                rdp.include(request, response);
            }
            
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Home Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Home extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            HttpSession session = request.getSession();
            if(session.getAttribute("User") == null)
            {
                response.sendRedirect("index.html");
            }
            PrintWriter out = response.getWriter();
            out.println("<h1 style='text-align:center; padding:10px'>Welcome to Home</h1>");
            out.println("<hr>");
            out.println("<a href = 'Gallery'>Gallery</a>");
            out.println("<a href = 'Logout'>Logout</a>"); 
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Gallery Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Gallery extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            HttpSession session = request.getSession();
            if(session.getAttribute("User") == null)
            {
                response.sendRedirect("index.html");
            }
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to Gallery</h1>");
            
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Logout Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Logout extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
         try
        {
            HttpSession session = request.getSession();
            session.invalidate();
            Cookie c1 = new Cookie("username", "");
            Cookie c2 = new Cookie("password", "");
            c1.setMaxAge(-1);
            c2.setMaxAge(-1);
            response.addCookie(c1);
            response.addCookie(c2);
            response.sendRedirect("index.html");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Welcome Servlet - It will be your default page.


package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Welcome extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
       try
       {
           String username = "";
           String password = "";
           Cookie ck[] = request.getCookies();
           if(ck != null)
           {
               for(Cookie c : ck)
               {
                   if(c.getName().equals("username"))
                   {
                       username = c.getValue();
                   }
                   if(c.getName().equals("password"))
                   {
                       password = c.getValue();
                   }
               }
               
           }
           if(username.equals("") && password.equals(""))
               {
                   response.sendRedirect("index.html");
               }
               else
               {
                  response.sendRedirect("LoginCheck?t1="+username+"&t2="+password+"&t3=yes"); 
               }
       }
       catch(Exception ex)
       {
           System.out.println(ex);
       }
    }
}
    

3- web.xml Add Servlet information in web.xml and change default page to Welcome Servlet as follows -
<web-app>
    <servlet>
        <servlet-name>LoginCheck</servlet-name>
        <servlet-class>servs.LoginCheck</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Home</servlet-name>
        <servlet-class>servs.Home</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Gallery</servlet-name>
        <servlet-class>servs.Gallery</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Logout</servlet-name>
        <servlet-class>servs.Logout</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Welcome</servlet-name>
        <servlet-class>servs.Welcome</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginCheck</servlet-name>
        <url-pattern>/LoginCheck</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Home</servlet-name>
        <url-pattern>/Home</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Gallery</servlet-name>
        <url-pattern>/Gallery</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Logout</servlet-name>
        <url-pattern>/Logout</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Welcome</servlet-name>
        <url-pattern>/Welcome</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>Welcome</welcome-file>
    </welcome-file-list>
</web-app>        

Program Structure -



when user will run the project, he will be redirected to welcome servlet. Welcome servlet checks whether cookies exists for this user or not. If cookies do not exists, it will redirect user to index.html login form, otherwise it will redirect user directly to LoginCheck with username and password extrexted from cookies.
If username and password are valid, user will enter to Home page. Home conatin a Logout link, that will expire user cookies and session, and redirect user to index.html Login form.
If user close the browser without proper Logout, cookies will remain alive for 24 hours.And if user run the project again within 24 hours , it will directly takes the user to Home page without asking for username and password.

4- Now run your project, and it will ask for username and password, enter username and password (admin/123 in our example) and check RememberMe checkbox and click Login button.



It will create two cookies to hold username and password entered by user, and cookies will remains alive till 24 hour if user does not press logout button.