Cookies Servlet in Java


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 users memory allocated for cookies. Whenever the user sends further request then the cookie variables created by the same server travel along 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 creation of cookie variables.

Creation process of cookie variable

  1. The servlet class must be created by inheriting javax.servlet.http.HttpServlet
  2. Create an object of javax.servlet.http.cookie.By using name of the cookie variable and its value in the constructor.
  3. Add the object of cookie class into the response by using addCookie () method of Httpservlet response.The default lifespan of cookie variable can be changed by using the required number of second into setMaxAge() method of the cookie class.

Reading process of cookie variable

  1. The servlet class must be created by inheriting javax.servlet.http.HttpServlet.
  2. Find all cookie present in the request by using getCookies() method of HttpservletRequest .This method returns an array of cookie class.
  3. Find name of cookie variable by using getName() 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

<html>
<head>
<title>Cookie</title>
</head>
<body bgcolor="yellow">
<form action="./create" method = "get" >
<h2>Enter Product Name<input type="text" name="t1" ></h2>
<input type="submit" value="submit">
</form>
</body>
</html>

Create.java file

//Creating cookie
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class create extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
String s1=req.getParameter("t1");

//Cookie creation process
Cookie c=new Cookie("pname",s1);
res.addCookie(c);
PrintWriter out=res.getWriter();

out.println("<html><body>");
out.println("<h1 align='center'>Ur info</h1>");
out.println("<h1>Price of : "+s1+" is 50000</h1>");
out.println("<h2><a href='./buy'>Buy now</a> </h2>");
out.println("</body></html>");
}
}

buy.java file

//Reading cookie/session variable
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class buy extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{

//Reading value of session variable
HttpSession ses=req.getSession();
String s1=(String)ses.getAttribute("pn");

//Reading value of cookie variable
Cookie c[]=req.getCookies();

for(int i=0;i<c.length;i++)
{
if(c[i].getName().equals("pname"))
s1=c[i].getValue();
}

PrintWriter out=res.getWriter();
out.println("<html><body>");

out.println("<h1>Ur product: <font color='red'>"+s1+"</font> will be delivered soon</h1>");
out.println("</body></html>");

}
}

web.xml settings

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<servlet>
<servlet-name>create</servlet-name>
<servlet-class>create</servlet-class>
</servlet>

<servlet>
<servlet-name>buy</servlet-name>
<servlet-class>buy</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>create</servlet-name>
<url-pattern>/create</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>buy</servlet-name>
<url-pattern>/buy</url-pattern>
</servlet-mapping>

</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

Up Next
    Ebook Download
    View all
    Learn
    View all