↑
Main Page
ASP.NET
for (int i=0; i < cookies.length; i++) {
if (cookies[i].getName().equals(name)) {
return cookies[i];
}
}
} else {
return null;
}
}
%>
When this code is inserted into a JSP, you can retrieve the value of a cookie by doing the following:
<%
Cookie nameCookie = getCookie(request, “name”);
System.out.println(“Name is “ + nameCookie.getValue());
%>
Creating a cookie is equally easy in the JSP world. To create a new cookie, simply instantiate a new
Cookie
object and pass in the name and value. Then, add it to the user ’s system by using the
addCookie()
method of the response object:
<%
Cookie nameCookie = new Cookie(“name”, “Nicholas”);
response.addCookie(nameCookie);
%>
Alternately, you can add additional data to the cookie before storing it:
<%
Cookie nameCookie = new Cookie(“name”, “Nicholas”);
nameCookie.setDomain(“http://www.wrox.com”);
nameCookie.setPath(“/books”);
response.addCookie(nameCookie);
%>
To delete a specific cookie, you must first retrieve it and then set its expiration to
0
(JSP cookies use the
number of milliseconds as the expiration value):
<%
Cookie cookieToDelete = getCookie(“name”);
cookieToDelete.setMaxAge(0);
response.addCookie(cookieToDelete);
%>
ASP.NET
ASP.NET handles cookies in a very similar way to JSP. The
Request
object (automatically created for
each ASP.NET page) contains a
Cookies
collection from which all cookies can be read. Each cookie is an
instance of
HttpCookie
, which has the following properties:
486
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 486
Free JavaScript Editor
Ajax Editor
©
→