How to get SessionContext in JBOSS

元气小坏坏 提交于 2019-12-18 11:56:26

问题


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.



来源:https://stackoverflow.com/questions/1938517/how-to-get-sessioncontext-in-jboss

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!