banner



How To Set Cookies In Java

Servlets - Cookies Handling


Cookies are text files stored on the customer computer and they are kept for various data tracking purpose. Java Servlets transparently supports HTTP cookies.

At that place are three steps involved in identifying returning users −

  • Server script sends a ready of cookies to the browser. For instance name, age, or identification number etc.

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

  • When adjacent time browser sends any request to web server and so it sends those cookies information to the server and server uses that information to identify the user.

This affiliate will teach you how to set or reset cookies, how to access them and how to delete them.

The Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can as well set a cookie direct on a browser). A servlet that sets a cookie might send headers that look something similar this −

HTTP/1.ane 200 OK Appointment: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.three.nine (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;     path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html        

Equally you can meet, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.

If the browser is configured to shop cookies, it will and so keep this information until the death date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser'south headers might look something similar this −

Get / HTTP/1.0 Connectedness: Continue-Alive User-Amanuensis: Mozilla/four.six (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: prototype/gif, */* Accept-Encoding: gzip Take-Language: en Have-Charset: iso-8859-ane,*,utf-eight Cookie: proper noun = xyz        

A servlet will and then accept access to the cookie through the asking method request.getCookies() which returns an assortment of Cookie objects.

Servlet Cookies Methods

Following is the listing of useful methods which y'all can utilise while manipulating cookies in servlet.

Sr.No. Method & Description
1

public void setDomain(String pattern)

This method sets the domain to which cookie applies, for case tutorialspoint.com.

ii

public String getDomain()

This method gets the domain to which cookie applies, for case tutorialspoint.com.

3

public void setMaxAge(int decease)

This method sets how much time (in seconds) should expire before the cookie expires. If you don't gear up this, the cookie will final only for the electric current session.

4

public int getMaxAge()

This method returns the maximum age of the cookie, specified in seconds, By default, -i indicating the cookie will persist until browser shutdown.

5

public String getName()

This method returns the name of the cookie. The name cannot be inverse afterwards creation.

6

public void setValue(Cord newValue)

This method sets the value associated with the cookie

7

public String getValue()

This method gets the value associated with the cookie.

eight

public void setPath(String uri)

This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page besides as all subdirectories.

nine

public String getPath()

This method gets the path to which this cookie applies.

10

public void setSecure(boolean flag)

This method sets the boolean value indicating whether the cookie should but be sent over encrypted (i.eastward. SSL) connections.

11

public void setComment(String purpose)

This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.

12

public Cord getComment()

This method returns the annotate describing the purpose of this cookie, or goose egg if the cookie has no annotate.

Setting Cookies with Servlet

Setting cookies with servlet involves three steps −

(one) Creating a Cookie object − You phone call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

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

Proceed in mind, neither the proper noun nor the value should contain white space or any of the following characters −

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

(ii) Setting the maximum historic period − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would prepare a cookie for 24 hours.

cookie.setMaxAge(threescore * 60 * 24);        

(iii) Sending the Cookie into the HTTP response headers − You use response.addCookie to add together cookies in the HTTP response header as follows −

response.addCookie(cookie);        

Case

Let us modify our Course Case to prepare the cookies for first and last name.

// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*;   // Extend HttpServlet class public class HelloForm extends HttpServlet {     public void doGet(HttpServletRequest request, HttpServletResponse response)       throws ServletException, IOException {              // Create cookies for first and last names.             Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));       Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));        // Set up expiry date after 24 Hrs for both the cookies.       firstName.setMaxAge(60*60*24);       lastName.setMaxAge(60*threescore*24);        // Add both the cookies in the response header.       response.addCookie( firstName );       response.addCookie( lastName );        // Set response content type       response.setContentType("text/html");         PrintWriter out = response.getWriter();       String title = "Setting Cookies Instance";       String docType =          "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";              out.println(docType +          "<html>\north" +             "<head>                <championship>" + title + "</title>             </head>\n" +                          "<body bgcolor = \"#f0f0f0\">\due north" +                "<h1 align = \"center\">" + title + "</h1>\due north" +                "<ul>\n" +                   "  <li><b>Outset Name</b>: "                   + asking.getParameter("first_name") + "\n" +                   "  <li><b>Concluding Name</b>: "                   + request.getParameter("last_name") + "\northward" +                "</ul>\n" +             "</body>          </html>"       );    } }        

Compile the above servlet HelloForm and create advisable entry in spider web.xml file and finally try following HTML folio to phone call servlet.

          <html>    <trunk>       <course activeness = "HelloForm" method = "Become">          Outset Proper noun: <input type = "text" proper noun = "first_name">          <br />          Last Name: <input type = "text" name = "last_name" />          <input type = "submit" value = "Submit" />       </form>    </body> </html>        

Proceed higher up HTML content in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above class.

Endeavour to enter Beginning Proper name and Last Proper name and then click submit push button. This would brandish first name and last proper name on your screen and aforementioned time information technology would ready 2 cookies firstName and lastName which would exist passed dorsum to the server when adjacent time you would printing Submit button.

Next section would explain you lot how you lot would access these cookies dorsum in your web application.

Reading Cookies with Servlet

To read cookies, yous demand to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then wheel through the array, and apply getName() and getValue() methods to access each cookie and associated value.

Example

Let us read cookies which we have fix in previous instance −

// Import required java libraries import coffee.io.*; import javax.servlet.*; import javax.servlet.http.*;   // Extend HttpServlet class public grade ReadCookies 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 = "Reading Cookies Example";       String docType =          "<!doctype html public \"-//w3c//dtd html four.0 " +          "transitional//en\">\n";                 out.println(docType +          "<html>\due north" +          "<caput><title>" + championship + "</championship></head>\n" +          "<body bgcolor = \"#f0f0f0\">\n" );        if( cookies != nothing ) {          out.println("<h2> Found Cookies Name and Value</h2>");           for (int i = 0; i < cookies.length; i++) {             cookie = cookies[i];             out.print("Proper noun : " + cookie.getName( ) + ",  ");             out.print("Value: " + cookie.getValue( ) + " <br/>");          }       } else {          out.println("<h2>No cookies founds</h2>");       }       out.println("</trunk>");       out.println("</html>");    } }        

Compile to a higher place servlet ReadCookies and create advisable entry in spider web.xml file. If you would have set up first_name cookie as "John" and last_name cookie as "Player" and so running http://localhost:8080/ReadCookies would brandish the following effect −

          

Found Cookies Name and Value

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

Delete Cookies with Servlet

To delete cookies is very simple. If you desire to delete a cookie then you merely need to follow up following 3 steps −

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

  • Fix cookie age as zero using setMaxAge() method to delete an existing cookie

  • Add together this cookie dorsum into response header.

Example

The post-obit example would delete and existing cookie named "first_name" and when you lot would run ReadCookies servlet side by side time it would return naught value 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 assortment of Cookies associated with this domain       cookies = request.getCookies();        // Set up response content type       response.setContentType("text/html");         PrintWriter out = response.getWriter();       String title = "Delete Cookies Example";       String docType =          "<!doctype html public \"-//w3c//dtd html iv.0 " + "transitional//en\">\northward";                 out.println(docType +          "<html>\n" +          "<head><title>" + title + "</title></caput>\northward" +          "<body bgcolor = \"#f0f0f0\">\n" );                 if( cookies != zero ) {          out.println("<h2> Cookies Proper noun 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("Proper noun : " + cookie.getName( ) + ",  ");             out.print("Value: " + cookie.getValue( )+" <br/>");          }       } else {          out.println("<h2>No cookies founds</h2>");       }       out.println("</torso>");       out.println("</html>");    } }        

Compile above servlet DeleteCookies and create advisable entry in web.xml file. Now running http://localhost:8080/DeleteCookies would brandish the following result −

          

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

Now try to run http://localhost:8080/ReadCookies and it would display only i cookie as follows −

          

Constitute Cookies Name and Value

Name : last_name, Value: Player

You can delete your cookies in Internet Explorer manually. Beginning at the Tools carte du jour and select Internet Options. To delete all cookies, press Delete Cookies.

Useful Video Courses


Servlets and JSP Tutorial For Beginners!

Video

JSP and Servlets - The Complete Course

Video

JSP and Servlets Bootcamp: Web Applications for Beginners

Video

Java Servlets Certification Training (beginner to advanced)

Video

Servlets and JSP Tutorial for Beginners

Video

How To Set Cookies In Java,

Source: https://www.tutorialspoint.com/servlets/servlets-cookies-handling.htm

Posted by: buckleydowanceares.blogspot.com

0 Response to "How To Set Cookies In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel