Oracle9i JDeveloper - Hands on Labs (J2EE)
Building J2EE Applications Using JSP, Servlets, and EJB
Introduction
Welcome to the Hands On Lab exercises for building J2EE Applications using Java
Servlets, JSP and EJB. The goal of these exercises is to provide instruction on how to
fully make use of all of Oracle9i JDeveloper's J2EE development features in
building J2EE applications.
The hands-on exercises are contained in the following Labs:
Prerequisites
Please read the prerequisites and ensure that you have
the proper environment to complete this lab.
Lab 1: The Web Tier - Servlet 2.3 Filters and Listeners
In this section we will be working with the new J2EE 1.3 Web Tier features which
includes Servlet 2.3 filters and listeners.
Exercise 1: Creating and Testing a Servlet Filter
This exercise shows how to build and test a Servlet filter. In this exercise you will
build a Servlet and a filter to filter the incoming request for a particular request
parameter.
Create a simple Http Servlet
- Select and open J2EEAPPS.jws workspace in the navigator
- Select Web-Tier.jpr project in the navigator.
- Create a simple HelloWorld Servlet from New gallery
Select File | New
Choose Web-Tier in the Categories, and select Servlets
Select Http Servlet from Items list
Click OK.
- Accept all of the defaults for steps 1 through 3 of the Servlet wizard and click Finish.
This will generate a new file called: Servlet1.java along with
a J2EE web app descriptor file, web.xml.
- Save the project using File | Save All.
You may also click on the Save All Icon: on the menu.
Create a Servlet Filter
This filter will scan the request object for a specific request parameter, "userid
". If there is request parameter named "userid" and it has a non-null
value, it will then be logged to the console.
- Select Web-Tier.jpr project in the navigator.
- Select File | New
Choose Web-Tier in the Categories, and select Servlets
Select Servlet Filter from Items list
Click OK.
- On step 2 of 3, allow the filter to be mapped to Servlet1.
Select the the radio button, Map to Servlet or JSP and select Servlet1 from the drop down list. (Should be default.)
Servlet1 is the Servlet you just created in the previous step.
- Accept the remaining defaults and click Finish.
This will generate a new file called: Filter1.java which will
be mapped to your Servlet.
- Save the project using File | Save All.
You may also click on the Save All Icon: on the menu.
Modifying and Running the Servlet
HttpServlets interact with Http clients (browsers) using the Request object and the
Response object. The Request object contains all of the Http client's request information
such as the URL requested along with any HTML form parameters passed. The Response object
contains the entire response from the Servlet to the client. The response is usually in
HTML but can actually be in any document type such as XML, or even binary such as a JPG or
GIF.
In this exercise we will we will modify the Filter to scan the request object for the
parameter, "userid" and if it is not null, print out the value in the log
console.
- Double click on your Filter1 class (Filter1.java) in the
Navigator.The file opens in the Code Editor. In the Structure pane, double click doFilter() to jump to that method in the code
- Modify the doFilter() as follows:
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain) throws IOException, ServletException
{
String userid = request.getParameter("userid");
if ( userid != null )
System.out.println("Filter: userid = " + userid );
chain.doFilter(request, response);
}
- Save the filter. File | Save
- To test the filter. Run the Servlet by right-clicking the file and and selecting Run Servlet1.java.
You may also click on the Run Icon: on
the menu.
JDeveloper will compile and launch the Servlet in a browser window with a printed output
of:
The Servlet has received a GET. This is the reply.
- Enter the parameter, userid with a name onto the request URL
in the browser:
Ex: http://130.35.101.70:8988/your_context_root/servlet/Servlet1?userid=scott
Notice that the userid parameter with value "scott" was added:
"?userid=scott"
- Now re-run the servlet with the new parameters added to the URL. (Just hit
"enter" after typing the additional parameters.)
- Observe JDeveloper's console window for the "Embedded OC4J" will have the
following message:
Filter: userid = scott
Exercise 2: Creating and Testing the Servlet Listener
Servlet listeners provide the ability to "listen" for changes to the servlet
context such as when an attribute is added or changed.
In this exercise, we'll build a servlet listener which will listen for the attribute,
"session_id" and log it's use.
Creating a simple JSP page
- In the same project as before Web-Tier.jpr ,build a simple
JSP page.
Select File | New
Choose Web-Tier in the Categories, and select JavaServer Pages (JSP)
Select JSP Page from the Items
Click OK.
- You should now have a new JSP file, untitled1.jsp, added to
your project and invoked in the editor. Save the JSP file (File |
Save).
- Now let's add some code to the JSP which adds a session attribute,
"session_id".
In the JSP page, add the following code before the closing "</body>" tag.<%
String session_id = "Tiger";
session.setAttribute("session_id", "Tiger");
%>
Added session attribute: session_id with value: <%= session_id %>
- Save the JSP file (File | Save)
Creating a Servlet Listener
Now we'll build the servlet listener which will listen for this session setattribute
event.
- In the same Web-Tier.jpr project create a servlet listener.
Select File | New
Choose Web-Tier in the Categories, and select Servlets
Select Servlet Listener from Items
Click OK.
This wizard will guide you through the steps of creating a servlet listener.
- .Accept the default listener name and package name: Listener1,
mypackage1.
- .Step 2 of 2 allows you to select what type of listener. In this exercise we'll create a
listener which listens to HttpSessionattribute events.
In the drop down list, Listener to Create:
select javax.servlet.http.HttpSessionAttributeListener.
(This will generate a listener which implements
javax.servlet.http.HttpSessionAttributeListener.)
- Click Finish to generate a new file called: Listener1.java.
- Double click on your Listener1 class (Listener1.java) in the
Navigator.The file opens in the Code Editor. In the Structure pane of the Navigator,
double click attributeAdded() to jump to that method in the
code
- Modify the attributeAdded() as follows:
public
void attributeAdded(HttpSessionBindingEvent event)
{
name = event.getName();
session = event.getSession();
String session_id = (String) session.getAttribute("session_id");
if (session_id!= null)
System.out.println("Listener: session_id = " + session_id);
}
- Select File | Save All.
Running the JSP and Listener
Now let's test the newly created servlet listener by running the JSP which adds the
HttpSession attribute, "session_id".
- Run the JSP page, untitled1.jsp by right clicking on the JSP
page and selecting: Run untitled1.jsp.
- The JSP will then be compiled and executed. As the browser renders the JSP, notice the Embedded OC4J console window. You will see the listener's output:
Listener: session_id = Tiger
As you can see, the listener has trapped the setAttribute for
"session_id" event in the untitled1.jsp JSP page, and acted on it by displaying
it's value in the console. In a larger application, the listener could log this event in a
file or a database table for future analysis.
Lab 2: The EJB-Tier - EJB 2.0
In Lab2 we will build a set of Enterprise Javabeans. We will use EJB Modeler to model
Session and Entity beans, EJB Module Editor to edit the EJBs, and EJB Verifier to verify
EJBs.
In exercise 1, we will reverse engineer a CMP entity bean based on the employees
database table.
In exercise 2 we will build a session bean facade which will act as our main proxy for
communicating to the entity bean and expose business methods to the clients.
In exercise 3 we will create Container Managed Relationship between Entity beans.
Exercise 1: Creating a Session Bean
Model Session Bean
- Select the project EJB-Tier
- In the Navigator, right click your project (EJB-Tier.jpr) and choose New UML Diagram.
- In the New dialog, select Class Diagram and click OK.
- In the Create New Class Diagram dialog, click OK.
- In the Component Palette, choose EJB from the drop-down
list. (If the Component Palette is not visible, from the View
menu choose Component Palette.)
- In the Component Palette, click Session Bean to create a new
session bean.
- In the class model (the empty window), click in one corner and drag towards the opposite
corner to draw a session bean on the class diagram.
The Enterprise JavaBean Wizard opens.
- Review the information on the Welcome page and then click Next.
- On the Select EJB Version page, select Enterprise JavaBeans 2.0
and click Next.
- On the EJB Name and Type page, enter hrApp
in the EJB Name field.
Notice the Session Type is Stateless.
Accept this as the default and click Next.
- On the Class Definitions page you can accept the defaults
and click Next.
- On the EJB Home and Component Interfaces page, select the
checkboxes for both Include Remote Interfaces and Include Local Interfaces.
Local interfaces are used for bean-to-bean interaction. In the later exercises, this
session bean will be used to locally access entity beans, so you must generate the local
interfaces.
- Click Next.
- On the Summary page, review the choices you have made. Click Finish.
Your session bean is added to the UML diagram.

