3

I have a @SessionScoped cdi bean which is used to track user session information in my web application. Is there any way to find all objects of this bean from another @ApplicationScoped bean?

yayayokoho3
  • 1,209
  • 2
  • 16
  • 40

1 Answers1

2

You cannot do this out of the box. Java EE forbid this kind of things for security reason.

Now you can imagine a more elaborate approaches to keep track of these session beans at your application scope level. The cleanest way would be to produce them from an @ApplicationScoped bean :

@ApplicationScoped
public class Registry {
  private List<SessionData> data = new ArrayList<>;

  @Produces
  @SessionScoped
  public SessionData produceSessionData() {
    SessionData ret = new SessionData();
    data.add(ret);
    return ret;
  }

  public void cleanSessionData(@Disposes SessionData toClean) {
    data.remove(toClean);
  }
}

Note the @Dispose method which will be called when your produced bean has ended its lifecycle. A convenient way to keep your list up to date and avoid extra memory usage.

Antoine Sabot-Durand
  • 4,875
  • 17
  • 33
  • Thank you Antoine for valuable answer. I had to do the job with the help of a HashMap inside my ApplicationScoped bean, which is loaded with unique userId and related SessionScoped bean's object when successful login happens and then removing the related session bean object from HashMap inside PreDestroy event of SessionScoped bean. And I must give a try your solution too. Thanks again. – yayayokoho3 Nov 20 '14 at 10:51