Invalidate specific jsf bean session

岁酱吖の 提交于 2020-02-04 23:10:33

问题


How I invalidate a specific bean in a session?

I have this example code. I test with ExternalContext.invalidateSession(); but it destroy all beans in the session in the application since it destroys the full session.

@Named
@SessionScoped
class Managed implements Serializable {

       public void invalidate (){
           // lines //
           externalContext.invalidateSession();   
       }

}

but, with invalidateSession all beans in the session are destroyed, I want to invalidate only the one specific "Managed" bean, how I do that?


回答1:


Ignoring the fact that you're not clear on how you want to implement this solution, to start

  1. Inject the BeanManager into wherever you plan to execute the logic. It has to be a managed component

    @Inject
    BeanManager beanManager;
    

    The bean manager is the component that will grant you access to all the CDI beans (and other stuff) within your context.

  2. You then use the BeanManager to get a contextual reference to the bean you're interested in

    Bean<Managed> bean = (Bean<Managed>) beanManager.resolve(beanManager.getBeans(Managed.class));
    Managed managedBean= (Managed) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)
    
    managedBean = null; //or whatever you want to do with it
    

This solution should destroy the active instance of that session bean; if another attempt is made to use that same bean, CDI will most likely create a brand new instance on-demand




回答2:


While the approach with BeanManager is viable, I would suggest slightly different approach.

You should be able to @Inject HttpSession into your managed @SessionScoped bean and then invoke invalidate() on that session.

Something along these lines:

@Named
@SessionScoped
class Managed implements Serializable {
       @Inject
       HttpSession session;

       public void invalidate (){
           session.invalidate(); //invalidates current session  
       }    
}

Yet another way to achieve this is to make use of FacesContext. You were on the right track but you need to take one extra step:

((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true)).invalidate();


来源:https://stackoverflow.com/questions/38401786/invalidate-specific-jsf-bean-session

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!