Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How Java Cookies helps in storing user’s information

Today we are going to learn “Cookies in Java”. We are going to learn how a server identifies a new/frequent user of a particular domain, remembers username and password at client side.

What are Cookies?

A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. This is useful for having the browser remember some specific information.

Why we use Cookies?

  1. Identifying a user during an e-commerce session: Many on-line stores use a "shopping cart" metaphor in which the user selects an item, adds it to his shopping cart, then continues shopping. Since the HTTP connection is closed after each page is sent, when the user selects a new item for his cart, how does the store know that he is the same user that put the previous item in his cart? Cookies are a good way of accomplishing this task.
  2. Avoiding username and password: Many large sites require we to register in order to use their services, but it is inconvenient to remember the username and password for each services. Cookies are a good alternative for low-security sites. When a user registers, a cookie is sent with a unique user ID. When the client reconnects at a later, the user ID is returned; the server looks it up, determines it belongs to a registered user, and doesn't require an explicit username and password.
  3. Customizing a site: Many "portal" sites let we customize the look of the main page. They use cookies to remember what we wanted, so that we get the same result next time.

Types of Cookies:

There are two types of cookies as follows:

  • Session cookies: Session cookies are stored in memory and are accessible as long as the user is using the web application. Session cookies are lost when the user exits the web application. Such cookies are identified by a session ID and are most commonly used to store details of a shopping cart.
  • Persistent cookies: Persistent cookies are also known as Permanent cookies. Persistent cookies are used to store long-term information such as user preferences and user identification information. Permanent cookies are stored in persistent storage and are not lost when the user exits the application. Persistent cookies are lost when they expire.
  • Sending and Receiving Cookies: To send cookies to the client, a servlet should use the Cookie constructor to create one or more cookies with designated names and values and insert the cookies into the HTTP response headers with response.addCookie.

To read incoming cookies, a servlet should call request.getCookies, which returns an array of Cookie objects corresponding to the cookies the browser has associated with our site (null if there are no cookies in the request). In most cases, the servlet should then loop down this array calling getName() on each cookie until it finds the one whose name matches the name it was searching for, then call getValue() on that Cookie to see the value associated with the name.

Sending Cookies to the Client:

Sending cookies to the client involves three steps:

  1. Creating a Cookie object: We call the Cookie constructor with a Cookie name and a cookie value, both of which are strings.
  2. Setting the maximum age: If we want the browser to store the cookie on disk instead of just keeping it in memory, we use SetMaxAge to specify how long (in seconds) the cookie should be valid.
  3. Placing the Cookie into the HTTP response headers. We use Response.addCookie to accomplish this. If we forget this step, no Cookie is sent to the browser.

Creating a Cookie Object:

We create a cookie by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain white space or any of the following characters:

[ ] ( ) = , " / ? @ : ;

Cookie  userCookie = new Cookie("userID", "a1234");

Setting the Maximum Age:

If we create a cookie and send it to the browser, by default it is a session-level cookie: a cookie that is stored in the browser’s memory and deleted when the user quits the browser. If we want the browser to store the cookie on disk, use setMaxAge with a time in seconds, as below.

UserCookie. setMaxAge(60*60*24*365);

Validity of this cookie is 1 year.

Adding a Cookie:

We can add the created cookie into HTTP Response Headers. This is an optional step and if we did not use it cookie is stored at the browser.

response.addCookie(userCookie);

Reading Cookies from the Client:

To send a cookie to the client, we create a Cookie, set its maximum age (usually), and then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, we should perform the following two tasks:

  1. Call request.getCookies: This yields an array of Cookie objects.
  2. Loop down the array, calling getName on each one until us find the cookie of our use.

Call request.getCookies:

To obtain the cookies that were sent by the browser, we call getCookies on the HttpServletRequest. This call returns an array of Cookie objects corresponding to the values that came in on the Cookie HTTP request headers. If the request contains no cookies, getCookies should return null.

Loop Down the Cookie Array:

Once we have the array of cookies, we typically loop down it, calling getName on each Cookie until we find matching one.

Cookies are specific to our host (or domain), not our servlet (or JSP page).

Example:

String cookie Name = "userID";
Cookie[] cookies = request.getCookies();
if (cookies != null)
 {
         for(int i=0; i<cookies. length; i++) 
        {
                     Cookie cookie = cookies[i];
                    if (cookieName.equals(cookie.getName())) 
                    doSomethingWith(cookie.getValue());
         }
}

We present two utilities that simplify retrieving a cookie or cookie value that matches a designated cookie name.

Listing 1: Program to demonstrate cookie in java

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

public class CookieDemo extends HttpServlet
{
    public void doGet(HttpServletRequest request, 
                      HttpS   ervletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        Cookie[] cookies = request.getCookies();
        boolean foundCookie = false;

        for(int i = 0; i < cookies.length; i++)
        { 
            Cookie cookie1 = cookies[i];
            if (cookie1.getName().equals("color"))
            {
                out.println("bgcolor = " + 
                           cookie1.getValue());
                foundCookie = true;
            }
        }  

        if (!foundCookie)
        {
          Cookie cookie1=new Cookie("color", "cyan");
          cookie1.setMaxAge(24*60*60);
           response.addCookie(cookie1); 
        }
                          out.println("This page will set its background color using a cookie when reloaded.");
   }
}

Output of the Program is:

This page will set its background color using a cookie when reloaded.

Listing 2: Program to check Repeat Visitors using Cookie

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

/* Servlet that says "Welcome aboard" to first-time
 * visitors and "Welcome back" to repeat visitors.
 * Also see RepeatVisitor2 for variation that uses
 * cookie utilities from later in this chapter.
 */

public class RepeatVisitor extends HttpServlet
{
 public void doGet(HttpServletRequest request,
                                    HttpServletResponse response) throws                   ServletException, IOException
 {
                  boolean newbie = true;
                 Cookie[] cookies = request.getCookies();
                 if (cookies != null) 
                  {
                         for(int i=0; i<cookies.length; i++) 
                        {
                             Cookie c = cookies[i];
                            if ((c.getName().equals("repeatVisitor")) &&
                                          (c.getValue().equals("yes"))) 
                              {
                                        newbie = false;
                                         break;
                             }
                     }
   }
        String title;
        if (newbie) 
      {
        Cookie returnVisitorCookie= new Cookie("repeatVisitor",                 "yes");
         returnVisitorCookie.setMaxAge(60*60*24*365); // 1 year
          response.addCookie(returnVisitorCookie);
         title = "Welcome Aboard";
      } 
     else
    {
          title = "Welcome Back";
    }
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 String docType =
 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
 "Transitional//EN\">\n"; 
out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" +
 "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
 "</BODY></HTML>");
   }
}

Output of the Program is:

For New Users.....
Welcome Aboard

For Repeated User.....
Welcome back

Disadvantages of Cookies:

  1. Fundamental disadvantage is as per the definition it cannot send the huge amount of data.
  2. More amounts of data will be transferred between the browser and server.
  3. In case of some browser softwares we have an option to disable cookies, for example in case NetscapeCommunicator we have an option to disable cookies, in such cases our application fails.

Conclusion:

Customers using cookies can take advantage of the cookie support in Java Plug-in when deploying Java applets or beans within their enterprise. Java Plug-in recognizes and works seamlessly in our enterprise environment with our browser's cookie policy.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login