问题
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
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.
You then use the
BeanManager
to get a contextual reference to the bean you're interested inBean<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