What is Cookie – Servlet to add cookie

What is cookie?

A cookie is a small information that is exchanged between server and client.Actually using cookie client can save some information on the client’s machine.And when the client requests to the server then the client send the information to the server.A cookie can be of maximum 4 KB.

Servlet code to add cookie on the client machine
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class AddCookie extends HttpCookie
{
public void doGet(HttpRequest request,HttpResponse response) throws
ServletException,IoException
{
PrintWriter out=response.getWriter();
response.setContentType(“text/html”);
Cookie cook=new Cookie(“Raja”,”username”);
response.addCookie(cook);
out.println(“Cookie is set”);
}
}

Servlet Code to retrieve cookie
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class GetCookie extends HttpServlet
{
public void doGet(HttpRequest request,HttpResponse response) throws
ServletException,IoException
{
PrintWriter out=response.getWriter();
response.setContentType(“text/html”);
Cookie cooks[]=response.getCookies();
for(int i=0;i<=cooks.length;i++)
{
Cookie cook=Cooks[i];
if(cook.getName().equals(“username”))
{
String name=cook.getValue();
break;
}
}
out.println(“User Name: ” + name);
}

Cookie is one of the type of session management. To know more about session management, visit the below link,

https://smoothknowledge.com/2017/12/31/session-management/

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.