BEA Logo BEA WebLogic Server Release 5.1

  Corporate Info  |  News  |  Solutions  |  Products  |  Partners  |  Services  |  Events  |  Download  |  How To Buy

   Introduction to WebLogic Server 5.1:   Previous topic   |   Next topic   |   Contents   |  Index

 

EJB (Enterprise JavaBeans)

 

The Enterprise JavaBeans specification defines a model for component-based applications in Java. WebLogic Server version 5.0 implements the EJB 1.1 specification, including nearly all optional features.

Like JavaBeans, EJBs are reusable software components that can be assembled into applications. But EJBs execute in an EJB Server, WebLogic Server in this case, and they encapsulate business logic instead of GUI objects.

EJB defines separate, independent roles and responsibilities for:

An EJB developer creates an EJB by defining a public EJB interface for the bean and implementing the interfaces for the desired EJB characteristics.

An application developer uses EJBs by calling standard JNDI and EJB methods and the EJB's public interface methods.

An EJB container, such as WebLogic Server, manages an EJB through its life cycle and provides run-time services, such as caching, transaction management, persistence, and tools that support EJB deployment.

System administrators deploy EJBs in the servers they manage. They configure runtime properties for each EJB by modifying a deployment descriptor. The deployment descriptor supplies the EJB server with the information it requires to host the EJB. The deployment descriptor also allows the system administrator to define permissions on an EJB and to configure resources used by an EJB.

The EJB specification establishes "contracts" that define the services provided by each role. Be sure to read the EJB specification before you begin developing or using EJBs. By defining the roles and responsibilities for creating, deploying, hosting, and accessing EJBs, the EJB component model enables you to create your own EBJs or obtain EJBs from other sources and easily incorporate them into applications.

EJBs depend upon, and utilize, other J2EE technologies. For example, you use JNDI to access an instance of an EJB in applications, such as HTTP Servlets or JSP pages. EJBs can use JDBC for persistence and they can use JTA to participate in transactions involving other transactional J2EE technologies such as JMS. They can use RMI or IIOP (CORBA) to operate in a distributed environment.

Types of EJBs

There are two types of EJBs: session beans and entity beans. Each of these has subtypes, which are described in the following sections.

Session Beans

A session bean is a transient EJB instance that serves a single client. The EJB container creates a session bean at a client's request and maintains the bean as long as the client maintains its connection to the bean. Sessions beans are not persistent. Session beans tend to implement procedural logic; they embody actions more than data.

A session bean can be stateless or stateful. Stateless session beans maintain no client-specific state between calls and can be used by any client. They can be used to provide access to services that do not depend on the context of a session, such as sending a document to a printer or retrieving non-updateable data into an application.

A stateful session bean maintains some state on behalf of a specific client. Stateful session beans can be used to manage a process, such as assembling an order or routing a document through a workflow process. With the ability to accumulate and maintain state through multiple interactions with a client, session beans are often the controlling objects in an application. Since they are not persistent, session beans must complete their work in a single session and use JDBC, JMS, or entity beans to record the work permanently.

Entity Beans

An entity bean represents a dataful object, such as a customer, an account, or an inventory item. Entity beans contain data values and methods to act upon those values. The values are saved in a database (using JDBC) or in a file (as a serializable Java object), or in some other data store. Entity beans can participate in transactions involving other EJBs and transactional services, such as JMS.

Entity beans are often mapped to objects in databases. An entity bean could represent a row in a table, a single column in a row, or an entire table or query result. Application requirements determine how beans are mapped to database objects.

An entity bean can employ bean-managed persistence, where the bean contains code to retrieve and save persistent values, or container-managed persistence, where the EJB container loads and saves values on behalf of the bean. With container-managed persistence, the WebLogic EJB compiler can generate JDBC support classes to map an entity bean to a row in a database. Other container-managed persistence mechanisms are available. For example, TOPLink for BEA WebLogic Server, from The Object People, provides persistence for an object relational database.

