Computer programming

Computer programming

Computer programming news and links

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>" );

}

}

Sponsors
Comments
Be the first to leave a comment!
Add a Comment:
Already a member? Log In
Sponsors
About the Author

6 Kudos
Top Geek Articles
Celebrities on the Phone
Cell phones are to celebrities like bats are to baseball: no one runs too far without them.
Why every guy should buy their girlfriend Wii Fit.
Gratuitous...
Hot Geeks -- The Sexiest Geeky Girls
These girls are gorgeous AND they'll play Warcraft with you. Doesn't get much better than that.
More From Zimbio
Copyright © 2009 - Zimbio, Inc. Some rights reserved.