- Save all.
Add a Field to the Session Bean
- On the UML diagram, click into the first empty block on the session bean to create a new
attribute. Type company : String to create a field called company of type String.
- Click anywhere outside of the session bean model to remove the focus from the model.
The field you added in the UML model is synchronized with the other tools. Take a look at
the EJB Module Editor.
- In the UML diagram, double click anywhere on the session bean model to open the EJB
Module Editor.
- Expand the node for your session bean (hrApp) and click the Fields node.
Notice that the field you added in the UML model appears in the Fields page of the EJB
Module Editor. The EJB Module Editor is used to edit the EJB module or any of the EJBs
contained within. Close the EJB Module Editor.
- To view the Java code that this step added, take a look at the Code Editor.
In the Navigator, expand the folders for your project (EJB-Tier.jpr),
the EJB module (ejb-jar.xml), and your session bean (hrApp).
- Double click on your bean class (hrAppBean.java).The file
opens in the Code Editor. In the Structure pane of the Navigator, double click getCompany() to jump to that method in the code.Notice that the
framework generated getter and setter methods for the field you added in the UML model.
Running and Testing the Application
Iterative testing is an integral part of developing an application. In this tutorial, you
will run and test the application every time you make changes to the session bean. For
testing purpose, you will generate a sample Java client.
- In the Navigator, right-click your session bean (hrApp) and
choose Run hrApp from the context menu.
- In the Navigator, right click on your session bean (hrApp)
and choose New Sample Java Client.
- In the Sample EJB Java Client Details dialog, select the option for Connect
to OC4J Embedded in JDeveloper and click OK.
A new file, hrAppClient.java appears in the Navigator and
opens in the Code Editor.
- Uncomment the setCompany() method and set the value to "Oracle Corporation".
- Call getCompany() and print it to the console. Your code
should be similar to the code below:
HrApp = HrAppHome.create( );
HrApp.setCompany ("Oracle Corporation");
System.out.println(HrApp.getCompany());
- Run the client by right-clicking on hrAppClient.java in the
Navigator and choosing Run hrAppClient.java.You should see
"Oracle Corporation" displayed in the Log Window.
Exercise 2: Reverse Engineering database table as CMP Entity Bean
Create CMP Entity Bean
Creating a CMP entity bean from a table is very easy to do using the UML Modeler; you
drag the table from the Navigator onto the UML model.
- You'll be using the UML model again. To bring the UML model window to the front, from
the Window menu, choose hr.
- In the Navigator, expand the nodes for Connections, Database,
hrConnection, HR, and then Tables.
- Click on DEPARTMENTS and drag it to the UML model.
- In the Create from Tables dialog, select the option for EJB 2.0
Entity Beans. Click OK.
The new CMP bean appears on the UML model. Notice that a new node, Departments, appears in
the Navigator as well.
- Build the EJB-Tier project (Project | Rebuild EJB-Tier.jpr)
Creating a Session Bean Facade
Adding a local reference to the EJBs and making a session bean as a facade is easy to
do using the UML modeler. You select the type of reference you want to create, and draw a
line between the two beans.
- In the Component Palette, choose EJB Local Reference. (If the Component Palette is not
visible, from the View menu choose Component
Palette.)
- In the UML model, click on the session bean (hrApp) and drag
to the entity bean (Departments).
The local reference is displayed as a line between hrApp and Departments.The local ref
that you created in the UML model is also reflected in the deployment descriptor and bean
class.
- In the Navigator, double click ejb-jar.xml.The file opens in
the Code Editor.
- Scroll through the code and find the local ref that was generated.
- In the Navigator, double click the bean class (hrAppBean.java)
to open it in the Code Editor.
- In the Structure pane, double click getDepartmentsLocalHome()
to jump to that method. Notice that the method is generated for you.
Add a business Method to the Session Bean
In this step, you'll add a new method to the session bean called listDepartments().
This method will call the default-generated findAll() method on
the Departments entity bean.
- In the UML model, create a new method by clicking in the middle field of the session
bean (hrApp) and typing listDepartments() : String
- The next step is to add implementation code to the bean class. In the Navigator, double
click hrAppBean.java to open it in the Code Editor.
- In the Structure Pane, double click listDepartments() to
jump to that method.
- Copy and paste the following code in place of the existing stub method:
public String listDepartments()
{
try {
Collection col = getDepartmentsLocalHome().findAll();
Iterator it = col.iterator();
StringBuffer sb = new StringBuffer ("Department Listing ....\n");
DepartmentsLocal dept;
while(it.hasNext())
{
dept = (DepartmentsLocal)it.next();
sb.append(dept.getDepartment_id() + "....." +
dept.getDepartment_name()+ "....." +
dept.getLocation_id() + ".....\n");
}
return sb.toString();
}
catch(NamingException ne)
{
System.out.println(ne.toString());
throw new javax.ejb.EJBException(ne);
}
catch(FinderException fe)
{
System.out.println(fe.toString());
throw new javax.ejb.EJBException(fe);
}
}
- Add the following to the import block:
import javax.ejb.FinderException;
import java.util.Collection;
import java.util.Iterator;
import hr.DepartmentsLocal;
- Compile your program to make sure you have no errors. From the Program
menu, choose Make hrAppBean.java.
- From the File menu, choose Save.
Running and Testing the Application
- In the Navigator, right-click your session bean (hrApp) and
choose Run hrApp from the context menu.
- In the Navigator, right click on your session bean (hrApp)
and choose New Sample Java Client.
- In the Sample EJB Java Client Details dialog, select the option for Connect
to OC4J Embedded in JDeveloper and click OK.
A new file, hrAppClient1.java appears in the Navigator and
opens in the Code Editor.
- Call listDepartments() with the following code:
System.out.println( HrApp.listDepartments( ));
- Run the client by right-clicking on hrAppClient.java in the
Navigator and choosing Run hrAppClient.java.You should see the
department number, the department name, and the location in the Log Window.
Add a Finder Method to Entity Bean
- In the Navigator, double-click the Departments entity
bean.The EJB Module Editor opens.
- In the EJB Module Editor, expand the Departments node and
click Methods. In the Method Category,
select Finder Methods.
- Click Add. The Method Details dialog opens.
- In the Method Details dialog, change the Name to findByDname
- In the Return Type field, type DepartmentsLocal.
In the Parameters field, type String dname
- On the bottom of the dialog, click the EQL tab.
- Paste in the following code:
select distinct object (d) from Departments d where d.department_name =
?1
- Click OK to close the dialog.
- In the EJB Module Editor, click Preview XML.Notice the query
tag that was added.
- Click OK to close the EJB Module Editor.
Add a business Method to the Session Bean Facade
- In the UML model, add a new method to the session bean by clicking below the listDepartments() method and typing the following
listByDname(String dname) : String

