Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hold session in stateful EJB 3.1 bean?

I'm working on a Java webapp trying to combine the following technologies:

  • Java EE 6
  • CDI
  • JSF 2
  • EJB 3.1
  • Spring Security

I provide CDI-based backing beans (@ViewScoped, @Named) for my JSF pages.

I use @Stateless EJB beans for the actual work to be done.

I only need few session information like jSessionCookie (managed by container), internal username and some other internal IDs. Now, I wonder where to put this session information so that I can access it in the backing beans for JSF, but also provide it to the stateless EJBs? Should I use a @Stateful EJB session bean or should I create CDI-based POJO with @SessionScoped and @Named?

Are there any best practices?

like image 542
Sebi Avatar asked Aug 21 '12 19:08

Sebi


2 Answers

For your particular use case, a stateful session bean would not be a good choice.

Do note that contrary to what people may claim, stateful session beans are surely not something you should generally avoid. However, they are for advanced use cases, for instance when dealing with JPA's extended persistence context.

The reason why stateful session beans would not work here, is that they are not automatically associated with the HTTP session, which seems to be your prime concern. You could add the @SessionScoped annotation to them, but then you could just as well use a regular managed bean. You would not use any of the particular features of a SFSB.

See alo:

  • Can I use EJB Stateless Bean with CDI to maintain user session?
  • Using a Stateful Session Bean to track an user's session
  • Calling a CDI session scoped producer method from an EJB stateless session bean
  • Contexts and Dependency Injection in Java EE 6

You can inject your stateless EJBs with a session scoped CDI bean, but you have to realize that within the same application your EJB bean would be dependent on the HTTP session then (something you sometimes want to avoid, e.g. if your bean has to be called from other contexts as well).

like image 138
Arjan Tijms Avatar answered Sep 21 '22 17:09

Arjan Tijms


@Stateful EJB is something I'd try to stay away from. I believe behavior and state are things that should not be mixed.

I would also go for SJuan76's answer and use SessionScoped JSF backing bean.

like image 45
Peter Butkovic Avatar answered Sep 19 '22 17:09

Peter Butkovic