User session counter servlet

The UserSessionCounter servlet (Example 1) demonstrates how to keep a session counter by user, using the HttpSession tracking technique.

The flow of this servlet can be described in the following steps:

❑  We get a handle to a session object using the getSession method of the request. This method returns the current valid session associated with this request and user. This method takes a boolean argument, true means a new session should be created if none exists, false only returns an existing session, or null.

❑  If it is a new session, or if the session does not contain our object, we must add an object into the session of the type that we want to keep around, using the putValue method of HttpSession.

❑  We now have to create a reference to the SaveServletStats object in the servlet. We use the getValue method of HttpServlet to retrieve this object. Once you have a reference to your object through getValue, you can just manipulate the object as needed; updates to the object are automatically stored as part of the session object.

Example 1
package itso.servjsp.servletapi;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UserSessionCounter extends HttpServlet {
private int calledCount;
public void init(ServletConfig config) throws ServletException {
calledCount = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
if (session.isNew() || session.getValue("usersession")==null) {
session.putValue("usersession", new SaveServletStats());
SaveServletStats ustats =
out.println("<H4>This servlet has been called: </H4><BR>");
out.println("<B>" + calledCount + "</B> times since the servlet was loaded
THIS servlet life-cycle session<BR>");
out.println("<B>" + ustats.calledCount + "</B> times since the servlet was
loaded by this user<BR>");
Share this article :
Copyright © 2012. Best Online Tutorials | Source codes | Programming Languages - All Rights Reserved