Entity beans may be shared by many clients and applications. An instance of an entity bean can be created at the request of some client, but it does not disappear when that client disconnects. It continues to live as long as any client is actively using it. When the bean is no longer in use, the EJB container may passivate it-remove the live instance from the server. To minimize accesses to the persistence store, and to optimize server performance, the EJB server administrator can tune the frequency of passivation in a bean's deployment descriptor. For example, the system administrator can specify the maximum number of bean instances to cache and how long to delay passivation when the bean is no longer in use. By configuring each bean independently, the system administrator can tune a WebLogic Server for the combination of applications that share it.

Developing EJBs

Developing an EJB involves implementing interfaces from the javax.ejb package and defining and implementing the bean's public interface. The EJB specification tells you what classes, interfaces, and methods are required for each type of bean. The specification also contains rules that must be followed to ensure that the bean can be deployed in any compliant EJB server.

Some EJB code is generated with tools provided with the EJB server. The WebLogic EJB compiler, weblogic.ejbc, generates this code for WebLogic Server. WebLogic Server also includes DeployerTool, a graphical utility that makes it easy to change WebLogic Server deployment properties, validate beans against the EJB 1.1 specification, and deploy beans in WebLogic Servers.

The Emp example shows how to build a JDBC container-managed entity bean for an existing database table. This example uses the Emp table, which is in the Cloudscape demo database included in the WebLogic Server distribution.

The Emp table has the following SQL definition:

create table emp (
empno int not null,
ename varchar(10),
job varchar(9),
mgr int,
hiredate date,
sal float,
comm float,
deptno int
)

The Emp Enterprise JavaBean example includes these source files:

EmpBeanHome.java extends javax.ejb.EJBHome
Defines the home interface for the Emp bean, including one create() signature, and four finder methods.

Emp.java extends javax.ejb.EJBObject
The public interface for the Emp EJB. It defines a get method for each field, a set method for each field except the primary key (empno), and an htmlToPrint() method that returns a String representing an Emp EJB instance in HTML.

EmpBean.java implements javax.ejb.EntityBean
Contains the implementation for the Emp EJB and the EntityBean methods required by the EJB specification. It declares public variables corresponding to the Emp database table columns. It implements the required ejbCreate() method and overrides several life cycle methods, which are defined in the javax.ejb.EntityBean interface. Finally, it implements each method defined by the Emp interface.

EmpBeanPK.java implements java.io.Serializable
The primary key class for the Emp EJB. The primary key for this database table is the empno column. This class defines the default constructor and a constructor that sets the primary key field for an instance of this class.

ejb-jar.xml
weblogic-ejb-jar.xml
weblogic-cmp-rdbms-jar.xml
These are XML deployment files. ejb-jar.xml contains deployment parameters defined by the EJB specification. ejb-jar.xml references weblogic-ejb.jar.xml and weblogic-cmp-rdbms-jar.xml. weblogic-ejb-jar.xml contains EJB deployment information that is specific to to the WebLogic Server EJB container. weblogic-cmp-rdbms-jar.xml contains WebLogic Server-specific deployment information to map an entity bean to a database using WebLogic Server's container-managed persistence.

Remote Interface

The remote interface defines a public interface for an EJB. The remote interface for the Emp bean is defined in the Emp.java file:

Listing 7-1 Emp.java


package examples.intro;

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

public interface Emp extends EJBObject {

public int getEmpno()
throws EJBException, RemoteException;
public String getEname()
throws EJBException, RemoteException;
public String getJob()
throws EJBException, RemoteException;
public int getMgr()
throws EJBException, RemoteException;
public java.sql.Date getHiredate()
throws EJBException, RemoteException;
public double getSal()
throws EJBException, RemoteException;
public double getComm()
throws EJBException, RemoteException;
public int getDeptno()
throws EJBException, RemoteException;

public void setEname(String newEname)
throws EJBException, RemoteException;
public void setJob(String newJob)
throws EJBException, RemoteException;
public void setMgr(int newMgr)
throws EJBException, RemoteException;
public void setHiredate(Date newHiredate)
throws EJBException, RemoteException;
public void setSal(double newSal)
throws EJBException, RemoteException;
public void setComm(double newComm)
throws EJBException, RemoteException;
public void setDeptno(int newDeptno)
throws EJBException, RemoteException;

public String htmlToPrint()
throws EJBException, RemoteException;
}


