How to Read a Cookie and Delete a Cookie in Servlet
Servlets - Cookies Handling
Cookies are text files stored on the customer computer and they are kept for diverse data tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
-
Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
-
Browser stores this information on local machine for future use.
-
When side by side fourth dimension browser sends any asking to spider web server then information technology sends those cookies information to the server and server uses that information to identify the user.
This chapter volition teach yous how to set or reset cookies, how to access them and how to delete them.
The Anatomy of a Cookie
Cookies are usually ready in an HTTP header (although JavaScript can also set a cookie direct on a browser). A servlet that sets a cookie might ship headers that look something like this −
HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.ix (UNIX) PHP/4.0b3 Fix-Cookie: proper noun = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connectedness: close Content-Type: text/html
As yous can see, the Gear up-Cookie header contains a proper name value pair, a GMT date, a path and a domain. The name and value volition be URL encoded. The expires field is an instruction to the browser to "forget" the cookie later the given fourth dimension and date.
If the browser is configured to shop cookies, it will then keep this data until the expiry date. If the user points the browser at whatever page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might await something like this −
Go / HTTP/i.0 Connexion: Keep-Alive User-Amanuensis: Mozilla/iv.6 (X11; I; Linux two.2.6-15apmac ppc) Host: zink.demon.co.united kingdom:1126 Accept: epitome/gif, */* Accept-Encoding: gzip Accept-Language: en Have-Charset: iso-8859-one,*,utf-8 Cookie: proper name = xyz
A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects.
Servlet Cookies Methods
Following is the list of useful methods which y'all tin use while manipulating cookies in servlet.
Sr.No. | Method & Description |
---|---|
1 | public void setDomain(Cord design) This method sets the domain to which cookie applies, for example tutorialspoint.com. |
2 | public String getDomain() This method gets the domain to which cookie applies, for case tutorialspoint.com. |
3 | public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse earlier the cookie expires. If you lot don't set this, the cookie will last merely for the electric current session. |
four | public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, Past default, -1 indicating the cookie volition persist until browser shutdown. |
v | public String getName() This method returns the name of the cookie. The name cannot be changed subsequently creation. |
6 | public void setValue(String newValue) This method sets the value associated with the cookie |
seven | public String getValue() This method gets the value associated with the cookie. |
8 | public void setPath(String uri) This method sets the path to which this cookie applies. If y'all don't specify a path, the cookie is returned for all URLs in the same directory as the electric current page besides equally all subdirectories. |
9 | 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 merely be sent over encrypted (i.e. SSL) connections. |
11 | public void setComment(String purpose) This method specifies a annotate that describes a cookie'southward purpose. The comment is useful if the browser presents the cookie to the user. |
12 | public String getComment() This method returns the annotate describing the purpose of this cookie, or cypher if the cookie has no comment. |
Setting Cookies with Servlet
Setting cookies with servlet 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.
Cookie cookie = new Cookie("key","value");
Go on in heed, neither the name nor the value should contain white infinite or any of the following characters −
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age − You lot use setMaxAge to specify how long (in seconds) the cookie should exist valid. Post-obit would set upwardly a cookie for 24 hours.
cookie.setMaxAge(lx * 60 * 24);
(3) Sending the Cookie into the HTTP response headers − You utilize response.addCookie to add cookies in the HTTP response header as follows −
response.addCookie(cookie);
Case
Let us modify our Course Case to set up the cookies for offset and concluding name.
// Import required java libraries import coffee.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 offset and concluding names. Cookie firstName = new Cookie("first_name", asking.getParameter("first_name")); Cookie lastName = new Cookie("last_name", asking.getParameter("last_name")); // Fix expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*threescore*24); lastName.setMaxAge(60*60*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 Case"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\northward"; out.println(docType + "<html>\n" + "<head> <title>" + championship + "</championship> </head>\northward" + "<torso bgcolor = \"#f0f0f0\">\due north" + "<h1 align = \"center\">" + championship + "</h1>\n" + "<ul>\north" + " <li><b>First Name</b>: " + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " + request.getParameter("last_name") + "\north" + "</ul>\northward" + "</body> </html>" ); } }
Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally effort following HTML folio to call servlet.
<html> <torso> <form activeness = "HelloForm" method = "Go"> Commencement Name: <input type = "text" proper name = "first_name"> <br /> Last Name: <input blazon = "text" proper name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html>
Proceed to a higher place 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 higher up form.
Try to enter First Name and Last Name and and then click submit push. This would display showtime name and last name on your screen and same time it would set ii cookies firstName and lastName which would be passed back to the server when adjacent fourth dimension you would press Submit button.
Next section would explain you how you lot would access these cookies back in your spider web awarding.
Reading Cookies with Servlet
To read cookies, you lot need to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then wheel through the array, and use getName() and getValue() methods to access each cookie and associated value.
Example
Allow us read cookies which nosotros accept set in previous instance −
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet grade public class ReadCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = zip; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content blazon response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cord championship = "Reading Cookies Instance"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + championship + "</title></head>\n" + "<torso bgcolor = \"#f0f0f0\">\n" ); if( cookies != nada ) { 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("</body>"); out.println("</html>"); } }
Compile above servlet ReadCookies and create advisable entry in web.xml file. If you would have prepare first_name cookie as "John" and last_name cookie as "Actor" then running http://localhost:8080/ReadCookies would display the following result −
Found Cookies Proper noun and Value
Name : first_name, Value: John
Proper noun : last_name, Value: Actor
Delete Cookies with Servlet
To delete cookies is very simple. If you lot want to delete a cookie and then yous simply need to follow upwardly following 3 steps −
-
Read an already existing cookie and store information technology in Cookie object.
-
Set up cookie age every bit cipher using setMaxAge() method to delete an existing cookie
-
Add together this cookie back into response header.
Example
The following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet side by side fourth dimension it would return goose egg value for first_name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public course DeleteCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = cipher; // Go an array of Cookies associated with this domain cookies = request.getCookies(); // Prepare response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String championship = "Delete Cookies Case"; Cord docType = "<!doctype html public \"-//w3c//dtd html four.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<torso bgcolor = \"#f0f0f0\">\n" ); if( cookies != naught ) { 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.impress("Value: " + cookie.getValue( )+" <br/>"); } } else { out.println("<h2>No cookies founds</h2>"); } out.println("</torso>"); out.println("</html>"); } }
Compile higher up servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following upshot −
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
At present try to run http://localhost:8080/ReadCookies and it would display only i cookie as follows −
Establish Cookies Name and Value
Proper name : last_name, Value: Actor
You lot tin can delete your cookies in Internet Explorer manually. Start at the Tools carte and select Internet Options. To delete all cookies, printing Delete Cookies.
Useful Video Courses
Video
Video
Video
Video
Source: https://www.tutorialspoint.com/servlets/servlets-cookies-handling.htm