16 - JSP Cookies Handling

16.1 Overview of JSP Cookies Handling

Cookies are small textual that is sent from server to client and then client sends back this information to same server with all subsequent requests.

There are two types of cookies:

· Session cookies - are temporary cookies and are deleted as soon as user closes the browser. The next time user visits the same website, server will treat it as a new client as cookies are already deleted.

· Persistent cookies - remains on hard drive until we delete them or they expire.

There are several benefits and usage of Cookies.

a) Remember Username and Password Several websites provides an auto login feature (Remember password) on private systems. This feature is implemented with the help of cookies.

b) Remember Preferences- Several sites uses cookies for user preferences.

c) Advertising – Several sites utilizes cookies to store the information of interested topics of user and later uses the information to display advertise.

Browsers provides options which user can use to delete or disable the cookies.

In this chapter we will discuss the how to send and read the cookies.

16.2 JSP Cookies API

JSP Specification provides a class Cookie in javax.servlet.http package .

Cookie class provides a two argument constructor (name and value of cookie) like below Cookie(String name , String value)

Following are the commonly used methods available in Cookie class.

· public void setMaxAge(int expiry)- This method sets maximum age ( in seconds )of cookie .If you don't set this, the cookie will last only for the current session.

· public int getMaxAge()- This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.

· public String getName()- This method returns the name of the cookie.

· public String getValue()- This method gets the value of the cookie.

· public void setValue(String value)- This method sets the value of the cookie.

· public void setComment(String comment)-This method specifies a comment that describes a cookie's purpose.

· public String getComment()- This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

HttpServletResponse class provides a method addCookie() to add the cookie in response and it is sent to the browser. Similarly HttpServletRequest class provides a method getCookies() to read the cookie sent by client along with request

16.3 Restricted characters in cookies

There are certain characters which cannot be used in name and value of a cookie. These characters are –

· , (Comma)

· = (equals)

· (

· )

· "

· ; (semi colon)

· [

· ]

· /

· ?

· : (colon)

· @

16.4 Sending Cookies to Client

Sending cookie to client is a three step process.

a) Create a cookie object using two argument constructor

b) You can call setMaxAge() method on cookie object created in #a if you want to make the cookie persistent.

c) Add the cookie using addCookie() method provided by HttpServletResponse object

Lets write an sendCookie.jsp which will send two cookies to client

<!DOCTYPE html>
<html>
  <head>
    <title>Send Cookie Example</title>
  </head>
  <body>
    <H1>JSP sending two cookies to client </H1>
    <%
      Cookie userIdCookie= new Cookie("userID", "guest");
      userIdCookie.setMaxAge(24*60*60);
      Cookie createdBy= new Cookie("createdBy","sendCookieJSP" );
      createdBy.setMaxAge(24*60*60);
      response.addCookie(userIdCookie);
      response.addCookie(createdBy);
    %>
  </body>
</html>

Now access sendCookie.jsp using http://localhost:8080/jsp-tutorial/sendCookie.jsp in Chrome browser

Reason I am saying Chrome because we can see the cookies sent by server to client using Google Chrome easily.

To see the cookies sent by browser, Go to

Settings à Show Advanced Settings à Privacy (Content Settings ) à All cookies and site data ...

Search for localhost and you will something like below .Here we can see the cookies sent by sendCookie.jsp . JSESSIONID is special cookie which is send by server to identify the user

         

To see the details , click on createdBy cookie to see the details

         

We can see the value sent in cookie against Content label. Similarly we can see for userID cookie

         

16.5 Reading Cookies

Reading Cookies sent by client in request is

a) Get an array of Cookies using getCookies() method of HttpServletRequest

b) Run a loop and call getName() , getValue() and getMaxAge() to see the details of cookie is sent by client.

Lets write a readCookie.jsp which will read the cookie sent by server in section 16.4

<html>
  <head>
    <title>Read Cookie Example</title>
  </head>
  <body>
    <H1>JSP Reading two cookies to client </H1>
    <table border=”1”>
     <tr>
      <td>Cookie Name </td>
      <td>Cookie Value </td>
      <td>Cookie Max Age  </td>
     </tr>
     <%
       Cookie[] cookies= request.getCookies();
       // check null because there are chances that there are no cookies
       if(cookies !=null)
       {
         for(int i=0 ;i<cookies.length;i++ )
         {
           Cookie cookie = cookies[i];
           out.println(" <tr> ");
           out.println("<td>" + cookie.getName() + "</td>" );
           out.println("<td>" + cookie.getValue() + "</td>" );
           out.println("<td>" + cookie.getMaxAge() + "</td>" );
           out.println(" </tr> ");
         }
       }
     %>
    </table>
  </body>
</html>

Now access readCookie.jsp using http://localhost:8080/jsp-tutorial/readCookie.jsp

         

You can see the cookies sent by sendCookie.jsp. This is what we discussed earlier that browser send the cookies sent by server back to server with each subsequent request.

16.6 Delete Cookies

There is no direct API which can be used to delete any cookie. In case we need to delete existing cookie , we can delete it indirectly by setting the maximum age to 0 and add it back to response.

Lets delete the one of the cookie that we sent in section 16.4 and verify if the cookie is deleted or not using readCookie.jsp

To do so let’s write a deleteCookie.jsp

<!DOCTYPE html>
<html>
  <head>
    <title>Delete Cookie Example</title>
  </head>
  <body>
    <H1>JSP deleting  userID cookie sent earlier  to client </H1>
    <%
     Cookie[] cookies= request.getCookies();
     //check null because there are chances that there are no cookies
     if(cookies !=null)
     {
       for(int i=0 ;i<cookies.length;i++ )
       {
         Cookie cookie = cookies[i];
         if(cookie.getName().equals("userID"))
         {
         cookie.setMaxAge(0);
            response.addCookie(cookie);
         }
       }
      }
    %>
  </body>
</html>

Now access deleteCookie.jsp using http://localhost:8080/jsp-tutorial/deleteCookie.jsp

         

To verify the cookie is deleted or not , again access readCookie.jsp using http://localhost:8080/jsp-tutorial/readCookie.jsp and we can see only two cookies this time.

         

16.7 Remember Username and Password Functionality

As mentioned earlier , cookies can be used to achieve remember username and password features. You must have seen this feature on several websites.

Lets create a small example

a) Create RememberMe.jsp which will have username and password fields with a Remember Me check box .This jsp will check for a cookies and if found , it will set the value of fields with the cookie values.

<html>
  <head>
   <title>Login Form</title>
  </head>
  <body>
  <%
    Cookie[] cookies = request.getCookies();
    String username="";
    String password = "";
    if(cookies!=null)
    {
      for(int i=0;i<cookies.length;i++){
        Cookie cookie = cookies[i];
        if(cookie.getName().equals("username-cookie"))
        {
            username= cookie.getValue();
        }
        else if(cookie.getName().equals("password-cookie"))
        {
            password= cookie.getValue();
        }
      }
    }
   %>
   <form name="logonform" action="displayHomePage.jsp" method="POST">
      Username: <input type="text" name="username" value ="<%= username %>"/>
      <br/>
      Password:<input type="password" name="password" value="<%= password %>"/>
      <br/>
      Remember Me<input type="checkbox" name="rememberMe" value ="true"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

b) Create displayHomePage.jsp which will display username and password .Also if the user has checked the “Remember Me” check box , this jsp will add username and password as cookie.

<html>
<head>
<title>Display Details</title>
</head>
<body>
    <%
    String username=request.getParameter("username");
    String password=request.getParameter("password");
String message="Username is : "+ username + "<br/> Password is :" + password ;
    String rememberMe=  request.getParameter("rememberMe");
    if(rememberMe!=null)
    {
        Cookie usernameCookie = new Cookie("username-cookie", username);
        Cookie passwordCookie = new Cookie("password-cookie", username);
        usernameCookie.setMaxAge(24*60*60);
        passwordCookie.setMaxAge(24*60*60);
        response.addCookie(usernameCookie);
        response.addCookie(passwordCookie);
        }
    %>    
    <strong>
    <%= message %>
    </strong>
</body>
</html>
Testing

a) Access RememberMe.jsp using http://localhost:8080/jsp-tutorial/RememberMe.jsp

         

Enter username and password and do not check the “Remember Me” check box and click submit

         

b) On submit below screen will be displayed . As “ Remember Me “ check box is not selected , cookies will not be added.

         

c) Again Access RememberMe.jsp using http://localhost:8080/jsp-tutorial/RememberMe.jsp . This time username and password field will not be auto populated because we did not check the “Remember Me ” check box in #a

         

Enter username and password and check the “Remember Me” check box and click submit

         

d) This time displayHomePage.jsp will add the cookies because “Remember Me ” is checked. On submit you will see below screen

         

e) Again Access RememberMe.jsp using http://localhost:8080/jsp-tutorial/RememberMe.jsp . This time username and password field will be auto populated because in #d , values were added in cookie

         

f) To verify if the values of username and password are correct or not , click submit

         

Like us on Facebook