The interface defines one get method and one set method for each field. The data types correspond to the JDBC data types of the database table. The htmlToPrint() method returns a String with the employee's data coded as a row in an HTML table. The string can be directed to the output of an HTTP Servlet or JSP page.

Implementation Class

The implementation for the Emp bean is in the EmpBean.java file. The bean implements the javax.ejb.EntityBean interface, which defines several methods that an entity bean must implement. These methods are called by the EJB container (WebLogic Server), at various times during the bean's life cycle. The EmpBean class also implements the methods defined by the Emp interface.

Listing 7-2 EmpBean.java


package examples.intro;

import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.sql.Date;

public class EmpBean implements EntityBean {

protected EntityContext entityContext;

public int empno;
public String ename;
public String job;
public int mgr;
public Date hiredate;
public double sal;
public double comm;
public int deptno;

public EmpBeanPK ejbCreate(int v_empno, String v_ename,
String v_job, int v_mgr,
Date v_hiredate, double v_sal,
double v_comm, int v_deptno)
throws EJBException, CreateException {
empno = v_empno;
ename = v_ename;
job = v_job;
mgr = v_mgr;
hiredate = v_hiredate;
sal = v_sal;
comm = v_comm;
deptno = v_deptno;
return new EmpBeanPK(empno);
}

public void ejbPostCreate(int v_empno, String v_ename,
String v_job, int v_mgr,
Date v_hiredate, double v_sal,
double v_comm, int v_deptno)
throws EJBException
{
// do nothing
}

public void ejbActivate() throws EJBException {
// do nothing
}

public void ejbLoad() throws EJBException {
// do nothing
}

public void ejbPassivate() throws EJBException {
// do nothing
}

public void ejbRemove() throws EJBException {
// do nothing
}

public void ejbStore() throws EJBException {
// do nothing
}

public void setEntityContext(EntityContext ctx)
throws EJBException {
entityContext = ctx;
}

public void unsetEntityContext() {
entityContext=null;
}

public int getEmpno()
throws EJBException, RemoteException {
return empno;
}

public String getEname()
throws EJBException, RemoteException {
return ename;
}

public String getJob()
throws EJBException, RemoteException {
return job;
}

public int getMgr()
throws EJBException,RemoteException {
return mgr;
}

public Date getHiredate()
throws EJBException, RemoteException {
return hiredate;
}

public double getSal()
throws EJBException, RemoteException {
return sal;
}

public double getComm()
throws EJBException, RemoteException {
return comm;
}

public int getDeptno()
throws EJBException, RemoteException {
return deptno;
}

public void setEname(String newEname)
throws EJBException, RemoteException {
ename = newEname;
}

public void setJob(String newJob)
throws EJBException, RemoteException {
job = newJob;
}

public void setMgr(int newMgr)
throws EJBException, RemoteException {
mgr = newMgr;
}

public void setHiredate(Date newHiredate)
throws EJBException, RemoteException {
hiredate = newHiredate;
}

public void setSal(double newSal)
throws EJBException, RemoteException {
sal = newSal;
}

public void setComm(double newComm)
throws EJBException, RemoteException {
comm = newComm;
}

public void setDeptno(int newDeptno)
throws EJBException, RemoteException {
deptno = newDeptno;
}

public String htmlToPrint()
throws EJBException, RemoteException {

String work = "<tr>" +
"<td>" + getEmpno() + "</td>" +
"<td>" + getEname() + "</td>" +
"<td>" + getJob() + "</td>" +
"<td>" + getMgr() + "</td>" +
"<td>" + getHiredate() + "</td>" +
"<td>" + getSal() + "</td>" +
"<td>" + getComm() + "</td>" +
"<td>" + getDeptno() + "</td></tr>";
return work;

}
}


