Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

More Details About Session Beans

Now that you have a feel for the structure of session beans and what it takes to implement them, there are a few more details you need to know to be more effective when designing and developing session beans.

The SessionBean Interface

Every session bean must implement the SessionBean interface, which contains four methods. The EJB container uses these methods to manage the session bean.


A SessionContext object contains information about the environment the session bean is running in. It contains a reference to the bean's Home interface, a reference to the bean itself, transaction information, and the identity of the caller who invoked a specific method.

The setSessionContext method is called once for each session bean and is part of the initialization of the bean. The bean is an active part of the EJB container after setSessionContext and remains active until the ejbRemove method is called.


The setSessionContext method is a great place to put initialization code. You might, for instance, want to create a database connection or locate another bean's Home interface in setSessionContext.

Of the methods in the SessionContext interface, getEJBObject is the one that you'll probably call the most. Sometimes, an EJB must pass itself to another method call. For example, suppose you have a ShoppingCart session bean that contains items that a user wants to order. Furthermore, suppose that you have an OrderPlacement session bean that takes the contents of a shopping cart and enters it into your ordering system. You often find situations like this when a company has an existing ordering system, possibly even on a mainframe. If you ever plan to migrate the ordering system to another platform, maybe from the mainframe to an EJB server, you want to design the ShoppingCart bean so it doesn't care how the order is entered-its only task is to manage the items you want to buy. The OrderPlacement bean takes care of placing the order. When you change over to a new ordering system, just change the OrderPlacement bean and leave the shopping cart alone.

Now, when the ShoppingCart bean needs to call the OrderPlacement bean, you would think it could just pass itself using the this keyword. In other words, it might do something like this:


The problem here is that the submitOrder method is probably declared something like this:

public void submitOrder(ShoppingCart cart) throws RemoteException;

This is a problem because ShoppingCart is a Remote interface for a session bean (for this example, at least). The this variable would refer to a ShoppingCartImpl object, however, which doesn't implement the ShoppingCart interface. When you first start working with EJBs, these distinctions can be a little confusing. An EJB really has two parts: the Remote interface and the implementation. The implementation is not a remote object. That is, it does not implement the Remote interface. In fact, in many EJB implementations, the Remote interface invokes a method in the container, and the container invokes a method in the implementation, just as it does for the standard methods, such as ejbCreate and ejbRemove.

The correct way to call the submitOrder would be


This code assumes, of course, that your setSessionContext method does this:

public void setSessionContext(SessionContext aContext)
    sessionContext = aContext;

Even if you don't need the session context in your bean, it's still a good idea to keep track of it. It only takes a few lines of code and you can always count on it being there.


If you decide to make it a standard practice to keep the session context, make sure you also standardize the access to the context. In other words, either pick a standard variable name for the context that every developer can count on, or create a standard method name, such as getSessionContext.


The EJB container calls a session bean's ejbRemove method to tell the bean it is going out of service. The bean should clean up any resources it is holding on to.


If your bean establishes a database connection in the setSessionContext method, close down the connection in the ejbRemove method. If you create any session beans, remove them in the ejbRemove method, and if you locate any Home interfaces, set them to null.

ejbPassivate and ejbActivate

One of the interesting aspects of the Enterprise JavaBeans specification is that it pro- vides various ways for EJB containers to do load balancing and various other kinds of performance-related operations. Passivation/activation is one such operation, and it is similar to the way your computer manages memory.

Most modern operating systems use a concept called virtual memory, where instead of keeping everything in RAM memory, the operating system writes some information out to disk.

Over time, the least-recently used memory areas are written to disk (this technique is called "swapping"). You might notice sometimes that if you start up an application and then minimize or iconify it (depending on what windowing environment you are using) and run a lot of things, it takes a while to display the application when you finally try to access it again. This happens because application's memory areas were written out to disk to free up space for the other stuff you were running. The delay is caused by the computer reading the information back off the disk.

The ejbPassivate and ejbActivate methods allow an EJB container to perform swapping. If, at some point, the EJB container realizes that it has a lot of beans in memory that haven't been accessed in a while, it might choose to store some of those beans to disk. The idea is that the EJB container uses object serialization to store infrequently used beans to a file somewhere. This process, in EJB, is called passivation. When a client tries to access a passivated bean, the EJB container activates the bean again by reading it back from the disk.

The ejbPassivate and ejbActivate methods help the EJB container solve a messy problem-you can't serialize certain "live" operating system resources such as network connections. Because most database connections involve a network connection, this means you can't serialize database connections, either.

If you establish a database connection in your setSessionContext method, you must do something with that connection when the EJB container needs to passivate the session bean. Specifically, you should close the connection and set the connection variable to null. When the EJB container calls your ejbActivate method, re-establish the connection.


Don't be fooled into thinking that ejbActivate is called when the session bean is first created. The ejbActivate method is only called sometime after the ejbPassivate method has been called.

Session Bean Requirements, Restrictions, and Permissions

The EJB specification places some specific restrictions and requirements on session beans. Some of these requirements indicate things that a bean must do, others indicate things a bean must not do, and others specify methods and interfaces that a bean must implement. There are also things that the specification specifically allows, just in case you might get the impression that they were forbidden by other restrictions.

