Implementing the Stateless Session Bean

This section discusses the implementation of the remote home interface SignOnHome, remote interface SignOn and the stateless session bean class SignOnEJB.

Defining the Home Interface

The home interface, SignOnHome, is defined in Listing 5.1.

Listing 5.1. The Full Text of day05/SignOnHome.java
package day05;

import java.rmi.RemoteException;
import javax.ejb.*;

public interface SignOnHome extends EJBHome {
  SignOn create()
     throws CreateException, RemoteException;
}

So, to create a bean instance, you call the create() method on the home interface, and receive a reference to the remote interface.

Note

For a stateless session bean, the return parameter of create() method of home interface must be remote interface instance. Also, a stateless session bean can define a single create() method with no parameters. The throws clause of the create() method must include CreateException. This exception is thrown to the client, when there is a problem in creating or initializing the bean instance.


Note

The remote home interface is a Java Remote Method Invocation (RMI) interface. All RMI interfaces conform to certain rules. The method arguments and return types of a remote method must be legal types for the RMI over Internet Inter-Orb Protocol (RMI/IIOP), such as primitives, serializable objects, and RMI/IIOP remote objects. Each method declared in the remote interface must include java.rmi.RemoteException in its throws clause. This exception is thrown when a remote invocation fails for some reason, such as network failure, protocol errors, and so on.


Defining the Component Interface

The SignOn remote interface is defined in Listing 5.2.

Listing 5.2. The Full Text of day05/SignOn.java
package day05;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;

public interface SignOn extends EJBObject {
   public boolean validateUser(String login, String password)
         throws InvalidLoginException, RemoteException;
}

This interface contains the one business method—validateUser—that is callable by the client. The remote interface is a Java RMI interface. So, method arguments and return types of a remote method must be legal types for RMI/IIOP and the method must include java.rmi.RemoteException in its throws clause. InvalidLoginException is a customized application exception thrown by the SignOn enterprise bean to report an unsuccessful login attempt.

Note

Enterprise JavaBeans define two types of exceptions: application exceptions and system exceptions.

Enterprise beans use application exceptions to signal an error in the business logic to the client. There are two types of application exceptions: predefined and customized. The javax.ejb package includes several predefined exceptions that are designed to handle common problems. For example, javax.ejb.CreateException is a predefined exception. You can code your own customized exceptions to indicate an error in business logic. For example, the SignOn enterprise bean throws InvalidLoginException to report an unsuccessful login attempt.

A system exception indicates a problem with the services that support an application. Examples of these problems include remote invocation failure, failure to obtain database connection, JNDI exceptions, and so on. If your enterprise bean encounters a system-level problem, it should throw a javax.ejb.EJBException. The EJB container logs system exception and throws java.rmi.RemoteException if the client is a remote client, or javax.ejb.EJBException if the client is a local client. If a system exception is thrown, the EJB container might destroy the bean instance.


Implementing the Enterprise Bean Class

Listing 5.3 shows the SignOnEJB enterprise bean class implementation. The stateless session bean implements the javax.ejb.SessionBean interface. It implements the methods setSessionContext(), ejbCreate(), ejbActivate(), ejbPassivate(), and ejbRemove(), as defined in the SessionBean interface. The ejbCreate() method creates an instance of javax.naming.InitialContext and looks up the environment naming context via the InitialContext under the name "java:comp/env". In addition, it implements the validateUser method that accepts the user's login name and password as parameters and returns true if the login is successful. The method throws InvalidLoginException if the login name and password are invalid. For simplicity, this method uses environment entries to validate the user's login name and password. On Day 21, we'll integrate the SignOn bean with an entity bean to store and retrieve the user's login name and password from the database.

Listing 5.3. The Full Text of day05/SignOnEJB.java
package day05;

import java.util.*;
import javax.ejb.*;
import javax.naming.*;

public class SignOnEJB implements SessionBean  {
   private SessionContext ctx;
   private Context environment;

   public SignOnEJB() {
      print("The container created this instance.
");
   }
   /* --- Callback methods --- */
   public void setSessionContext(SessionContext c) {
      print("The container called the setSessionContext method ");
      print("to associate session bean instance with its context.
");
      ctx = c;
   }
   public void ejbCreate() throws CreateException {
      print("The container called the ejbCreate method
");
      print("so that we can initialize the bean instance.
");
      try {
         InitialContext ic = new InitialContext();
         environment = (Context) ic.lookup("java:comp/env");
      } catch (NamingException ne) {
         throw new CreateException("Could not look up context");
      }
   }
   /* Methods ejbActivate and ejbPassivate  are
      not used by stateless session beans
   */
   public void ejbActivate() {}
   public void ejbPassivate() {}

   public void ejbRemove() {
      print("This instance is in the process of being removed ");
      print("by the container.
");
   }

   /* ---Here you implement all business methods
      as defined in the component interface---
   */
   public boolean validateUser(String userName, String password)
    throws InvalidLoginException {
      try {
         String storedPassword = (String) environment.lookup(userName);
         if ( storedPassword.equals(password) ) {
            return true;
         }
         else {
            throw new InvalidLoginException("Invalid login/password");
         }
      } catch(NamingException ne) {
         throw new InvalidLoginException("Invalid login/password");
      }
   }
   void print(String s) {
      System.out.println(s);
   }
}

Note

Because the concepts of activation and passivation are not applicable to stateless session beans, we provide empty implementations for the methods ejbActivate() and ejbPassivate().


Writing the Exception Class

Listing 5.4 shows the InvalidLoginException class. InvalidLoginException derives from java.lang.Exception.

Listing 5.4. The Full Text of day05/InvalidLoginException.java
package day05;

public class InvalidLoginException extends Exception {
   public InvalidLoginException() {
      super();
   }
   public InvalidLoginException(Exception e) {
      super(e.toString());
   }
   public InvalidLoginException(String s) {
      super(s);
   }
}

As mentioned earlier, the SignOn enterprise bean throws InvalidLoginException if the login name and password are invalid.

Declaring the Deployment Descriptors

As you learned on Day 2, the deployment descriptor describes a component's deployment settings. Listing 5.5 shows the ejb-jar.xml deployment descriptor for the SignOn enterprise bean. ejb-jar.xml describes the enterprise bean's deployment properties, such as its bean type and structure. The file also provides the EJB container with information about where it can find, and then load, the home interface, remote interface, and bean class.

Listing 5.5. The Full Text of day05/ejb-jar.xml
<?xml version="1.0"?>

<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>SignOnEJB</ejb-name>
      <home>day05.SignOnHome</home>
      <remote>day05.SignOn</remote>
      <ejb-class>day05.SignOnEJB</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
      <env-entry>
        <env-entry-name>student</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>password</env-entry-value>
      </env-entry>
      <env-entry>
        <env-entry-name>student1</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>password1</env-entry-value>
      </env-entry>
    </session>
  </enterprise-beans>
</ejb-jar>

The ejb-jar element is the root element of the EJB deployment descriptor. It contains the structural information about all the included enterprise beans. The enterprise-beans element contains the declarations of one or more enterprise beans. The session element declares a session bean, and an ejb-name element within the session element defines the session bean's name (SignOnEJB). The session element also declares other things such as the home interface (day05.SignOnHome), the remote interface (day05.SignOn), and the bean's class (day05.SignOnEJB). The session-type element declares that this is a stateless session bean (as opposed to a stateful session bean).

The env-entry element defines an environment property that the enterprise bean can access via JNDI. Each env-entry element describes a single environment entry. The env-entry element consists of the environment entry name relative to the java:comp/env context, the Java type of the environment entry value, the environment entry value, and so on. For example, the value of the environment entry name student is password, and its type is java.lang.String. The SignOn enterprise bean uses environment entries to validate the user's login name and password.

As you learned on Day 2, in addition to the standard ejb-jar.xml, an application typically requires a certain amount of additional environment-specific or vendor-specific binding information. Listing 5.6 shows a weblogic-ejb-jar.xml deployment descriptor that is specific to WebLogic Server.

Listing 5.6. The Full Text of day05/weblogic-ejb-jar.xml
<?xml version="1.0"?>

<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
  <weblogic-enterprise-bean>
    <ejb-name>SignOnEJB</ejb-name>
    <jndi-name>day05/SignOn</jndi-name>
  </weblogic-enterprise-bean>
</weblogic-ejb-jar>

The jndi-name element declares the JNDI name of the enterprise bean. So, the JNDI name of the SignOnEJB is day05/SignOn.

Listing 5.7 shows a jboss.xml deployment descriptor that is specific to JBoss.

Listing 5.7. The Full Text of C:styejbexamplesday05jboss.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>SignOnEJB</ejb-name>
      <jndi-name>day05/SignOn</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

The preceding file declares the JNDI name of SignOnEJB as day05/SignOn.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.167