2008-11-18 66 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 
} 
相關問題