Remove/destroy session scoped CDI managed bean

2019-01-28 05:32发布

I have a session scoped CDI managed bean:

@Named
@SessionScoped 
public class SampleBean implements Serializable {
    // ...
}

I need to remove this bean from the session after a certain flow for which I used the following code like as seen in this answer:

ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getSessionMap().remove("sampleBean");

However, it does not work and the SampleBean remains in the session.
Am I missing something?

2条回答
smile是对你的礼貌
2楼-- · 2019-01-28 05:58

In contrary to JSF managed beans, CDI managed beans are not stored directly by their managed bean name in the session map. They are instead stored in server's memory by the CDI manager implementation (Weld, OpenWebBeans, etc) using e.g. session ID as key.

The trick which you used there is therefore not applicable on CDI managed beans. You need to look for an alternate approach. The right approach in this particular case is to use @ConversationScoped instead of @SessionScoped. In properly designed web applications, there should never be the need to manually terminate a scope. So using @SessionScoped for a conversation/flow was already wrong in first place.

查看更多
何必那么认真
3楼-- · 2019-01-28 05:58

And this ¿?

FacesContext .getCurrentInstance() .getApplication() .createValueBinding( "#{yourBeanName}").setValue(FacesContext.getCurrentInstance(), null );

查看更多
登录 后发表回答