gpt4 book ai didi

java - 我可以这样实现 HttpSessionListener 吗?

转载 作者:行者123 更新时间:2023-12-02 00:56:01 24 4
gpt4 key购买 nike

我正在尝试在 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";
}
}

如何在 session 结束时通知监听器?我正在尝试一起绕过“/WEB-INF.web.xml”,这可行吗?或者说有道理吗?

最佳答案

这不会绕过/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
}

关于java - 我可以这样实现 HttpSessionListener 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/299947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com