protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{	
	int lngCookieSet    = 0;
	String strCookieVal = "";
	
	String cookieName = "Name";

	Cookie[] cookies = request.getCookies();
		
	if(cookies != null && cookies.length > 0)
	{
	  for(int i=0;i<cookies.length;i++)
	  {
	    if(cookieName.equals(cookies[i].getName()))
	    {
	      lngCookieSet = 1;
	      strCookieVal = cookies[i].getValue();
	    }
	  }
	}	
		
	if(lngCookieSet == 1)
	{
	   PrintWriter prw = response.getWriter();	
	   prw.print(strCookieVal);
	}
	else
	{
	   Cookie cook = new Cookie("Name", "Mugil");
	   cook.setMaxAge(24*60*60*365);//1 Year
	   response.addCookie(cook);	
	}
}

1.We should check

cookies != null

otherwise the compiler will generate null pointer exception

2.The

new Cookie

constructor will take Cookie Name and Value as Parameter.

3.The addCookie Will add cookie to response Header to set cookie on Client Side

Posted in JSP.

Leave a reply