Java Programming, Lecture Notes # 1311
November 27, 2000
Second in a miniseries
This lesson is also the second lesson in a miniseries of several lessons intended to get you up and running with Sun's Enterprise JavaBeans(TM) very quickly.
First you learn to step, then you learn to run
The lessons in this miniseries will show you the steps involved in writing, compiling, deploying and executing a simple bean. However, the miniseries won't spend much effort explaining why you need to take those steps.
More details in subsequent lessons
Subsequent lessons will come back and fill in the gaps to give you a better understanding of the steps.
Subsequent lessons will also teach you about the different kinds of beans and how to use those beans in different situations.
Steps in this lesson
The previous lesson entitled Getting Started with EJB, Part 1 contained a list of the required steps involved in writing, compiling, deploying and executing a simple bean.
Download and Install
The first two steps involved downloading and installing the JDK and the J2EE. I will assume that you have completed those two steps.
Preview
Now I will move on to the third, fourth, fifth, and sixth steps, which read as follows (note that the wording for these steps is somewhat more brief than the original version in the previous lesson):
Viewing tip
You may find it useful to open another copy of this lesson in a separate browser window. That will make it easier for you to scroll back and forth among the listings while you are reading about them.
Recommended supplementary reading
It is strongly recommended that you study the previous lesson entitled Enterprise JavaBeans(TM), Getting Started with EJB, Part 1 before embarking on this lesson.
Additional supplementary material that I have written is available at Gamelan. A consolidated index to that material is available at Baldwin's Java Programming Tutorials.
Because of the likelihood of confusion regarding the use of the term beans, and just in case you are reading this lesson without having read the earlier lessons in this series, I will tell you that an enterprise bean is not the same thing as a JavaBean Component(TM), as discussed in my series of tutorial lessons beginning with lesson number 500.
Purposes, goals, etc.
I explained what an enterprise bean is in the previous lesson. I also explained the purpose and goals of enterprise beans in that lesson.
I gave a brief explanation as to how the goal is achieved by freeing the application programmer from the requirement to write the code for complex services such as concurrency, transactions, persistence, distributed objects, naming, and security.
I explained that to be of any use, a bean must be deployed in a server that is compliant with Sun's Java 2 Platform Enterprise Edition.
My approach
I also explained that I intend to show you how to deploy beans in Sun's Java 2 Platform Reference Implementation. It is my expectation that having learned how to deploy and use beans in that implementation, you will be able to expand that knowledge and apply it to servers of other brands from other vendors.
Writing EJB doesn't have to be complicated
The concept that I want to reinforce in this lesson is that writing Enterprise JavaBeans(TM) doesn't have to be complicated.
Unfortunately, I can't say the same thing about deploying enterprise beans. Deploying beans can be very complicated, and I will address that complexity in subsequent lessons.
Minimum programming requirement for a bean
The minimum programming requirement for an enterprise bean consists of:
The "hello Professor Baldwin" bean
The name of the source file containing the bean class is HelloBean.java. This is a typical "hello world" bean. It has one business method. (I will also discuss business methods in more detail in subsequent lessons.)
How does it behave?
The one business method of the bean receives a string as an incoming parameter and returns that string along with a greeting to the user of the bean.
The bean's life cycle
The bean also displays information about where it is in its life cycle. (I will also discuss the life cycle of a bean in detail in subsequent lessons.)
The life cycle information is displayed on the console where the server containing the bean is running. Optionally, that output can be redirected to a log file when the J2EE server is started.
Stateless vs. stateful beans
The bean in the example will be a stateless session bean. I will have a lot more to say about session beans, of both the stateless and stateful variety, in subsequent lessons.
This bean was tested using the J2EE server and JDK 1.3 under WinNT workstation 4.0.
A very brief discussion
This will be a very brief discussion, intended to give you a view of a bean from 50,000 feet. Please don't be dismayed by the lack of details. Details will be forthcoming in subsequent lessons.
The bean class
Listing 1 shows the beginning of the bean class along with a couple
of import directives.
import
javax.ejb.*;
import java.util.Date; public class HelloBean
implements SessionBean{
Listing 1 |
A session bean must implement the SessionBean interface. This is illustrated in Listing 1.
The SessionContext variable
Listing 1 also shows the declaration of an instance variable of the type SessionContext. This variable will be populated by one of the methods that I will mention later. I will also have a lot more to say about the SessionContext in subsequent lessons.
Import directives
Note that the javax.ejb package that is imported in Listing 1 is contained in the class library that you receive when you download J2EE from Sun.
Since this package is not part of the standard JDK 1.3, but comes with J2EE, I assume that it is the responsibility of the vendor of the J2EE package-compliant server to provide it.
Creating the bean
Listing 2 shows a method named ejbCreate() that is invoked when
the bean is created. The bean class can define overloaded versions
of this method name. The home interface that I will present and discuss
later must declare a create method corresponding to each overloaded
version of ejbCreate().
public void ejbCreate(){
System.out.println("HelloBean Created " + new Date()); }//end ejbCreate() Listing 2 |
The client causes one of the overloaded versions of the ejbCreate() method to be invoked when it invokes a method that causes the bean to be created. Note, however, that the client does not invoke this method directly. In a subsequent lesson, I will show you a client program that can create and use this bean.
Used for initialization
The ejbCreate() method is intended to be used for initialization purposes, much like a parameterized constructor is used in an ordinary non-bean class.
Business methods
The business methods of a bean are exposed to the client through the remote interface (to be discussed later) and can be indirectly invoked by the client.
The intent is that the client will invoke the business methods to accomplish the business purposes of the bean. Since this is a "hello" bean, we would expect its single business method to do something involving the word hello.
aBusinessMethod()
This bean contains only one business method. That method, named
aBusinessMethod()
is shown in Listing 3.
public String aBusinessMethod(String str){
return "Hello " + str; }//end aBusinessMethod() Listing 3 |
As you can see, this is a very simple business method. The method receives a reference to a String object and returns the string representation of that object concatenated to the string "Hello". In other words, the method says hello to the client when it is invoked.
Method output
When this business method is invoked on the bean, passing a reference to a String object containing my name, the following string is returned to the client by the method:
Hello Professor Baldwin
Callback methods
The three methods shown in Listing 4, along with the setSessionContext()
method shown in Listing 5, are callback methods. They are invoked
by the server and its associated container when certain critical events
occur during the lifetime of the bean.
public void ejbRemove(){
System.out.println("HelloBean Removed " + new Date()); }//end ejbRemove() public void ejbActivate(){
public void ejbPassivate(){
Listing 4 |
No registration required
However, unlike many other callback methods in Java, it isn't necessary for the programmer to register these callback methods on a source. They are automatically registered on the container (to which the beans belongs) when the bean becomes operational.
Purpose of callback methods
You write code in the body of the callback methods to deal with the needs of the bean at the critical points in its life when the callback methods are invoked by the server.
In this example, I have simply caused the methods to report that they have been invoked along with the date and time that they were invoked. I will discuss the use of these methods in more detail in a subsequent lesson.
Session context
Listing 1 showed the declaration of an instance variable of the type
SessionContext.
Listing 5 shows how this instance variable is populated by the method named
setSessionContext().
public void setSessionContext(
SessionContext ctx){ this.ctx = ctx; System.out.println( "HelloBean got SessionContext " + new Date()); }//end setSessionContext() Listing 5 |
According to the excellent book entitled Enterprise JavaBeans, by Tom Valesky, (Addison Wesley), the setSessionContext() method is invoked on the bean "at the very beginning of a Session bean's life."
Valesky goes on to say, "The container passes the Session bean an object that implements the SessionContext interface. The bean stores this object in an object variable, and can then use the SessionContext to interact with container-provided services such as security and transaction management."
The noarg constructor
Finally, the bean class ends with an empty public constructor having
no arguments as shown in Listing 6.
public HelloBean(){}//public constructor
}//end class HelloBean Listing 6 |
The output
When this bean is created and later removed by a client, the following output appears on the server console or in the server log file (note that newline characters were manually inserted to force the text to fit in this narrow format):
HelloBean got SessionContext
Sat Sep 16
08:13:41 CDT
2000
HelloBean Created
Sat Sep
16 08:13:41
CDT 2000
HelloBean Removed
Sat Sep
16 08:13:41
CDT 2000
Note also that additional output could appear if the server decided to passivate and activate the bean during its lifetime. I will have more to say on this subject in a subsequent lesson.
End of the bean class
That is the end of the bean class. All that is necessary now is to compile it, along with the two interfaces mentioned earlier, and to deploy it into a J2EE platform-compliant server . Then it can be used by a client of the server.
A complete listing of the bean program is shown near the end of this lesson.
The home interface
If you have already guessed that the create() method declared
in this interface has some relationship with the ejbCreate() method
mentioned earlier, you are correct. I will discuss that relationship
in detail later.
/*
File HelloHome.java
Copyright 2000 R.G.Baldwin Rev 9/15/00 ***********************************************/ import javax.ejb.*; public interface HelloHome
extends EJBHome{
Listing 7 |
The remote interface
You will note that this interface declares a method named aBusinessMethod() that matches the signature of the method having the same name in the bean class.
All business methods of a bean are exposed to the client program through
the remote interface. I will also have a lot more to say about this
in a subsequent lesson.
/*
File Hello.java
Copyright 2000 R.G.Baldwin Rev 9/15/00 ***********************************************/ import javax.ejb.*; import java.rmi.*; public interface Hello
extends EJBObject{
Listing 8 |
set
J2EE_HOME=d:\progfile\j2sdkee1.2.1
set CPATH=.;%J2EE_HOME%\lib\j2ee.jar javac -classpath %CPATH%
Listing 9 |
The first line creates an environment variable named J2EE_HOME and points it to the directory where the J2EE is installed.
The second line creates an environment variable named CPATH representing a classpath containing the current directory (.) and the path to a jar file provided with J2EE that contains the class libraries for J2EE.
The third line invokes the javac compiler on three separate source files after adjusting the classpath to include the environment variable named CPATH created earlier. (Note that in order to get the third line to fit in this narrow format, it was necessary for me to manually insert a newline. You will need to remove that newline before attempting to execute this batch file.)
Compiling the bean
To compile the bean, copy the two source files given above into some directory on your hard drive. Make certain that the names of the files match the class and interface names. Copy this batch file into the same directory. Then execute the batch file.
Once you have successfully executed this batch file, your bean should have been compiled, and should be ready for deployment into the J2EE.
This lesson has shown you how to accomplish the following four steps along your journey towards an operational session bean running in J2EE.
I explained that the minimum programming requirement for a bean is the bean class plus two interfaces.
A simple hello bean
I developed and provided the source code for a simple bean that greets a client with the word hello concatenated to a string provided by the client.
Life cycle and callback methods
I talked a little about the life cycle of a bean and the callback methods that the bean uses to monitor that life cycle.
The session context, bean creation, and the ejb package
I mentioned session context and ejbCreate().
I explained where to find the package named javax.ejb.
Business methods
I gave a brief explanation the concept of business methods, and how they are exposed to the client via the remote interface.
Required interfaces
I developed and showed the source code for the remote and home interfaces that must be compiled and provided along with the bean class for deployment into J2EE.
Compilation of the bean
I developed and showed a batch file that can be used to control the classpath variable during compilation of the bean and the two interfaces.
In the next lesson, I will begin walking you through the detailed steps required to deploy the bean into J2EE and to make it available to a client program.
In a lesson following that one, I will develop and discuss a client program that can link to the server and access the hello bean developed in this lesson.
After that, I will start explaining the different types of beans and how they can be used in different situations.
/*
File HelloBean.java
Copyright 2000 R.G.Baldwin Rev 9/15/00 This bean receives and
returns a String object
This is a stateless session
bean. According to
Implement the SessionBean
interface.
Tested using Sun j2ee
and JDK 1.3 under
public class HelloBean
implements SessionBean{
public void ejbCreate(){
public String
aBusinessMethod(String str){
public void ejbRemove(){
public void ejbActivate(){
public void ejbPassivate(){
public void setSessionContext(
public HelloBean(){}//public constructor }//end class HelloBean
Listing 10 |
Copyright 2000, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two. He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-