我正在尝试跟踪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”,它可行吗?或者它有意义吗?
答案 0 :(得分: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
}