maxinactiveinterval仅用于某些会话属性

时间:2014-09-09 10:22:53

标签: java httpsession

出于某些交易目的,我需要为{http}会话调用maxinactiveinterval。但是我需要仅针对某些属性实现超时,并且其他属性(如用户登录内容)必须保持不变。有没有办法只为某些属性设置超时?

1 个答案:

答案 0 :(得分:1)

您可以将最后一次访问时间与属性一起存储,当您使用该属性时,首先检查它是否不太旧。

为它创建一个包装类,类似于:

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;
    }
}

并将其存储起来:

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

然后像这样访问:

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");
    }
}

您甚至可以为此创建一个帮助程序,实用程序方法,这样您就不必重复代码:

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;
}