Cookies using JSP or Java Bean

By: Rajan Printer Friendly Format    


Cookies are a way of storing user specific data in their own computers. For example if you want to identify your site's visitor and greet him by his name the next time he visits your computer, you can use a cookie. So the first time the user visits you can provide a field to enter his name and then store this information as a cookie in his computer. The next time he visits your site, you can check whether a cookie by that name is stored in his computer and if it is stored then you can retrieve this name and greet him by saying 'Welcome back xxxxxxx'.

This Sample Java Program shows how to check whether a cookie by the specified name exists in the PC and if exists then print the value set for that Cookie. This code can be embedded in your JSP or Java Bean or Servlets.


try{
URL url= new URL(args[0]); 
URLConnection urlConnection = url.openConnection(); 
for(int i=0;;i++) 
{ 
String header=urlConnection.getHeaderField(i); 
if(header==null) 
break; 
if("set-cookie".equalsIgnoreCase(urlConnection.getHeaderFieldKey(i))) 
	System.out.println(header);
}
}catch(MalformedURLException mue){}
catch(IOException ioe){} 



Ask a Question



Most Viewed Articles (in JSP )

Latest Articles (in JSP)

Comment on this tutorial