Client View of Bean  «Prev  Next»

Lesson 6Calling the bean's business method
ObjectiveWrite Java Code to invoke Business Methods

Write Java Code to invoke Business Methods

Write the Java code to invoke a business method on the EJBObject.
On the creation of a new bean instance, the create() returns a remote reference to the bean's EJBObject instance.
Remember that there is a one-to-one relationship between the instances of the EJBObject and the bean.

Calling the bean's business methods

For our Hello bean, the remote interface used by the deployer to build the EJBObject will be similar to the following code skeleton:

View the code below for the EJBObject interface.
public interface Hello extends EJBObject {
 public String sayHello() throws RemoteException, HelloException;
 public String sayHello(String name) throws RemoteException;

Using the remote reference to the bean's EJBObject instance that was returned from create() (see above) and stored in the variable called bean, we can invoke the methods as follows:
try {
 String s = bean.sayHello("fred");
 String s = bean.sayHello();
catch (Exception e) {

If no exceptions were thrown, then running the client would produce:
Hello fred
Hello fred
All remote methods throw java.rmi.RemoteException.
They can also throw bean-specific exceptions such as HelloException, which is thrown when the name in the bean instance has not been initialized.

Removing a bean

To remove the bean instance we use the remove method of the EJBObject:

try {
catch (javax.ejb.NoSuchObjectException e) {
  // ----- 
catch (java.rmi.RemoteException e) {

If the bean instance has already been removed, the NoSuchObjectException will be thrown.

Build Ejb Client - Exercise

Click the Exercise link below to practice building the code for a complete client.
Build EJB Client - Exercise
In the next lesson, you will be introduced to the subtleties of exception handling in the bean.