Java J2ME JSP J2EE Servlet Android

Using cookie in Java servlet/ jsp

Cookie is often very important in web programming. Java servlet / jsp provide a easy way to work with browser cookie.

You can easily set cookie by the following way..
<%
String myName=request.getParameter("myName");
if(myName==null) myName="";
Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("myName",myName);
cookie.setMaxAge(2 * 365 * 24 * 60 * 60);
response.addCookie(cookie);
%>
Here a cookie name 'myName' is created with value request.getParameter("myName"). The lifetime for this cookie is set to 2 years;


You you can fetch that cookie using jsp/servlet easily by the following way
<%
String cookieName = "myName";
Cookie allCookies [] = request.getCookies ();
Cookie cook = null;
if (allCookies != null)
{
for (int i = 0; i < allCookies.length; i++)
{
if (allCookies [i].getName().equals (cookieName))
{
cook = allCookies[i];
break;
}
}
}
%>

The Cookie object cook will contain the requested cookie. And you can get the value of the cookie by calling cook.getValue() methode.

Thank you.