tags:

views:

313

answers:

1

I tried several ways in the session bean, like:

@Resource
private SessionContext ctx;

OR

private SessionContext ctx;

@Resource
private void setSessionContext(SessionContext ctx) {
  this.sctx = ctx;
}

OR

InitialContext ic = new InitialContext();
SessionContext ctx = (SessionContext) ic.lookup("java:comp/env/sessionContext");

None of them worked, differnet exceptions occured in JBOSS.

I really get mad about it. Anyone could tell me what's wrong. Thanks a lot!

A: 

The two first solutions (field injection and setter method injection) look fine and should work.

I have a doubt about the third one (the lookup approach) as you didn't show the corresponding @Resource(name="sessionContext") annotation but it should work too if properly used.

A fourth option would be to look up the standard name java:comp/EJBContext

@Stateless
public class HelloBean implements com.foo.ejb.HelloRemote {
  public void hello() {
    try {
      InitialContext ic = new InitialContext();
      SessionContext sctxLookup = 
          (SessionContext) ic.lookup("java:comp/EJBContext");
      System.out.println("look up EJBContext by standard name: " + sctxLookup);
    } catch (NamingException ex) {
      throw new IllegalStateException(ex);
    }
  }
}

These four approaches are all EJB 3 compliant and should definitely work with any Java EE 5 app server as reminded in 4 Ways to Get EJBContext in EJB 3. Please provide the full stack trace of the exception that you get if they don't.

Pascal Thivent