EmpBean.java implements methods from the javax.ejb.EntityBean interface. WebLogic Server calls these methods when an EJB moves from one state to another, for example when the bean moves from active to passive state or to and from the database. These methods do not have any specified behaviors; they are provided so you can perform any actions required when an event changes the bean's status.

In a bean-managed persistence entity bean, the ejbLoad() and ejbStore() methods contain the code to load or save a bean. In Emp, these are notification callbacks that are called after loading or before storing the bean to the database.

An ejbCreate() method is called when a bean is created. You must supply an ejbCreate() method to match each create() method you define in the bean's home interface. This example has one ejbCreate() method that sets all of the fields in the bean. A matching postCreate() method is called after the bean is created to allow the bean to complete any initialization activity required.

The get methods simply return the value of a field. The set methods change the field value.

Home Interface

The home interface defines create methods, which behave like constructors for the bean, and finder methods, which the container calls with application-supplied criteria to retrieve a bean instance or an enumeration of bean instances from the persistence store. The home interface for the Emp bean is in the EmpBeanHome.java file:

Listing 7-3 EmpBeanHome.java


package examples.intro;

import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.sql.Date;

public interface EmpBeanHome extends EJBHome {

public Emp create(int empno, String ename, String job,
int mgr, Date hiredate, double sal,
double comm, int deptno)
throws RemoteException, EJBException, CreateException;

public Emp findByPrimaryKey(EmpBeanPK pk)
throws RemoteException, FinderException;

public Emp findByEmpno(int empno)
throws RemoteException, FinderException;

public Enumeration findByName(String name)
throws RemoteException, FinderException;

public Enumeration findByNameLike(String name)
throws RemoteException, FinderException;

}


This interface defines one create() method and four finder methods. The findByPrimaryKey() finder method takes an instance of the bean's primary key class as its argument. The findByEmpNo() method is equivalent to the findByPrimaryKey() method. It returns a single Emp instance because the empno field is unique. The findByName() and findByNameLike() finders return Enumerations, since either method could match more than one employee.

In Emp, the JDBC code that implements these methods is generated by the WebLogic EJB compiler using this interface and definitions in the bean's deployment descriptor.

Primary Key Class

Entity beans must have a unique primary key to distinguish bean instances. The primary key is constructed from one or more fields and is described in a class that implements java.io.Serializable. The fields that represent the primary key must be declared public members of the primary key class and the class must have a public default constructor (with no arguments). The home interface includes a finder method, findByPrimaryKey(), which uses an instance of this class to retrieve a specific bean.

The primary key class must define hashCode() and equals() methods. The hashCode() method in this example just returns the employee number, which, conveniently, is a unique integer for each employee.

The primary key class for the Emp bean is in the EmpBeanPK.java file:

Listing 7-4 EmpBeanPK.java


package examples.intro;

import javax.ejb.*;
import java.util.*;
import java.lang.Integer;

public class EmpBeanPK implements java.io.Serializable {

public int empno;
public EmpBeanPK(int empno) {this.empno = empno; }

public EmpBeanPK() { }
public String toString() {
Integer n = new Integer(empno);
return n.toString();
}

public int hashCode() {
return empno;
}

public boolean equals(Object other) {
return ((EmpBeanPK) other).empno == this.empno;
}
}


Deployment Descriptors

Deployment descriptors identify the Java classes that implement the bean, the name used to bind the bean in the WebLogic Server JNDI tree, transaction requirements, security properties, caching and passivation attributes and, for container managed-entity beans, attributes to map the bean to database objects and finder methods.

Deployment descriptors are defined using XML and packaged with the bean in an EJB .jar file. The easiest way to edit deployment information for an EJB is to use the DeployerTool. See Deploying EJBs in WebLogic Server

The EJB 1.1 specification defines the contents of the ejb-jar.xml file. Here is the ejb-jar.xml file for the Emp bean:

Listing 7-5 ejb-jar.xml


<?xml version="1.0"?>

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

<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>Emp</ejb-name>
<home>examples.intro.EmpBeanHome</home>
<remote>examples.intro.Emp</remote>
<ejb-class>examples.intro.EmpBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>examples.intro.EmpBeanPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>hiredate</field-name>
</cmp-field>
<cmp-field>
<field-name>ename</field-name>
</cmp-field>
<cmp-field>
<field-name>sal</field-name>
</cmp-field>
<cmp-field>
<field-name>comm</field-name>
</cmp-field>
<cmp-field>
<field-name>mgr</field-name>
</cmp-field>
<cmp-field>
<field-name>empno</field-name>
</cmp-field>
<cmp-field>
<field-name>deptno</field-name>
</cmp-field>
<cmp-field>
<field-name>job</field-name>
</cmp-field>
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Emp</ejb-name>
<method-intf>Remote</method-intf>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>


The Emp bean uses two other XML deployment files: weblogic-ejb-jar.xml, which contains WebLogic Server-specific deployment parameters, and weblogic-cmp-rdbms-xml.jar, which contains parameters that configure a container-managed persistence bean for a database. The weblogic-ejb-jar.xml file for the Emp bean provides caching parameters, and, in the <persistence-descriptor> section, specifies that the bean uses WebLogic container-managed persistence. Here is weblogic-ejb-jar.xml:

Listing 7-6 weblogic-ejb-jar.xml


<?xml version="1.0"?>

<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN' 'http://www.beasys.com/j2ee/dtds/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>Emp</ejb-name>
<caching-descriptor>
<max-beans-in-free-pool>20</max-beans-in-free-pool>
<initial-beans-in-free-pool>0</initial-beans-in-free-pool>
<max-beans-in-cache>100</max-beans-in-cache>
<idle-timeout-seconds>10</idle-timeout-seconds>
<cache-strategy>Read-Write</cache-strategy>
</caching-descriptor>
<persistence-descriptor>
<persistence-type>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-type>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
</persistence-use>
</persistence-descriptor>
<jndi-name>EmpBeanHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>


The weblogic-cmp-rdbms-jar.xml file maps an entity bean into a database. It names the JDBC connection pool, the table in the database, and then maps each EJB field to a database column. The <finder-list> section defines a query for each of the bean's finder methods, using WebLogic Query Language (WQL). Here is weblogic-cmp-rdbms-jar.xml:

Listing 7-7 weblogic-cmp-rdbms-jar.xml


<!DOCTYPE weblogic-rdbms-bean PUBLIC 
"-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB RDBMS Persistence//EN"
"http://www.beasys/com/weblogic-rdbms-persistence.dtd">
<weblogic-rdbms-bean>
<pool-name>demoPool</pool-name>
<table-name>emp</table-name>
<attribute-map>
<object-link>
<bean-field>mgr</bean-field>
<dbms-column>mgr</dbms-column>
</object-link>
<object-link>
<bean-field>hiredate</bean-field>
<dbms-column>hiredate</dbms-column>
</object-link>
<object-link>
<bean-field>job</bean-field>
<dbms-column>job</dbms-column>
</object-link>
<object-link>
<bean-field>comm</bean-field>
<dbms-column>comm</dbms-column>
</object-link>
<object-link>
<bean-field>sal</bean-field>
<dbms-column>sal</dbms-column>
</object-link>
<object-link>
<bean-field>deptno</bean-field>
<dbms-column>deptno</dbms-column>
</object-link>
<object-link>
<bean-field>empno</bean-field>
<dbms-column>empno</dbms-column>
</object-link>
<object-link>
<bean-field>ename</bean-field>
<dbms-column>ename</dbms-column>
</object-link>
</attribute-map>
<finder-list>
<finder>
<method-name>findByNameLike</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
<finder-query><![CDATA[(like ename $0)]]></finder-query>
</finder>
<finder>
<method-name>findByEmpno</method-name>
<method-params>
<method-param>int</method-param>
</method-params>
<finder-query><![CDATA[(= empno $0)]]></finder-query>
</finder>
<finder>
<method-name>findByName</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
<finder-query><![CDATA[(= ename $0)]]></finder-query>
</finder>
</finder-list>
<options>
<use-quoted-names>false</use-quoted-names>
</options>
</weblogic-rdbms-bean>


