2017-05-05

Understanding Java cookies with example

Cookies are process stored data on the client computer browser and they are kept for various information tracking purpose. Static content are form server side pushed into client machine, so that its process and load data faster.

Step to Sending Cookies to the Client

Sending cookies to the client involves three steps

1. Creating a Cookie object:
      You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

2. Setting the maximum age:
      If you want the browser to store the cookie on disk instead of just keeping it in memory, you use         setMaxAge to specify how long (in seconds) the cookie should be valid.

3. Placing the Cookie into the HTTP response headers:
    You use response.addCookie to accomplish this. If you forget this step, no cookie is sent to the            browser



Creating a Cookie Object

      You 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:
[ ] ( ) = , " / ? @ : ;

For example, to create a cookie named userID with a value a1234, you would use the following.
Cookie c = new Cookie("userID", "a1234");

Setting the Maximum Age

If you 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 you want the browser to store the cookie on disk, use setMaxAge with a time in seconds, as below.

c.setMaxAge(60*60*24*7); // One week

Setting the maximum age to 0 instructs the browser to delete the cookie and it is treated as temporary cookie.

Placing the Cookie in the Response Headers

By creating a Cookie object and calling setMaxAge, all you have done is manipulate a data structure in the server’s memory. You haven’t actually sent anything to the browser. If you don’t send the cookie to the client, it has no effect. This may seem obvious, but a common mistake by beginning developers is to create and manipulate Cookie objects but fail to send them to the client. To send the cookie, insert it into a Set-Cookie HTTP response header by means of the addCookie method of HttpServletResponse. The method is called addCookie, not setCookie, because any previously specified Set-Cookie headers are left alone and a new header is set. Also, remember that the response headers must be set before any document content is sent to the client.

Here is an example:
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year
response.addCookie(userCookie);

Reading Cookies from the Client

To send a cookie to the client, you create a Cookie, set its maximum age (usually), then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, you should perform the following two tasks,
which are summarized below and then described in more detail in the following subsections.

1. Call request.getCookies. This yields an array of Cookie objects.
2. Loop down the array, calling getName on each one until you find the cookie of interest. You then       typically call getValue and use the value in some application-specific way.

String cookieName = "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());
}
}}


Example:


  • 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")) &&
  • // Could omit test and treat cookie name as a flag
  • (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>");
  • }
  • }

No comments:

Post a Comment