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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With