Running the Emp Example

  1. Set up your development environment as described in Setting Your Development Environment.

  2. Change to the examples/intro directory, and create a temporary directory named ejbtemp and then a directory named ejbtemp/META-INF:

    mkdir ejbtemp

    mkdir ejbtemp/META-INF

  3. Copy the deployment descriptor files to the ejbtemp/META-INF directory:

    copy *.xml ejbtemp/META-INF

  4. Compile the Java source files. Enter this command on a single line:

    javac -d ejbtemp Emp.java EmpBean.java EmpBeanPK.java 
    EmpBeanHome.java

    This command compiles the Emp bean into the ejbtemp directory, which is used to "stage" the EJB.

    An enterprise bean is packaged in a jar file. To create the jar file, you create a directory structure with all of the files you want to include. Then when you run the jar program, the directory structure is duplicated in the jar file.

  5. Compile the Java source files again, this time into the directory specified by the CLIENT_CLASSES environment variable.

    Windows NT:

    javac -d %CLIENT_CLASSES% Emp.java EmpBean.java EmpBeanPK.java 
    EmpBeanHome.java

    UNIX:

    javac -d $CLIENT_CLASSES Emp.java EmpBean.java EmpBeanPK.java 
    EmpBeanHome.java

    This javac command compiles the classes into a directory that is in the classpath, which allows the WebLogic EJB compiler to find them later.

  6. Change to the ejbtemp directory and create a jar file named Emp.jar:

    cd ejbtemp
    jar cf Emp.jar examples META-INF

  7. Run the WebLogic EJB compiler on the Emp.jar file you created:

    Windows NT:

    java -Dweblogic.home=%WL_HOME% weblogic.ejbc Emp.jar 
    -d %WL_HOME%\myserver\Emp.jar

    UNIX:

    java -Dweblogic.home=$WL_HOME weblogic.ejbc Emp.jar 
    -d $WL_HOME/myserver/Emp.jar

    The EJB compiler creates a new Emp.jar file in the ./myserver directory of the WebLogic Server. This jar file contains the classes you compiled, plus classes generated by the EJB compiler.

  8. Edit the weblogic.properties file and find the weblogic.ejb.deploy property. Add the full path for the Emp.jar file to this property. For example, if you installed WebLogic Server in the c:\weblogic directory, this property would be:

       weblogic.ejb.deploy=\
    c:/weblogic/myserver/Emp.jar

  9. Start (or restart) WebLogic Server.

  10. You can delete the examples/intro/ejbtemp directory and all of its contents.

You should see a message in the WebLogic Server log to tell you that the bean has been deployed.

The next section shows how to use the Emp bean in an application.

Using the Bean in an Application

The EmpQuery.jsp JSP page is a browser-based lookup form that lets you query the Emp table using the Emp bean's finder methods. It demonstrates how to look up a bean with JNDI, how to call the finder methods, and how to use the bean's htmlToPrint() method to include the bean's fields in an HTML table.

Here is a listing of the EmpQuery.jsp file:

Listing 7-8 EmpQuery.jsp


<!doctype html p

ublic "-//w3c/dtd HTML 4.0//en">
<html>
<head><title>Employee lookup</title></head>

<%@ page
info="EmpBean lookup example"
contentType="text/html"
import="java.lang.Integer, javax.naming.*, javax.ejb.*, weblogic.common.*,
examples.intro.Emp, examples.intro.EmpBeanHome"
%>
<body>
<font face="Helvetica">
<h1><font color="#FF0000">Employee Lookup</font></h1>

<hr>
<form action=<%= request.getRequestURI() %> method="post">
<table border=0 cellspacing=5 align=center>
<tr>
<td>Search by</td>
<td><select name=searchType>
<option value=1>Employee number</option>
<option selected value=2>Employee name</option>
<option value=3>Name like ('%' is wildcard)</option>
</select>
</td>
</tr>
<tr>
<td>Search for</td>
<td><input type=text name=criteria size=10 maxlength=10></td>
</tr>
<tr>
<td align=center colspan=2><input type=submit value="Go">
</td>
</tr>
</table>
</form>
<p>

<%

if (request.getParameter("searchType") != null
&& request.getParameter("criteria") != null)
{
int searchType = Integer.parseInt(request.getParameter("searchType"));
String criteria = request.getParameter("criteria");
Emp emp = null;
Enumeration emps = null;
try {
Context ctx = new InitialContext();
EmpBeanHome home = (EmpBeanHome) ctx.lookup("EmpBeanHome");
switch (searchType) {
case 1: // by employee number
emp = (Emp) home.findByEmpno(Integer.parseInt(criteria));
break;
case 2: // by Employee name
emps = home.findByName(criteria.toUpperCase());
break;
case 3: // by name like
emps = home.findByNameLike(criteria.toUpperCase());
break;
default:
}

if (emp != null || emps != null) {
// we have data
%>

<hr>
<h2>Search Results</h2>
<table border=1 align=center>
<tr>
<th>Employee number</th>
<th>Name</th>
<th>Title</th>
<th>Manager</th>
<th>Hire date</th>
<th>Salary</th>
<th>Commission</th>
<th>Department</th>
</tr>

<%
}
if (emp != null) {
out.print(emp.htmlToPrint());
}
else {
while (emps.hasMoreElements()) {
emp = (Emp) emps.nextElement();
out.print(emp.htmlToPrint());
}
}
%>
</table>

<%
}
catch (NumberFormatException nfe) {
out.print("<p>Error attempting to convert " +
criteria + " to an integer.");
}
catch (Exception e) {
out.print("<p>Exception: " + e.getMessage());
}
}
%>
<p>
<hr>
<center>
<p>Executed by
<%= application.getServerInfo() %>.<br>
Copyright 1999-2000 (C) BEA Systems, Inc.
All Rights Reserved.
</center>
</font>
</body>
</html>


You use JNDI to look up the bean's home interface:

Context ctx = new InitialContext();
EmpBeanHome home = (EmpBeanHome) ctx.lookup("EmpBeanHome");

Then, using the home interface, you can retrieve instances by using the bean's finder methods, or you could create a new instance using the create() method of the home interface. This example uses the findByEmpno(), findByName(), or findByNameLike() methods to retrieve beans, depending on user's browser entries.

The findByEmpno() method returns a single instance of an Emp bean while the findByName() and findByNameLike() methods return Enumerations of Emp beans. In either case, you must cast the returned object to the Emp interface, and then you can use any of the methods defined by that interface.

Running the EmpQuery.jsp Example

To try the EmpQuery.jsp example, make sure you have deployed the Emp bean as described in the previous section and that WebLogic Server is running.

  1. Copy EmpQuery.jsp to the myserver/public_html directory of your WebLogic Server installation.

  2. In a browser, enter the URL for EmpQuery.jsp. For example:

    http://localhost:7001/EmpQuery.jsp

    Change the hostname and port number if you are running WebLogic Server on a different computer or at a different listen port.

  3. Choose the type of lookup, enter the value to search for, and click Go.

The "Name Like" search type employs the SQL LIKE clause, which uses the percent sign (%) as a wildcard. For example, to find all employees with names starting with `A', enter "A%" in the "Search for" field. You can list all employees by entering "%" in the "Search for" field with a "Name like" search type.

More about EJB

The Sun Enterprise JavaBeans 1.1 specification is required reading for EJB developers. You can find javadocs for the javax.ejb interfaces and classes on the same web page.

Read the WebLogic EJB developers guide, Using WebLogic EJB for more about creating and deploying EJBs in WebLogic Server.