Table of Contents
A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
To know more about Java, Download Entri App!
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.
- Non-persistent cookie
- Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
Constructor of Cookie class
Constructor | Description |
Cookie() | constructs a cookie. |
Cookie(String name, String value) | constructs a cookie with a specified name and value. |
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method | Description |
public void setMaxAge(int expiry) | Sets the maximum age of the cookie in seconds. |
public String getName() | Returns the name of the cookie. The name cannot be changed after creation. |
public String getValue() | Returns the value of the cookie. |
public void setName(String name) | changes the name of the cookie. |
public void setValue(String value) | changes the value of the cookie. |
To know more about Java, Download Entri App!
How to create Cookie?
Let’s see the simple code to create cookie.
- Cookie ck=new Cookie(“user”,”sonoo jaiswal”);//creating cookie object
- response.addCookie(ck);//adding cookie in the response
How to delete Cookie?
Let’s see the simple code to delete cookie. It is mainly used to logout or signout the user.
- Cookie ck=new Cookie(“user”,””);//deleting value of cookie
- ck.setMaxAge(0);//changing the maximum age to 0 seconds
- response.addCookie(ck);//adding cookie in the response
How to read cookies
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++)
{
out.print(“Name: “+c[i].getName()+” & Value: “+c[i].getValue());
}
Example of Cookies in java servlet
index.html
<form action=”login”>
User Name:<input type=”text” name=”userName”/>
<br/>
Password:<input type=”password” name=”userPassword”/>
<br/>
<input type=”submit” value=”submit”/></form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{ response.setContentType(“text/html”);
PrintWriter pwriter = response.getWriter();
String name = request.getParameter(“userName”);
String password = request.getParameter(“userPassword”);
pwriter.print(“Hello “+name);
pwriter.print(“Your Password is: “+password);
//Creating two cookies
Cookie c1=new Cookie(“userName”,name);
Cookie c2=new Cookie(“userPassword”,password);
//Adding the cookies to response header
response.addCookie(c1);
response.addCookie(c2);
pwriter.print(“<br><a href=’welcome’>View Details</a>”);
pwriter.close();
}
catch(Exception exp)
{
System.out.println(exp);
}
}
}
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{ response.setContentType(“text/html”);
PrintWriter pwriter = response.getWriter();
//Reading cookies Cookie c[]=request.getCookies();
//Displaying User name value from cookie pwriter.print(“Name: “+c[1].getValue());
//Displaying user password value from cookie pwriter.print(“Password: “+c[2].getValue()); pwriter.close();
}
catch(Exception exp)
{ System.out.println(exp);
}
}
}
web.xml
<web-app>
<display-name>
BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet> <servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class></servlet>
<servlet-mapping> <servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping><servlet> <servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class></servlet>
<servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern></servlet-mapping>
</web-app>
Output:
Welcome Screen:
After clicking Submit:
After clicking View Details:
To know more about Java, Download Entri App!
Why is it important to choose Entri?
- Excellent online platform for all the Competitive Exams.
- Provides updated materials created by the Entri Experts.
- Entri provides a best platform with full- length mock tests including previous year question papers.
- You can download the app for free and join the required classes.
- Entri wishes you all the best for your examinations and future endeavours.
“YOU DON’T HAVE TO BE GREAT TO START, BUT YOU HAVE TO START TO BE GREAT.”