Cookies Servlet in Java

In this article we will know how to use cookies in servlet.

Cookies

 
This is a memory location present in a users machine to store information about the user. A page available in a server can create variables in the user's memory allocated for cookies. Whenever the user sends further request then the cookie variables created by the same server travel along with the request. The destination page of the request can find values from the cookie variable present in the request. These variables can be available in users machine for a period of 24 hours by default. The life span of cookie variables can be changed by the server. The user can deny the creation of cookie variables.
 
The creation process of cookie variable
  1. The servlet class must be created byinheriting javax.servlet.http.HttpServlet
  2. Create an object ofjavax.servlet.http.cookie.By using the name of the cookie variable and its valuein the constructor.
  3. Add the object of cookie class into theresponse by using addCookie () method of Httpservlet response.The defaultlifespan of cookie variable can be changed by using the required number ofsecond into setMaxAge() method of the cookie class.
Reading process of cookie variable
  1. The servlet class must be created byinheriting javax.servlet.http.HttpServlet.
  2. Find all cookie present in the request byusing getCookies() method of HttpservletRequest .This method returns anarray of cookie class.
  3. Find the name of cookie variable by usinggetName() or find value of cookie variable by using getValue() method.
Example:
  
Create a HTML file as below in context folder
 
To visible directory listing Go to E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf
  
In web.xml file change (false to true)
 
Cookie.html
  1. <html>  
  2. <head>  
  3. <title>Cookie</title>  
  4. </head>  
  5. <body bgcolor="yellow">  
  6. <form action="./create" method = "get" >  
  7. <h2>Enter Product Name<input type="text" name="t1" ></h2>  
  8. <input type="submit" value="submit">  
  9. </form>  
  10. </body>  
  11. </html>  
Create.java file
  1. //Creating cookie    
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4. import java.io.*;  
  5.   
  6. public class create extends HttpServlet   
  7. {  
  8.  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {  
  9.   String s1 = req.getParameter("t1");  
  10.   
  11.   //Cookie creation process    
  12.   Cookie c = new Cookie("pname", s1);  
  13.   res.addCookie(c);  
  14.   PrintWriter out = res.getWriter();  
  15.   
  16.   out.println("<html><body>");  
  17.   out.println("<h1 align='center'>Ur info</h1>");  
  18.   out.println("<h1>Price of : " + s1 + " is 50000</h1>");  
  19.   out.println("<h2><a href='./buy'>Buy now</a> </h2>");  
  20.   out.println("</body></html>");  
  21.  }  
  22. }  
buy.java file
  1. //Reading cookie/session variable  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4. import java.io.*;  
  5.   
  6. public class buy extends HttpServlet   
  7. {  
  8.  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {  
  9.   
  10.   //Reading value of session variable  
  11.   HttpSession ses = req.getSession();  
  12.   String s1 = (String) ses.getAttribute("pn");  
  13.   
  14.   //Reading value of cookie variable  
  15.   Cookie c[] = req.getCookies();  
  16.   
  17.   for (int i = 0; i < c.length; i++)   
  18.   {  
  19.    if (c[i].getName().equals("pname"))  
  20.     s1 = c[i].getValue();  
  21.   }  
  22.   
  23.   PrintWriter out = res.getWriter();  
  24.   out.println("<html><body>");  
  25.   
  26.   out.println("<h1>Ur product: <font color='red'>" + s1 + "</font> will be delivered soon</h1>");  
  27.   out.println("</body></html>");  
  28.   
  29.  }  
  30. }  
web.xml settings
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!--  
  3. Licensed to the Apache Software Foundation (ASF) under one or more  
  4. contributor license agreements. See the NOTICE file distributed with  
  5. this work for additional information regarding copyright ownership.  
  6. The ASF licenses this file to You under the Apache License, Version 2.0  
  7. (the "License"); you may not use this file except in compliance with  
  8. the License. You may obtain a copy of the License at  
  9.   
  10. http://www.apache.org/licenses/LICENSE-2.0  
  11.   
  12. Unless required by applicable law or agreed to in writing, software  
  13. distributed under the License is distributed on an "AS IS" BASIS,  
  14. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  15. See the License for the specific language governing permissions and  
  16. limitations under the License.  
  17. -->  
  18. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  19. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  20. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  21. version="2.5">  
  22.   
  23. <servlet>  
  24. <servlet-name>create</servlet-name>  
  25. <servlet-class>create</servlet-class>  
  26. </servlet>  
  27.   
  28. <servlet>  
  29. <servlet-name>buy</servlet-name>  
  30. <servlet-class>buy</servlet-class>  
  31. </servlet> 

  32. <servlet-mapping>  
  33. <servlet-name>create</servlet-name>  
  34. <url-pattern>/create</url-pattern>  
  35. </servlet-mapping>  
  36.   
  37. <servlet-mapping>  
  38. <servlet-name>buy</servlet-name>  
  39. <url-pattern>/buy</url-pattern>  
  40. </servlet-mapping>  
  41.   
  42. </web-app>  
Compile both the files as below
 
javac -cp servlet-api.jar create.java (for tomcat 6.0)
 
javac -cp servlet-api.jar buy.java (for tomcat 6.0)
 
CkeSrlt1.gif  
 
Output
 
Run the tomcat then write the below line in the URL
 
Here test is the Context path, which we mentioned in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.
 
http://localhost:8081/test/
 
After giving the URL, a set a listing will come, here only one appears
 
As cookie.html,click it
 
CkeSrlt2.gif
 
Thanks for reading