Servlets - Cookies Handling


Cookies are text files put away on the client PC and they are kept for different data following reason. Java Servlets transparently supports HTTP cookies.

There are three steps involved with identifying returning clients −

  • Server text sends a lot of cookies to the browser. For instance name, age, or identification proof number etc.

  • Browser stores this data on local machine for future use.

  • When next time browser sends any request to web server then it sends those cookies data to the server and server utilizes that data to recognize the user.

This section will show you how to set or reset cookies, how to get to them and how to erase them.

The Anatomy of a Cookie

Cookies are generally set in a HTTP header (in spite of the fact that JavaScript can likewise set a cookie specifically on a browser). A servlet that sets a cookie may send headers that look something like this −

HTTP/1.1 200 OK 

Date: Fri, 04 Feb 2000 21:03:38 GMT 

Server: Apache/1.3.9 (UNIX) PHP/4.0b3 

Set-Cookie: name = xyz; lapses = Friday, 04-Feb-07 22:03:38 GMT; 

way =/; area = javacodegeeks.net 

Association: close 

Content-Type: content/html 

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a way and a space. The name and value will be URL encoded. The terminates field is a guidance to the browser to "overlook" the cookie after the given time and date.

If the browser is designed to store cookies, it will at that point keep this data until the expiry date. On the off chance that the client focuses the browser at any page that coordinates the way and space of the cookies , it will resend the cookie to the server. The browser's headers may look something like this −

GET/HTTP/1.0 

Association: Keep-Alive 

Client Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) 

Host: zink.demon.co.uk:1126 

Acknowledge: picture/gif, */* 

Acknowledge Encoding: gzip 

Acknowledge Language: en 

Acknowledge Charset: iso-8859-1,*,utf-8 

cookies : name = xyz 

A servlet will at that point approach the cookie through the request strategy request.getCookies() which restores a variety of Cookie objects.

Servlet Cookies Methods

Following is the rundown of valuable methods which you can utilize while controlling cookies in servlet.

Sr.No. Method & Description
1

public void setDomain(String design)

This strategy sets the space to which cookie applies, for instance javacodegeeks.net.

2

public String getDomain()

This strategy gets the space to which cookie applies, for instance javacodegeeks.net.

3

public void setMaxAge(int expiry)

This technique sets how much time (in short order) ought to slip by before the cookie terminates. On the off chance that you don't set this, the cookie will last just for the current session.

4

public int getMaxAge()

This strategy restores the most extreme age of the cookies , determined in a moment or two, By default, - 1 demonstrating the cookie will continue until browser shutdown.

5

public String getName()

This strategy restores the name of the cookies . The name can't be changed after creation.

6

public void setValue(String newValue)

This strategy sets the value related with the cookie

7

public String getValue()

This technique gets the value related with the cookie.

8

public void setPath(String uri)

This strategy sets the way to which this cookie applies. On the off chance that you don't determine a way, the cookie is returned for all URLs in indistinguishable registry from the present page just as all subdirectories.

9

public String getPath()

This strategy gets the way to which this cookie applies.

10

public void setSecure(boolean flag)

This strategy sets the boolean value showing whether the cookie should just be sent over encoded (for example SSL) connections.

11

public void setComment(String reason)

This technique determines a remark that depicts a cookies 's motivation. The remark is helpful if the browser displays the cookie to the user.

12

public String getComment()

This strategy restores the remark portraying the motivation behind this cookies , or null if the cookie has no comment.

Setting Cookies with Servlet

Setting cookies with servlet includes three steps −

(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie esteem, the two of which are strings.

Cookie cookie = new Cookie("key","value"); 

Keep at the top of the priority list, neither the name nor the value ought to contain void area or any of the accompanying characters −

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

(2) Setting the greatest age − You use setMaxAge to determine to what extent (in a moment or two) the cookie ought to be substantial. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60 * 60 * 24); 

(3) Sending the Cookie into the HTTP reaction headers − You use response.addCookie to include cookies in the HTTP reaction header as pursues −

response.addCookie(cookie); 

Try to enter First Name and Last Name and after that click submit catch. This would show first name and keep going name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.

Next area would clarify you how you would get to these cookies back in your web application.

Reading Cookies with Servlet

To read cookies, you have to make a variety of javax.servlet.http.Cookie protests by calling the getCookies() technique for HttpServletRequest. At that point spin through the exhibit, and use getName() and getValue() strategies to get to every cookie and related value.

Example

Let us read cookies which we have set in past precedent −

//Import required java libraries 

import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

//Extend HttpServlet class 

public class ReadCookies extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

Cookie cookie = null; 

Cookie[] cookies = null; 

//Get a variety of Cookies related with this domain 

cookies = request.getCookies();
    // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Reading Cookies Example";
      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 = \"#f0f0f0\">\n" );

      if( cookies != null ) {
         out.println("<h2> Found Cookies Name and Value</h2>");

         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.print("Name : " + cookie.getName( ) + ",  ");
            out.print("Value: " + cookie.getValue( ) + " <br/>");
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

Compile above servlet ReadCookies and make proper section in web.xml record. On the off chance that you would have set first_name cookie as "Jon" and last_name cookie as "Moxley" at that point running http://localhost:8080/ReadCookies would show the accompanying outcome −

Found Cookies Name and Value

Name : first_name, Value: Jon
Name : last_name, Value: Moxley

Delete Cookies with Servlet

To erase cookies is exceptionally straightforward. In the event that you need to erase a cookies , at that point you just need to catch up following three steps −

  • Read an officially existing cookie and store it in Cookie object.

  • Set cookie age as zero utilizing setMaxAge() strategy to erase a current cookie

  • Add this cookie again into reaction header.

Example

The following precedent would erase and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null an incentive for first_name.

//Import required java libraries
    import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class DeleteCookies extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      Cookie cookie = null;
      Cookie[] cookies = null;
         
      // Get an array of Cookies involved with this domain
      cookies = request.getCookies();

      // Set response content type
      response.setContentType("text/html");
       PrintWriter out = response.getWriter();
      String title = "Delete Cookies Example";
      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 = \"#f0f0f0\">\n" );
         
      if( cookies != null ) {
         out.println("<h2> Cookies Name and Value</h2>");

         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];

            if((cookie.getName( )).compareTo("first_name") == 0 ) {
               cookie.setMaxAge(0);
               response.addCookie(cookie);
               out.print("Deleted cookie : " + cookie.getName( ) + "<br/>");
            }
            out.print("Name : " + cookie.getName( ) + ",  ");
            out.print("Value: " + cookie.getValue( )+" <br/>");
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

Compile above servlet DeleteCookies and make suitable passage in web.xml document. Presently running http://localhost:8080/DeleteCookies would show the accompanying outcome −

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: Jon

Name : last_name, Value: Moxley

Now endeavor to run http://localhost:8080/ReadCookies and it would show just a single cookie as pursues −

Found Cookies Name and Value

Name : last_name, Value: Moxley

You can erase your cookies in Internet Explorer manually. Begin at the Tools menu and select Internet Options. To erase all cookies, press Delete Cookies.







© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3