Tomcat JSF 会话 BEan @Predestroy "Session already invalidated"

Tomcat JSF Session BEan @Predestroy "Session already invalidated"

所以我尝试使用

@SessionScoped JSF 托管 bean 上的 @PreDestroy 方法上访问 HttpSession 的属性
session.getAttribute("myAttribute"); 

但是我得到了

java.lang.IllegalStateException: getAttribute: Session has already been invalidated

为什么?

在我的会话 bean 之一被销毁之前,我需要访问该会话打开的外部服务的连接列表,它们当然存储在会话属性对象中。

我该怎么做?

显式访问会话范围托管 bean 中的会话属性没有意义。只需将该属性设为会话作用域托管 bean 本身的 属性。

@SessionScoped
public class YourSessionScopedBean implements Serializable {

    private Object yourAttribute; // It becomes a session attribute already.

    @PreDestroy
    public void destroy() {
        // Just access yourAttribute directly, no need to do it the hard way.
    }

}

您遇到的异常发生是因为会话是通过 HttpSession#invalidate() 调用而不是 "just" 过期显式无效的。