0

as discussed here Display username in jsp redirected from a servlet to get the same instance of a Stateful Session Bean, i have to save it in the HttpSession related. It is working good, but in a servlet i did so:

SessionCart cart = (SessionCart) request.getSession().getAttribute("cart");
if (cart==null){
   cart = new SessionCart();}

Where the attribute "cart" is the one where i saved the initialized cart. The problem is that, if the cart was not initialized before, the row cart=new SessionCart(); initialize a bean not related to Context, so the entitymanager got by @PercistenceContext is null. I tried to use the annotation

@EJB
private SessionCart cart;

but this one create a new session cart anyway, without my control (so if i have a cart related to user yet, i create a new one and i trash it... this is not so good). My question is: could i create a new Stateful Session Bean without using annotation @EJB and getting it related to context? So i can control when i want to create it

Community
  • 1
  • 1
Neo87
  • 63
  • 1
  • 11

1 Answers1

0

If I get it correct, you want to initialize your bean lazy.

To control/create your bean at runtime you could use Instance<Bean> Java EE API

In your case it would look like that:

@Inject
private Instance<SessionCart> sessionCartInstance;

if (cart == null) {
    cart = sessionCartInstance.get();
}
  • i found even the way ses = (SessionCart) new InitialContext().lookup("java:global/ibei/ejb/SessionCart"); what do you think is better? It's the first time i see Instance class – Neo87 Feb 05 '15 at 14:54
  • This is a manual lookup, if you don't use remote EJBs I would prefer Instance as it is type safe. – Kescha Skywalker Feb 05 '15 at 18:13
  • Thx, great explaination, finally i found a great way to do it! – Neo87 Feb 09 '15 at 10:47