< Zurück | Inhalt | Weiter >

23.2.2 Using Our Bean

We have put a lot of pieces in place to get a bean that we can call from across the enterprise. But what does that call look like? How might we make use of the bean?

The first step is to make contact with the JNDI service and locate the home interface for the bean. It looks like the section of code in Example 23.5.


image

Example 23.5 Locating the home interface

//Look up home interface

InitialContext initctxt = new InitialContext(); Object obj = initctxt.lookup("ejb/Money");

MoneyHome homer = (MoneyHome) PortableRemoteObject.narrow(obj, MoneyHome.class);


image


We’re putting this code in the init() method of a servlet; it could also be in a test program, or in a JSP. It needs to happen only once for our servlet (which is why we put it in the init() method) and then the connection can be used many times, once for each contact with the bean.

We get to the actual bean this way:


Money mrbean;

mrbean = homer.create();


We then use the bean, making the calls on its remote interface (a Money object, that extends EJBObject) as if it were just a simple method call on an ordinary class:


car = mrbean.save(20000.00, 0.04, 250.00);


The math is done in the actual SessionBean, out there in the network, and the results are sent back to this application. Our application goes on to display this number as part of an HTML page.

Then when we’re done with the bean, we need to clean up:


mrbean.remove();