今天在尝试servlet中的session,在资料上看到,当浏览器关闭后,session会失效,但是当我使用IE和firefox出现了不同的情况。当我使用IE的使用,关闭IE后,session失效了,但是使用firefox,session依然是有用的,请问这个到底是怎么回事?

解决方案 »

  1.   

    cookie分两种,一种是会话cookie也就是你们所说的session,session本质就是cookie,只是会话cookie不存放在本地硬盘,存放在浏览器分配的内存块中。另一种就你们说的那种cookie,存放在本地硬盘的浏览器缓存文件夹下。为什么火狐关闭了还有,这得看你当时火狐的进程状况和你的设置。另外,开了firebug会影响火狐的行为。我遇到这种情况,一般是火狐窗口关闭了,但是进程还在。过一会,火狐的进程自己停止了,再打开也就没了。
      

  2.   

    默认情况下关闭浏览器 session都失效吧,除非显式指定响应头set cookie的expires属性
      

  3.   

    这是我之前写的一段代码,令session在浏览器关闭后不失效         /**
     * @author Zhou Hao, Fri, 20 Jul 2012 20:11:14 EST
     * 
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // This method is used to test the functionality through which session information
    // can be retrieved even if a browser has been closed.
    // This is achieved by setting related HTTP response header, that it, "Set-Cookie".
    // The implementation of getSession() will not specify the age of the cookie (named as JSESSIONID),
    // which means that a programmer has to reset the expiration information manually. 

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);
    if(session !=null){
    // if session has been set, just show it.
    out.print(session.getId());
    }else{
    out.print("no session<br/>");
    HttpSession session2 = request.getSession();
    Collection<String> names = response.getHeaderNames();
    for (String name : names) {
    if("Set-Cookie".equals(name)){
    // Get GMT timezone
    TimeZone zone = TimeZone.getTimeZone("GMT");
    // For testing purpose, I just set the expiration time as 2 minute after from now on.
    Date d = new Date(System.currentTimeMillis()+60*1000);
    // Set the date format in Set-Cookie header in accordance with HTTP specification.
    // Example: "Set-Cookie ...;Expires=Wed, 09 Jun 2021 10:18:14 GMT".
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
    // Set timezone as GMT. 
    //The SimpleDateFormat will convert the default timezone (in this machine is EST)
    // to GMT timezone.
    sdf.setTimeZone(zone);
    // Format the date.
    String date = sdf.format(d);
    // Append the expiration information to response header Set-Cookie
    response.setHeader(name, response.getHeader(name)+"; Expires="+date);
    }
    }
    }
    }