Implement the SessionBean Interface

You probably wouldn't think of creating a session bean that doesn't implement javax.ejb.SessionBean, but just in case the thought crosses your mind, forget it!

Declare the Class as Public, and Not Final or Abstract

Remember that the EJB container needs to create instances of the bean, so the class must be public and concrete (non-abstract).

Create a Public, Parameterless Constructor

Again, the EJB container must create instances of the bean. If the constructor is protected or private, the container can't create the instance.

Don't Implement a finalize Method

Although you rarely need to define a finalize method in the first place, the EJB specification explicitly forbids finalize in both session and entity beans. If your bean needs to do any cleanup, it should do it in the ejbRemove method or in ejbPassivate.

Implement the create Method and Any remote Methods

A session bean must implement any create methods specified in the Home interface, and all methods specified in the Remote interface. In implementing these methods, there are several additional requirements:

  • The methods must be public and cannot be static or final.

  • The parameters and return types must be valid RMI/IIOP return types. In general, this means that they must either be native types (int, char, double, and so on), serializable objects, or Remote interfaces.

  • The method name can't start with ejb (this might confuse an EJB deploy tool and possibly create conflicts).

Optionally Implement the Remote Interface

It might sound strange to say that a bean can implement the Remote interface, but is not required to. The distinction is subtle but extremely important. The methods in the implementation class must have the same method signatures as those in the Remote interface, except that the methods in the implementation class are not required to throw RemoteException. In other words, although every method in the Remote interface must have a corresponding method in the implementation class, the implementation isn't required to implement the Remote interface with a declaration like this:

public class ShoppingCartImpl implements SessionBean, ShoppingCart

The reason you might be tempted to implement the Remote interface is that the compiler will then tell you when you miss a method. In other words, if your implementation class doesn't implement a method in the Remote interface, the compiler generates an error. Otherwise, you won't know about the missing method until you run a deployment tool or a packaging tool. The longer it takes you to learn about an error, the longer it takes to fix it because you must repeat more steps.

The problem with implementing the Remote interface is that you might accidentally try to pass the object using the this keyword when you should really be using the getEJBObject method in the session context. Normally, when you accidentally use this instead of getEJBObject, the compiler generates an error because it is expecting an object that implements the Remote interface, and the implementation class doesn't. By implementing the Remote interface, you get around the compiler error, but you end up with a runtime error because the implementation is not really a proper reference to a Remote interface as the EJB container expects.


Although implementing the Remote interface can point out errors at compile time, it can also cause errors that might not be discovered until runtime, which can be much costlier to fix. You are better off not implementing the Remote interface and discovering some errors at deployment time.

Optionally Implement the SessionSynchronization Interface

The SessionSynchronization interface gives a session bean better control over how a transaction takes place. You will learn more about this interface and how to use it in Chapter 8, "Using Container-Managed Persistence."

Subclass Another Class When Necessary

Just in case you were worried about it, your implementation class might be a subclass of another class. In fact, that superclass could even be the implementation class for another kind of bean.

Implement Helper Methods as Necessary

An implementation class might have additional helper methods that are not part of the Remote or Home interfaces. There are no restrictions on the kinds of parameters, the return type, or the visibility (public, protected, private) of the method.

Don't Throw RemoteException

If you need to throw an EJB-related exception, throw javax.ejb.EJBException instead.

Remote and Home Interface Restrictions

In addition to the restrictions on the implementation class, there are some restrictions on the Remote and Home interfaces. Most of these restrictions are similar to ones you have already seen for the implementation class.

Remote Interfaces Must Extend javax.ejb.EJBObject

When you use some deployment tools, such as the one provided by WebLogic, you'll notice that it automatically knows which class contains the Remote interface. It looks for the EJBObject interface to detect a Remote interface. Furthermore, the EJBObject interface contains some additional methods that every EJB must implement.

Home Interfaces Must Extend javax.ejb.EJBHome

As with the Remote interfaces an EJBObject, the EJBHome interface helps identify Home interfaces and defines some methods that you can invoke on every Home interface.

Parameters and Return Types Must Be Valid for RMI/IIOP

Again, this generally means the types must either be native types, serializable objects, or Remote interfaces.

All Methods Must Throw java.rmi.RemoteException

Because the Home and Remote interfaces extend the java.rmi.Remote interfaces, all the methods in the interfaces must throw java.rmi.RemoteException. The RMI specification explicitly requires all methods in a remote interface to throw RemoteException.

All Methods Must Have Corresponding Implementations

Normally, in a typical RMI implementation, this would go without saying because the implementation class would implement the Remote interface. In the case of EJB, however, because the implementation class isn't required to implement the Home and Remote interfaces, the compiler can't enforce the relationship between the implementation class and the Home and Remote interfaces.

Each create method in the Home interface must have a corresponding ejbCreate method in the implementation class. Also, the create method must throw CreateException.

Interfaces Can Extend Other Interfaces

To support subclassing of Enterprise JavaBeans, the Home and Remote interfaces can extend other interfaces, as long as the parent interfaces are descendants of EJBObject (for Remote interfaces) or EJBHome (for Home interfaces).

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020