日期:2014-05-17  浏览次数:20697 次

初学者关于session的疑惑
淘宝或者csdn上用户选择免登陆后,关闭浏览器再次打开,发现自己还在线,这并不能说session没有失效,我觉得是因为服务器的数据库中存入了与客服端cookie里面一样的值,用户再次请求的时候,服务器获取了cookie的值与服务器数据库的值做了匹配,匹配上了,则直接取出所匹配的值,这个值就是用户的信息如用户名密码之类的,然后在登录该用户,所以你可以在一周之类不用登陆,其实是服务器帮你登录,但这跟session无关,不能用用户在不在线,来判断session的存在。
所以觉得这个结论还是对的:
session死亡 发生在以下情况:
1.session的持有者(即客户端浏览器)在最大无活动等待时间(MaxInactiveInterval)内无任何响应或请求
2.session被调用invalidate()方法强制弊了
3.jsp服务器重起或发生中断(此时应该是所有session都当了)

用户关闭浏览器后标志着
a.session将不再发送请求到服务器
b.该session将不会有人调用他的invalidate()方法
 所以,此时只能等待session自己超时死亡,如果设置了该session的MaxInactiveInterval为-1,那么这个session只有在第3种情况下才能死了. 

------解决方案--------------------
可以这样去销毁 session
package com.ack.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DestroyAServletSession extends HttpServlet {
  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletExceptionIOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();
    pw.println( "<HTML><BODY>" );

    // get current session, and don't create one if it doesn't exist
    HttpSession theSession = req.getSession( false );

    // print out the session id
    if( theSession != null ) {
      pw.println( "<BR>Session Id: " + theSession.getId() );
      synchronized( theSession ) {
        // invalidating a session destroys it
        theSession.invalidate();
        pw.println( "<BR>Session destroyed" );
      }
    }

    pw.println( "</BODY></HTML>" );
    pw.close();
  }
}