简体   繁体   中英

Set Expiry date to Session cookie

I want to achieve this browser cookie -

  1. Cookie should expire in 15 mins.
  2. Cookie should expire when browser closed.

Which ever happens first. Any help would be really appreciated.

Thank you

Everything you need is here: http://www.quirksmode.org/js/cookies.html

var name = 'My Cookie',
    value = 'foobar';

// Set a cookie without an expires header so it goes away on browser close
document.cookie = name + '=' + value + '; path=/';

// Erase said cookie in 15 minutes if the user left browser open.
setTimeout(function(){

    var date = new Date(),
        days = -1,
        expires = '';

    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = '; expires=' + date.toGMTString();
    document.cookie = name + '=' + value + expires + '; path=/';
}, 60000 * 15 );

You can specify this in your web.xml file. I am pretty sure that when the browser closes the session is ended by default.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app 
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <session-config>
      <session-timeout>15</session-timeout> 
    </session-config>

</web-app>

Within the app you can use the method:

public void setMaxInactiveInterval(int interval)

This is a method on the session object it will override what is in the web.xml file.

Reference: http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpSession.html#setMaxInactiveInterval%28int%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM