2008-11-18 72 views
0

我想跟踪我的Java servlet中的有效用户ID,我可以用这种方式实现HttpSessionListener吗?我可以用这种方式实现HttpSessionListener吗?

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

如何在会话结束时通知监听器?我试图绕过“/WEB-INF.web.xml”,是否可行?或者它有道理?

+0

因为这关系到你原来的问题,作为后续,它可能是最好的发布后续问题为你原来的问题的一部分。 – 2008-11-18 20:51:32

回答

3

这不会绕过/WEB-INF/web.xml。此外,你最终会得到这个类的两个实例,而不是1个执行这两个函数。我建议你把这个Vector放在ServletContext里,并且有2个独立的类。

在servlet中,通过getServletContext()得到它。在监听器,你会做这样的事情:

public void sessionCreated(HttpSessionEvent se) { 
    Vector ids = (Vector) se.getSession().getServletContext().getAttribute("currentUserIds"); 
    //manipulate ids 
} 
相关问题