How to get SessionContext in JBOSS

2019-02-03 17:41发布

问题:

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!

回答1:

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.



回答2:

You can list these bindings using the following code, it will show you whats available in the context. (This uses groovy code to do the iteration (each) over the enumeration)

Context initCtx = new InitialContext();
Context context = initCtx.lookup("java:comp") as Context
context.listBindings("").each {
   println it
}

Dependending if this code is run in an ejb context or web context you would see different output.



标签: jboss ejb