Servlet HttpSession Management
Session tracking is a mechanism that is used to maintain state about a series of requests from the same user. Java Servlet technology provides an API for managing sessions and allows several mechanisms for tracking sessions. One of the best approach is by using HttpSession object. HttpSession interface is defined in "javax.servlet.http" package and is used for the purpose of session tracking while working with servlets.
we can access a session by calling the HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) method of a request object. This method will return the current session associated with this request or if the request does not have any session, it will create a new one.
A sample Program demonstrating the usage of HttpSession
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
class HttpSessionEx extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println( "<HTML><BODY>" );
HttpSession sess = request.getSession(true);
// HttpSession Methods
Date cd = new Date(sess.getCreationTime());
Date acd = new Date(sess.getLastAccessedTime());
out.println("Session ID " + sess.getId());
out.println("Session was Created at: " + cd);
out.println("Session was Last Accessed at: " + acd);
// getting the session item
Object sessobj = sess.getAttribute( "power" );
out.println( "<BR>" + sessobj );
// getting the contents of the session
Enumeration data = sess.getAttributeNames();
while( data.hasMoreElements() ) {
String value = (String) data.nextElement();
sessobj = sess.getAttribute(value);
out.println( "<BR>" + value + " = " + sessobj );
}
out.println( "</BODY></HTML>" );
}
}
1 comments:
Hi
My name is Alayoua Mbark . I've just visited your website and I was wondering if you'd be interested in exchanging links with my website. I have page rank 3.
If you are interested, please add the following information to your website and let me know when it's ready in Email mbarkalayoua@gmail.com . I'll do the same for you in less than 24 hours, otherwise you can delete my link from yoursite.
Title: cars|used cars|car|car rental|enterprise car rental
URL: http://carforallnet.blogspot.com
I hope you have a nice day and thank you for your time.
Mbark Alayoua
mbarkalayoua@gmail.com
http://carforallnet.blogspot.com
Post a Comment