Servlets - Cookies Handling


Cookies are content records put away on the customer PC and they are kept for different data following reason. Java Servlets straightforwardly underpins HTTP cookies.

There are three stages associated with distinguishing returning clients −

  • Server content sends a lot of treats to the program. For instance name, age, or recognizable proof number etc.

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

  • When next time program sends any demand to web server then it sends those treats data to the server and server utilizes that data to recognize the user.

This section will show you how to set or reset treats, 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 treat specifically on a program). A servlet that sets a treat 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 = tutorialspoint.com 

Association: close 

Content-Type: content/html 

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

If the program is designed to store treats, it will at that point keep this data until the expiry date. On the off chance that the client focuses the program at any page that coordinates the way and space of the treat, it will resend the treat to the server. The program'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 

Treat: name = xyz 

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

Servlet Cookies Methods

Following is the rundown of valuable techniques which you can utilize while controlling treats in servlet.

Sr.No. Method & Description
1

public void setDomain(String design)

This strategy sets the space to which treat applies, for instance tutorialspoint.com.

2

public String getDomain()

This strategy gets the space to which treat applies, for instance tutorialspoint.com.

3

public void setMaxAge(int expiry)

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

4

public int getMaxAge()

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

5

public String getName()

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

6

public void setValue(String newValue)

This strategy sets the esteem related with the cookie

7

public String getValue()

This technique gets the esteem related with the cookie.

8

public void setPath(String uri)

This strategy sets the way to which this treat applies. On the off chance that you don't determine a way, the treat 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 treat applies.

10

public void setSecure(boolean flag)

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

11

public void setComment(String reason)

This technique determines a remark that depicts a treat's motivation. The remark is helpful if the program displays the treat to the user.

12

public String getComment()

This strategy restores the remark portraying the motivation behind this treat, or invalid if the treat has no comment.

Setting Cookies with Servlet

Setting treats with servlet includes three stages −

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

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

Keep at the top of the priority list, neither the name nor the esteem 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 treat ought to be substantial. Following would set up a treat for 24 hours.

cookie.setMaxAge(60 * 60 * 24); 

(3) Sending the Cookie into the HTTP reaction headers − You use response.addCookie to include treats 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 treats 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 treats back in your web application.

Reading Cookies with Servlet

To read treats, 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 treat and related value.

Example

Let us read treats 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 treat = null; 

Cookie[] treats = null; 

//Get a variety of Cookies related with this domain 

treats = 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 treat as "John" and last_name treat as "Player" at that point running http://localhost:8080/ReadCookies would show the accompanying outcome −

Found Cookies Name and Value

Name : first_name, Value: John
Name : last_name, Value: Player

Delete Cookies with Servlet

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

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

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

  • Add this treat again into reaction header.

Example

The following precedent would erase and existing treat named "first_name" and when you would run ReadCookies servlet next time it would return invalid 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 associated 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 treat : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

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

Found Cookies Name and Value

Name : last_name, Value: Player

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







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

Python 3