I’m trying to tracking valid user Ids in my Java servlet, can I implement HttpSessionListener this way ?
public class my_Servlet extends HttpServlet implements HttpSessionListener { String User_Id; static Vector<String> Valid_User_Id_Vector=new Vector<String>(); private static int activeSessions=0; public void sessionCreated(HttpSessionEvent se) { // associate User_Id with session Id; // add User_Id to Valid_User_Id_Vector Out(' sessionCreated : '+se.getSession().getId()); activeSessions++; } public void sessionDestroyed(HttpSessionEvent se) { if (activeSessions>0) { // remove User_Id from Valid_User_Id_Vector by identifing it's session Id Out(' sessionDestroyed : '+se.getSession().getId()); activeSessions--; } } public static int getActiveSessions() { return activeSessions; } public void init(ServletConfig config) throws ServletException { } public void destroy() { } protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { User_Id=request.getParameter('User_Id'); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return 'Short description'; } }
How to get the listener notified when a session ends ? I’m trying to bypass ‘/WEB-INF.web.xml’ all together, is it doable ? Or does it make sense ?
This won’t bypass
/WEB-INF/web.xml. Furthermore, you’ll end up with 2 instances of this class, not 1 performing both functions. I suggest you put this Vector in theServletContextand have 2 separate classes.In the servlet, you get to it via
getServletContext(). In the listener, you’ll do something like this: