A cookie is a piece of data from a website that is stored within a web browser(Client side) that the website can retrieve at a later time. Cookies are used to tell the server that users have returned to a particular website.
When you send a request to the server, the server sends a reply in which it embeds the cookie which serves as an identifier to identify the user. So, next time when you visit the same website, the cookie lets the server know that you are visiting the website again.
Session management. For example, cookies let websites recognize users and recall their individual login information and preferences, such as sports news versus politics.
Personalization. Customized advertising is the main way cookies are used to personalize your sessions. You may view certain items or parts of a site, and cookies use this data to help build targeted ads that you might enjoy.
Tracking. Shopping sites use cookies to track items users previously viewed, allowing the sites to suggest other goods they might like and keep items in shopping carts while they continue shopping.
The constructor of Cookie class creates the cookie object with corresponding cookie name and value.
//creating cookie object
Cookie cookie = new Cookie("username","Studyglance");
//adding cookie to the response
Response.addCookie(cookie);
Cookie ck[ ]=request.getCookies();
Cookie Demo
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
//creating cookie object
Cookie ck=new Cookie("uname",name);
//adding cookie in the response
response.addCookie(ck);
out.print("Cookie Saved");
//creating submit button
out.print("
");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.println("Reading the cookies
");
out.println("
");
out.println("Name of the cookie : " + ck[0].getName() + "
");
out.println("Value in cookie : " + ck[0].getValue());
out.close();
}catch(Exception e){
System.out.println(e);
}
}
}
set
SetCookieServlet
set
/servlet1
get
GetCookieServlet
get
/servlet2