Wednesday, November 3, 2010

Set Cookies from JSP - example

Set Cookies as follows
You may need to add page import
<%@ page language="java" import="java.util.*"%>
<%
Cookie cookie = new Cookie ("username","sanjeewa malalgoda");
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>

Get Cookies as Follows
Here we search cookie for name username and display the results
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i]; break;
}
}
}
%>
<%
if (myCookie == null)
{
%>No Cookie found with the name <%=cookieName%>
<%
}
else
{
%>
Welcome: <%=myCookie.getValue()%>.
<%
}
%>

No comments:

Post a Comment