Handling Cookies in JSP (III)

31 March 2008

Please read the first 2 parts on this topic. This particular post will focus on retrieving cookies and displaying their contents.

Presented below is a page that reads contents for the cookies and displays it to the user.

showcookievalue.jsp

<%@ page language="java" %> 
<% 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; 
} } } 
%> 
<html> <head> <title>Show Saved Cookie</title> </head> 
<body> 
<% if (myCookie == null) 
{ 
%> 
No Cookie found with the name <%=cookieName%> 
<% } else { %> <p>Welcome: <%=myCookie.getValue()%>. 
<% } %> 
</body>

We created an array of cookies, since there can be more than one cookie stored. Then we read all the cookies into that array. Note that you may only retrieve cookies stored by your site (domain). Then we simply retrived the stored value from the cookie with name “username”.

Try it. Happy coding.

del.icio.us:Handling Cookies in JSP (III)  digg:Handling Cookies in JSP (III)  spurl:Handling Cookies in JSP (III)  wists:Handling Cookies in JSP (III)  simpy:Handling Cookies in JSP (III)  newsvine:Handling Cookies in JSP (III)  blinklist:Handling Cookies in JSP (III)  furl:Handling Cookies in JSP (III)  reddit:Handling Cookies in JSP (III)  fark:Handling Cookies in JSP (III)  blogmarks:Handling Cookies in JSP (III)  Y!:Handling Cookies in JSP (III)  smarking:Handling Cookies in JSP (III)  magnolia:Handling Cookies in JSP (III)  segnalo:Handling Cookies in JSP (III)  gifttagging:Handling Cookies in JSP (III)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Handling Cookies in JSP (III)

Leave a Reply