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.

Using Session in JSP

Session is very important in we programming. There are many use of session in web programming. Java servlet/ Jsp provide easy way to work with session.

See the following code...
<%
Vector users = new Vector();
users.add("ABC");
users.add("BCD");
users.add("CDE");
session.setAttribute("users", users);
%>

This will set the Vector object users to session with name users.

To get values from session we can do the following..
<%
Vector users = (Vector)getAttribute("users");
for(int i=0;i<users.size();i++)
out.print((String)users.get(i)+"<br >");
%>

In this way we can handle session in JSP/servlet.

For any query just add comment..