- In the Navigator, double-click hrAppBean.java to open it in
the Code Editor.
- In the Structure pane, double-click listByDname() to jump to
that method in the code.
- Replace the stub method with the following code:
public String listByDname(String dname)
{
try {
DepartmentsLocal dept = getDepartmentsLocalHome().findByDname(dname) ; StringBuffer sb = new StringBuffer ("Department Details....\n");
sb.append(dept.getDepartment_id() + "......" +
dept.getDepartment_name() + "......" +
dept.getLocation_id() + "......\n");
return sb.toString();
}
catch(NamingException ne)
{
System.out.println(ne.toString());
throw new javax.ejb.EJBException(ne);
}
catch(FinderException fe)
{
System.out.println(fe.toString());
throw new javax.ejb.EJBException(fe);
}
}
Running and Testing the Application
- In the Navigator, right-click your session bean (hrApp) and
choose Run hrApp from the context menu.
- In the Navigator, right click on your session bean (hrApp)
and choose New Sample Java Client.
- In the Sample EJB Java Client Details dialog, select the option for Connect
to OC4J Embedded in JDeveloper and click OK.
A new file, hrAppClient2.java appears in the Navigator and
opens in the Code Editor.
- Call the Dept finder method findByDname() through the session
bean's method listByDname() with the following code:
System.out.println(HrApp.listByDname( "Sales"));
- Run the application by selecting Run | Run hrAppClient2.java
- You should see the output like,
Department Details....
80......Sales......2500.....
in the Log Window.
Exercise 3: Adding a Container-managed Relationship (CMR)
Create Employees Entity Bean with a CMR to Departments Entity Bean
JDeveloper automatically reverse engineers foreign key relationships between the tables
as CMR between Entity beans
- You'll be using the UML model again. To bring the UML model window to the front, from
the Window menu, choose hr.
- In the Navigator, expand the nodes for Connections, Database,
hrConnection, HR, and then Tables.
- Click on Employees and drag it to the UML model.
The new CMP bean appears on the UML model. Notice that a new node, Employees, appears in
the Navigator and a CMR between Departments and Employees is created
- Build the EJB-Tier project (Project | Build EJB-Tier.jpr)
Add a business Method to the Session Bean Facade to call CMR accessor
- In the UML model, add a new method to the session bean by clicking below the listDepartments() method and typing the following
listEmployees (Long pk) : Collection
- In the Navigator, double-click hrAppBean.java to open it in
the Code Editor.
- In the Structure pane, double-click listEmployees() to jump
to that method in the code.
- Replace the stub method with the following code:
public Collection listEmployees(Long pk)
{
try {
return this.getDepartmentsLocalHome().findByPrimaryKey(pk).getEmployees_department_id();
}
catch(NamingException ne)
{
System.out.println(ne.toString());
throw new javax.ejb.EJBException(ne);
}
catch(FinderException fe)
{
System.out.println(fe.toString());
throw new javax.ejb.EJBException(fe);
}
}
- Add the following import statements in hrAppBean.Java:
import hr.EmployeesLocal;
- Build the EJB-Tier project (Project | Build EJB-Tier.jpr).
Lab 3: Building a J2EE Enterprise Application
Now it's time to put it all together and build a Web client for our EJBs.
Details about the Client-Tier Project
- In order to run EJB's from the EJB-Tier project, our Client-Tier project has some
additional settings
- J2EE - The EJB runtime libraries are included.
- Project Dependency on the EJB-Tier Project. This allows the Client-Tier project access
to EJB classes from the EJB-Tier Project.
To see these settings, double click on the project Client-Tier.jpr
and click on the Development/Libraries node the Dependencies node.
Exercise 1: Creating a JSP to display contents from an EJB
Before building our JSP, we'll need to add an EJB reference so all objects in the
Client-Tier project can access the EJBs residing in the EJB-Tier project.
Create listemp.jsp Javaserver Page
- Select Client-Tier.jpr in the navigator.
- Create a new JSP page.
Select File | New
Choose Web-Tier in the Categories, and select JavaServer Pages (JSP)
Select JSP Page (not "JSP Document" ) from the list
- Set the JSP file name to: listemp.jsp
- Click Ok.
Add an EJB reference to the EJB Tier from this Web application
- Select the web.xml file the Navigator, Right click on it and
select Settings....
- In the Web Application Deployment Descriptor dialog, Select EJB
Local Refs and Click Add....
Add the following details in the Create EJB reference dialog box (See Figure below)
- Name - ejb/hrapp
- Home Interface - hr.hrAppLocalHome
- Local Interface - hr.hrAppLocal
- EJB link - hrApp
- EJB type - Session
- Description - Reference to hrApp Session Bean
We will now modify the contents of this JSP so it can access an our EJB. To do this
we'll first copy the entire contents of a JSP template file which has most of the code
necessary to display data from our EJB.
- Click on the link listemp_template.jsp
to display it's contents in a new browser window.
(Note: If a new window does not pop up, the content may be in an existing browser window.)
- Select the ENTIRE contents of this template page and copy (Ctrl-C) and paste (Ctrl-V)
over the ENTIRE contents of your listemp.jsp page.
- Save the listemp.jsp page.
The final step is to add the <EJB:usehome ..> ejb
tag. This exercise is meant to show you how to use the EJB tags located on the Component
Palette.
- In the new listemp.jsp page, place your cursor under the line: <!-- Place EJB:usehome
tag here... --->
- Using the Component Palette select the Palette page OJSP EJB
in the dropdown list. You should then see the tags: useHome, useBean, createBean, iterate
on the palette.
- Click on the tag useHome and specify the following
attributes:
- id - hrapphome
- type - hrAppLocalHome
- location - java:comp/env/ejb/hrapp
- local - true
(Note: These values ARE case sensitive!)
- Click Ok to insert the tag. The resulting tag should look
like:
<EJB:useHome id="hrapphome"
type="hrAppLocalHome" location="java:comp/env/ejb/hrapp"
local="true" />
- Your JSP should be ready to run. Feel free to inspect how it works.
- Save all and build the project.
- Build the Client-Tier project (Project | Build Client-Tier.jpr)
Running the JSP
- Run the listemp.jsp jsp by right-clicking on it and selecting Run
listemp.jsp.
You'll notice as the JSP starts up, the EJB middle tier will also initialize the existing
EJBs.
- As the JSP executes, you will see a select control allowing you to select a department
number and the employees of that department will display in an HTML table.
Exercise 2: Deploying Your J2EE Application to Standalone OC4J
server
Oracle9i JDeveloper has the ability to assemble an Enterprise Application Archive (EAR)
containing an EJB jar file, and a Web application WAR file. In this exercise we will
create a WAR file and an EJB JAR archive deployments and combine them into an Enterprise
Archive (EAR) deployment profile. We will then deploy the entire application (EAR) to
Standalone OC4J Server.
Renaming the Web Context root
Now let's define a more user friendly Web context root. This is the name of the Web
application that you'll see in the URL. For example:
http://localhost:8888/your_context_root/untitled1.jsp
Modify the J2EE Web context root by:
- Double-clicking on the Client-Tier.jpr project to select
it's properties.
- Click on the J2EE node.
- Change the default J2EE Web Context Root from:
J2EEApplication-Client-Tier-context-root
to
myhrapp
- Click OK
Now when we deploy our application, we'll be able to refer to the deployed app using the
new context root.
Create an EJB JAR deployment profile for your EJB
- In the project EJB-Tier.jpr , create an EJB Deployment Profile
Select ejb-jar.xml in the Navigator
Right-mouse on it choose Create EJB Jar Deployment Profile ...
- Click Save to store your deployment profile in the default
location.
- In the J2EE EJB Module Deployment Profile Settings page, click OK
to accept the defaults.
You will see the new deployment profile, ejb1.deploy added to
your project
Create a WAR deployment profile for your Client application
- In the project Client-Tier.jpr, create WAR deployment profile
select web.xml in the Navigator
Right-mouse on it and choose Create WAR Deployment Profile ...
- Click Save to store your deployment profile in the default
location.
- In the J2EE Web Module Deployment Profile Settings page, click OK
to accept the defaults.
- As before, you will see the new deployment profile, webapp1.deploy
added to your project.
Create an EAR deployment profile for your entire application
- In the project Client-Tier.jpr, create an EAR deployment profile
Select File | New
Choose General in the Categories, and select Deployment Profiles
Select EAR File - J2EE Application from Items list
Click OK.
- Click Save to store your deployment profile in the default
location.
- In the J2EE Application Deployment Profile Settings page, click on Application
Assembly to see the list of J2EE modules available for assembly.
- Click on the checkboxes for both the EJB JAR (ejb1.deploy)
and Web module WAR (webapp1.deploy) to package these archives
into the EAR file.
- Click OK to save your settings.
- You will now see the Enterprise Application deployment profile, application1.deploy
added to your project.
- Save all your files: File |Save All.
Deploying and running the Enterprise Application
- To deploy your enterprise application, right-click on the deployment profile, application1.deploy and select Deploy to |
localoc4j.
- After the successful completion of your deployment, you will see the following message,
"Deployment Finished."
---- Deployment finished. ----
To run the application from the remote server use the following:
To run the EJB servlet:
http://localhost:8888/myhrapp/listemp.jsp
This concludes the Building J2EE ApplicationsHands-On exercises.
|