Session Tracking in Servlet

Chapter 1 - The Servlet Technology Method

    Session Tracking in Servlet

  • Session Tracking

    To associate a session with a user, a web container can use several methods, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL.

    Finalizing a Servlet

    The web container may determine that a servlet should be removed from service.The container calls the destroy method of the Servlet interface. In this method,release any resources the servlet is using and save any persistent state.

    A servlet’s service methods should all be complete when a servlet is removed. The server tries to ensure this by calling the destroy method only after all service requests have returned or after a server-specific grace period, whichever comes first.

    servlet has operations that may run longer than the server’s grace period, the operations could still be running when destroy is called.

    • Keep track of how many threads are currently running the service method.

    • Provide a clean shutdown by having the destroy method notify long-running threads of the shutdown and wait for them to complete.

    • Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return.

    Tracking Service Requests

    To track service requests, include the servlet class a field that counts the number of service methods that are running. The field should have synchronized access methods to increment, decrement and return its value:

    public class ShutdownExample extends HttpServlet {
        private int serviceCounter = 0;
        ...
        // Access methods for serviceCounter
        protected synchronized void enteringServiceMethod() {
            serviceCounter++;
        }
        protected synchronized void leavingServiceMethod() {
            serviceCounter--;
        }
        protected synchronized int numServices() {
            return serviceCounter;
        }
    }
    

    The service method should increment the service counter each time the method is entered and decrement the counter each time the method returns. This method call super.service to preserve the functionality of the original service method:

    protected void service(HttpServletRequest req,
                           HttpServletResponse resp)
                           throws ServletException,IOException {
        enteringServiceMethod();
        try {
            super.service(req, resp);
        } finally {
            leavingServiceMethod();
        }
    }
    

© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy