Java 在servlet中检查会话是否有效

Java 在servlet中检查会话是否有效,java,session,servlets,Java,Session,Servlets,/****注****/ 在WEB.XML文件中,我正在设置会话超时属性, 因此,会话可能已过期。 /************/ 我正在使用HttpSession对象来管理会话 HttpSesion session = myPersonalMethodThatReturnHttpSessionObject(); //我正在使用Eclipse,它在我放在下面的图中的调试视图中为我提供了以下详细信息 //那个么我怎样才能得到isValid字段或方法的值,这样我就可以在这里输入if条件了 if(se

/****注****/ 在WEB.XML文件中,我正在设置会话超时属性, 因此,会话可能已过期。 /************/

我正在使用HttpSession对象来管理会话

HttpSesion session = myPersonalMethodThatReturnHttpSessionObject();
//我正在使用Eclipse,它在我放在下面的图中的调试视图中为我提供了以下详细信息

//那个么我怎样才能得到isValid字段或方法的值,这样我就可以在这里输入if条件了

if(session != null)
{
    //removing attributes from session 
}
/*************************************更多描述*******************************************/

我的问题是。。。 注1-->会话超时为30分钟

Step1  some one login my web apllication
Step2  session is created.
Step3  if user close web application without signout
Step4  all session attribute is there 
Step5  if another user try to login.
Step6  I try to remove all session attribute and store new attribute value.
Step7  Above functionality work properly but, while session is invalidate can't remove session     attribute so i need to put condition in if session is valid that remove attribute else do nothing so I need to check session is valod or not. 

您应该创建一个具体的类来实现
javax.servlet.http.HttpSessionListener
,并将代码添加到它的两个回调方法中:

public interface HttpSessionListener extends java.util.EventListener {
   void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent);

   void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent);
}

记住在web.xml中注册您的侦听器

使用
HttpServletRequest
对象创建会话,如下所示

HttpSession session = httpServletRequest.getSession();

如果尚未创建会话或返回现有会话对象,这将为您提供新会话。

方法中的某个地方
myPersonalMethodThatReturnHttpSessionObject()
添加以下行

HttpSession session = request.getSession(false); 

这将帮助您找到有效的会话。

因为您看到的是
isValid=false
,我猜您的会话已无效/timedout

您应该调用
HttpSession session=request.getSession(true)
HttpSession session=request.getSession()
以始终获取有效会话

方法
request.getSession(true)
将确保在当前会话无效时创建新会话。如果当前会话有效,它将返回相同的会话


方法
request.getSession()默认调用
request.getSession(true)

根据您的更新,您的登录过程应如下所示:

HttpSession session = request.getSession(false);  // returns null if no session or session is invalid
if(session != null) {
    // you have old session
    session.invalidate();  // invalidate session - this will remove any old attrs hold in the session
}
// create new session
session = request.getSession(); // creates new empty session
....

无法直接获取
isValid
字段。
request.getSession(false)
正在使用它,如果当前会话无效,它将返回
null
。如果会话已经无效,您不必删除属性,因为它们已经被删除,并且会话不再可访问。

请提供更多说明如何使用它,这样可以更容易地提供好的解决方案。我正在更新我的问题。。。