Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SessionContext in JBOSS

Tags:

jboss

ejb

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!

like image 417
Ryan Avatar asked Dec 21 '09 06:12

Ryan


People also ask

How can I get SessionContext in EJB?

Method SummaryObtain a reference to the EJB local object that is associated with the instance. Obtain a reference to the EJB object that is currently associated with the instance. Obtain the business interface or no-interface view type through which the current business method invocation was made.

What is SessionContext?

The SessionContext interface provides access to the runtime session context that the container provides for a session bean instance. The container passes the SessionContext interface to an instance after the instance has been created.


1 Answers

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.

like image 120
Pascal Thivent Avatar answered Oct 20 '22 22:10

Pascal Thivent