简体   繁体   English

使特定的jsf bean会话无效

[英]Invalidate specific jsf bean session

How I invalidate a specific bean in a session? 我如何使会话中的特定bean无效?

I have this example code. 我有这个示例代码。 I test with ExternalContext.invalidateSession(); 我用ExternalContext.invalidateSession()测试; but it destroy all beans in the session in the application since it destroys the full session. 但它会破坏应用程序中会话中的所有bean,因为它会破坏整个会话。

@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? 但是,使用invalidateSession会话中的所有bean都被销毁,我想只使一个特定的“托管”bean无效,我是怎么做到的?

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. BeanManager注入您计划执行逻辑的任何位置。 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. bean管理器是允许您访问上下文中所有CDI bean(以及其他内容)的组件。

  2. You then use the BeanManager to get a contextual reference to the bean you're interested in 然后使用BeanManager获取对您感兴趣的bean的上下文引用

     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; 此解决方案应该销毁该会话bean的活动实例; if another attempt is made to use that same bean, CDI will most likely create a brand new instance on-demand 如果再次尝试使用同一个bean,CDI很可能会按需创建一个全新的实例

While the approach with BeanManager is viable, I would suggest slightly different approach. 虽然使用BeanManager的方法是可行的,但我建议略有不同的方法。

You should be able to @Inject HttpSession into your managed @SessionScoped bean and then invoke invalidate() on that session. 您应该能够@Inject HttpSession进入托管的@SessionScoped bean,然后在该会话上调用invalidate()

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 . 另一种实现此目的的方法是使用FacesContext You were on the right track but you need to take one extra step: 你是在正确的轨道上,但你需要采取一个额外的步骤:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM