0

我正在尝试在我的 Java servlet 中跟踪有效的用户 ID,我可以这样实现 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”,可行吗?还是有意义?

4

1 回答 1

3

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

在 servlet 中,您可以通过getServletContext(). 在侦听器中,您将执行以下操作:

public void sessionCreated(HttpSessionEvent se) {
    Vector ids = (Vector) se.getSession().getServletContext().getAttribute("currentUserIds");
    //manipulate ids
}
于 2008-11-18T20:10:52.093 回答