O'Reilly logo

Head First EJB by Bert Bates, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

SessionContext

You need it more than it needs you

At the beginning of a bean’s life, and only once in the bean’s life, the Container calls the bean’s setSessionContext() container callback method.

That context (a subclass of EJBContext) is the bean’s lifeline to the Container, and it’s the only thing the bean can call methods on to get references to his own home and EJB object, to get security information about the client, or to do transaction-related things. We won’t look at the security and transaction info now; they’re both covered in separate chapters.

image with no caption

Note

Memorize the SessionContext interface!

You must be able to look at a list of methods, and know which belong to the SessionContext interface. And remember, a lot of the questions related to lifecycle are about knowing the methods from which you can call certain methods on your context. For example, you have to know that you can’t get client-related info from your context in the ejbCreate() method of a stateless bean. Because there’s no client associated with a stateless bean’s ejbCreate()! But you CAN get client info from your context from a stateful bean’s ejbCreate(), because a client initiated it.

Things you can do with your SessionContext (9 methods, 4 categories)

  • get a reference to your home

    getEJBHome()
    getEJBLocalHome()

  • get a reference to your EJB object

    getEJBObject()
    getEJBLocalObject()

  • get security information about the client

    getCallerPrincipal()
    isCallerInRole(String s)

  • force a transaction to rollback (CMT only)

    setRollbackOnly()
  • find out if the transaction has already been set to rollback (CMT only)

    getRollbackOnly()
  • get a transaction reference, and start your own transaction (BMT only)

    getUserTransaction()
image with no caption

Relax

You don’t need to know the three deprecated methods.

Besides the ones shown on this page, the EJBContext interface has three other methods, all of which have been deprecated. You’re not tested on deprecated methods, so if you see them in the API, don’t panic. The only reason you need to know about them is in case you’re working with older EJB code. The methods are:

isCallerInRole(Identity id)

getCallerIdentity()

getEnvironment()

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required