Search code examples
javahttpsession

maxinactiveinterval for some session attributes only


I need to call maxinactiveinterval for http session for some transaction purpose. But i need to implement timeout only for some attributes and al other attributes like user login stuff has to persist. Is there a way to set timeout for some attributes only?


Solution

  • You could store the last access time along with the attribute and when you use the attribute, first check if it is not too old.

    Create a wrapper class for it, something like:

    class AttrWrapper<T extends Serializable> {
        public final T value;
        public final long timeoutMs;
        private long lastAccess = System.currentTimeMillis();
    
        public AttrWrapper(T value, long timeoutMs) {
            this.value = value;
            this.timeoutMs = timeoutMs;
        }
        public boolean isValid() {
            long now = System.currentTimeMillis();
            if (now - lastAccess > timeoutMs)
                return false;
            lastAccess = now;
            return true;
        }
    }
    

    And store it like this:

    // 1 minute timeout:
    session.setAttribute("myattr", new AttrWrapper<>("This is the value", 60*1000));
    

    And access it like this:

    AttrWrapper<?> attr = (AttrWrapper<?>) session.getAttribute("myattr");
    if (attr != null) {
        if (attr.isValid()) {
            // Attribute is valid, you can use it
        } 
        else {
            // Attribute is invalid, timed out, remove it
            session.removeAttribute("myattr");
        }
    }
    

    You can even create a helper, utility method for this so you don't have to repeat code:

    public static <T extends Serializable> T getAttr(String name, HttpSession sess) {
        @SuppressWarnings("unchecked")
        AttrWrapper<T> attr = (AttrWrapper<T>) sess.getAttribute("myattr");
        if (attr == null)
            return null;
        if (attr.isValid())
            return attr.value; // Attribute is valid, you can use it
    
        // Attribute is invalid, timed out, remove it
        sess.removeAttribute("myattr");
        return null;
    }