You are on page 1of 597

Oracle10g: Build J2EE Applications

Electronic Presentation

D17247GC10
Production 1.0
May 2004
D39458

Authors

Copyright 2004 Oracle. All rights reserved.

Lynn Munsinger
Sunitha Patel

This documentation contains proprietary information of Oracle Corporation. It is provided under a


license agreement containing restrictions on use and disclosure and is also protected by copyright
law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S.
Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the
following legend is applicable:

Technical Contributors and


Reviewers

Restricted Rights Legend

Anna Atkinson
Scott Brewton
Kenneth Cooper
Craig Hollister
Taj-ul Islam
Istvan Kiss
Peter Laseau
Glenn Maslen
Monica Motley-Mosser
Nagavalli Pataballa
Holger Dindler-Rasmussen
Glenn Stokol
Vasiliy Strelnikov
Venkat Tallapragada

Use, duplication or disclosure by the Government is subject to restrictions for commercial computer
software and shall be deemed to be Restricted Rights software under Federal law, as set forth in
subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software
(October 1988).

Publisher

Oracle and all references to Oracle Products are trademarks or registered trademarks of Oracle
Corporation.

S. Domingue

This material or any portion of it may not be copied in any form or by any means without the express
prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and
may result in civil and/or criminal penalties.
If this documentation is delivered to a U.S. Government Agency not within the Department of
Defense, then it is delivered with Restricted Rights, as defined in FAR 52.227-14, Rights in DataGeneral, including Alternate III (June 1987).
The information in this document is subject to change without notice. If you find any problems in the
documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle
Parkway, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this document is
error-free.

All other products or company names are used for identification purposes only, and may be
trademarks of their respective owners.

Introduction

Copyright 2004, Oracle. All rights reserved.

Course Objectives

After completing this course, you should be able to do


the following:
Identify the components and architecture of Java
2, Enterprise Edition (J2EE), based on the needs
of specific applications
Describe the Model View Controller (MVC)
architecture and create development plans for
J2EE applications
Build a Web-based database application by using
J2EE components: servlets, JavaServer Pages
(JSP), and Enterprise JavaBeans (EJB)

1-2

Copyright 2004, Oracle. All rights reserved.

Course Objectives

1-3

Test J2EE components by using Web and Java


clients
Provide versatile access to applications through
Web services, and use a published Web service in
an application
Deploy J2EE applications to Oracle Application
Server 10g
Manage transactions in EJB
Implement J2EE security in applications

Copyright 2004, Oracle. All rights reserved.

Course Environment

1-4

The development tool is Oracle JDeveloper 10g,


version 9.0.5.1.
The application server is Oracle Application
Server 10g, version 9.0.4.
The database is Oracle 10g.

Copyright 2004, Oracle. All rights reserved.

Course Overview

1-5

Lesson 1: Course Overview


Lesson 2: J2EE Overview
Lesson 3: Design considerations for building J2EE
applications
Lesson 4: Introduction to servlets
Lesson 5: Using JDBC to access the database
from servlets
Lesson 6: Advanced servlet topics
Lesson 7: Maintaining sessions in servlets
Lesson 8: Introduction to JavaServer Pages (JSP)
Lesson 9: Utilizing custom tags in JSP
Copyright 2004, Oracle. All rights reserved.

Course Overview

1-6

Lesson 10: Communication APIs in J2EE


Lesson 11: Introduction to Enterprise JavaBeans
(EJB)
Lesson 12: Creating session EJBs
Lesson 13: Creating entity EJBs
Lesson 14: Managing persistence in EJBs (BMP,
CMP)
Lesson 15: Specifying relationships in EJBs
(CMR)
Lesson 16: Creating Message-Driven Beans (MDB)

Copyright 2004, Oracle. All rights reserved.

Course Overview

1-7

Lesson 17: Integrating servlets, JSPs, and EJBs in


a J2EE application
Lesson 18: Introduction to Web Services
Lesson 19: Developing and publishing Web
Services
Lesson 20: Implementing security in J2EE
applications
Lesson 21: Transaction support in Oracle
Application Server 10g

Copyright 2004, Oracle. All rights reserved.

About the Course Applications

The course uses applications that are derived


from the Order Entry and Human Resources
sample schemas.
In the practices, you write applications that allow
users to:

1-8

Browse available products


Place products in a shopping cart for purchase
View employee details
Update employee data
Send messages to a queue
Use a Web service to validate a credit card

Copyright 2004, Oracle. All rights reserved.

Order Entry Schema

1-9

Copyright 2004, Oracle. All rights reserved.

Human Resources (HR) Schema

1-10

Copyright 2004, Oracle. All rights reserved.

HR Application Flow Diagram

Employee entity
No
Process
log in

View
employees
process

Administrator?
Yes

Insert
employees
process

1-11

Copyright 2004, Oracle. All rights reserved.

Summary

After completing this course, you should be able to:


Create J2EE components by using best practices
Develop J2EE applications by using servlets,
JSPs, and EJBs
Test J2EE components by using Web and Java
clients
Implement J2EE security in applications
Deploy J2EE applications to Oracle Application
Server 10g
Develop Web services, and provide access to
them

1-12

Copyright 2004, Oracle. All rights reserved.

J2EE Overview

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe the Java 2, Enterprise Edition (J2EE)
platform
Define the various components of J2EE
Describe the deployment options for a J2EE
application
Describe the architecture of Oracle Application
Server 10g Containers for J2EE (OC4J)
Describe the directory structure and the uses of
the configuration files of OC4J

2-2

Copyright 2004, Oracle. All rights reserved.

Java 2, Enterprise Edition Platform

The Java 2, Enterprise Edition (J2EE) platform is a


standard for developing and implementing
enterprisewide applications:
It provides multitier applications support.
It is designed to help improve the process of
developing, deploying, and implementing
enterprisewide applications.

2-3

Copyright 2004, Oracle. All rights reserved.

J2EE Platform

Is a multitiered, distributed application model


Supports component-based J2EE applications
Servlet

Web clients

JSP Page
Web components

Application

Enterprise
Beans

Browser

2-4

EJB clients

EJB components

Client tier

Middle tier

Copyright 2004, Oracle. All rights reserved.

EIS tier

Benefits of the J2EE Platform

2-5

Write once, run anywhere provides simplified


component development.
Multiple server products and vendors support the
J2EE standard, thus giving more deployment
choices.
Integration with legacy systems through standard
APIs is possible.
J2EE separates client requirements from business
logic.
J2EE provides multiple development and design
scenarios.

Copyright 2004, Oracle. All rights reserved.

Benefits of the J2EE Platform

2-6

J2EE separates development tasks into specific


skill areas.
Web designers can create JSP components.
Application behavior is created by Java
programmers.
Business logic and rules are created by Java
programmers and business experts.
Assembly and deployment can be assigned to
production environment teams.

Copyright 2004, Oracle. All rights reserved.

J2EE Components

J2EE is a component-based architecture for the


development and deployment of enterprisewide
applications.
A component is an application-level software unit.
Components can be easily updated as business
needs change.
Components are reusable.
There are several types of components:
Client-side components
Web components
Business-tier components

2-7

Copyright 2004, Oracle. All rights reserved.

J2EE 1.3 Components

The J2EE 1.3 Specification lists the following


components:
Java Message Service
Servlet 2.3
1.0.2
JavaServer Pages 1.2
Java Transaction API 1.0
Enterprise
Java Authentication and
JavaBeans 2.0
Authorization Service
JDBC 2.0
1.0
RMI-IIOP
J2EE Connector
JNDI 1.2
Architecture 1.0
Web services 1.1
SOAP with Attachments
API for Java 1.1
2-8

Copyright 2004, Oracle. All rights reserved.

J2EE Architecture
J2EE Server
Web Container
Browser

Application
Client

Java Servlet/JSP

EJB

EJB

Business container
APIs

Application
Client
Container

JNDI

JTA

JMS

Client Machine

RMI

JDBC

JAF

JavaMail

2-9

Copyright 2004, Oracle. All rights reserved.

Database

Client-Tier Components

A Web browser:
Is used for a Web-based J2EE application
Downloads static or dynamic Web pages from Webtier components
Is a thin client

An application client:

2-10

Is used for a non-browser-based J2EE application


Executes on the client machine
Can contain a graphical or command-line interface
Is a thick client
Accesses business-tier components or a servlet on
the Web tier
Copyright 2004, Oracle. All rights reserved.

J2EE Web-Tier Components

A Web tier may consist of:


Java servlets
JSPs

Servlets and JSPs:

Work on a request-response model


Generate HTML dynamically
Access the database through JDBC
Access the business-tier components
Handle user-centric events, such as an HREF link or
form submission
Usually generate visual interfaces such as a Web
page
2-11

Copyright 2004, Oracle. All rights reserved.

What Is a Servlet?

Servlet

Browser

Client info (host name,


form data)

Request

Process results
(access database)
Format results and produce
HTML

Success or failure

Send page back to client


Response
2-12

Copyright 2004, Oracle. All rights reserved.

What Is a JavaServer Page (JSP)?

A JSP:
Is a text-based document that includes:
HTML
JSP tags
Java code (including calls to JavaBeans
and servlets)

2-13

Cleanly separates content creation from


presentation logic
Focuses on rapid development and easy
modification of the user interface
Provides presentation-centric method of
developing servlets
Copyright 2004, Oracle. All rights reserved.

Web-Tier Components: Summary

Web-tier components generate dynamic content.


Servlets:
Extend Web server functionality
Are designed more for processing than for
presentation

JSPs:
Combine HTML (or other markup) and Java
Are designed to separate content creation from
presentation logic
Are precompiled and converted to servlets at run
time

2-14

Copyright 2004, Oracle. All rights reserved.

Business-Tier Components

Business-tier components:
Are EJBs
Handle business logic
Receive data from client programs
Retrieve data from database storage
Process the data and communicate with the
database and the client program
Can be invoked by the Web-tier components

2-15

Copyright 2004, Oracle. All rights reserved.

Enterprise JavaBeans (EJB)

Enterprise JavaBeans:
Are server-side components written in Java
Contain the business logic of an enterprise
application
Are hosted in EJB containers
Are based on Remote Method Invocation (RMI)
communication
Are platform independent
Provide remote services for clients
Can be exposed as Web services
Use JDBC to connect to a database
2-16

Copyright 2004, Oracle. All rights reserved.

J2EE Communication APIs

J2EE provides component communication


through APIs.
The APIs include:
RMI
JNDI
JDBC

2-17

These APIs facilitate communication between the


J2EE components.

Copyright 2004, Oracle. All rights reserved.

J2EE Server

The J2EE server provides:


Containers for each component type of a J2EE
application
System-level services to components:
Naming and directory services (JNDI)
Security services for Web components and EJBs
(JAAS)
Transaction architecture (JTA)
Remote client connectivity:
Enterprise beans (RMI/IIOP, ORMI)
Servlet/JSP (HTTP, HTTPS, FTP)

2-18

Copyright 2004, Oracle. All rights reserved.

Oracle Application Server 10g Containers


for J2EE (OC4J)

OC4J is the J2EE server implementation in Oracle


Application Server 10g
Key features:

2-19

Implements J2EE 1.3 Specification


Runs on standard JVM
Provides high performance and scalability
Is productive for developers to use
Is simple to manage and deploy
Provides clustering for high availability and failover

Copyright 2004, Oracle. All rights reserved.

J2EE Applications

J2EE applications consist of J2EE components and


are deployed in the form of modules:
Web modules contain the user interface: HTML,
JSP, and servlets.
EJB modules contain reusable EJB components.
Client modules provide access to remote
application code.
Packaging information identifies dependencies
between modules.

2-20

Copyright 2004, Oracle. All rights reserved.

Packaging J2EE Application Components

1. ejb.jar
Bean class, Home and Remote
interfaces, other supported files, DD
2. webtier.war
Java servlets, JSP files, HTML, GIF files,
DD (references to EJBs)
J2EEapplication.ear
3. J2EEappClient.jar
J2EE application client (Java class),
DD (references to EJBs)
4. DD for J2EE application (.xml)
DD = XML Deployment
Descriptor
2-21

5. Resource adapter (.rar)

Copyright 2004, Oracle. All rights reserved.

JARs

2-22

Are simple Java Archive files


Are used to package application files together
(for example, classes, images, and so on)
Can be included in Web Archives (WARs) and
Enterprise Archives (EARs)
Can be included in library paths

Copyright 2004, Oracle. All rights reserved.

WARs

Are specialized archives for packaging J2EEcompliant Web applications


Have a fixed directory structure
Have a deployment descriptor for the Web
application
WEB-INF
web.xml
classes
lib
index.html

Contain servlet code and


JavaBeans not in standard
JAR files
Contains required classes
that are packaged in
standard JAR files

welcome.jsp

2-23

Copyright 2004, Oracle. All rights reserved.

EJB JARs

Are specialized JARs for packaging EJBs


Have a fixed directory structure
Have a deployment descriptor for the EJB
components
myEJB
META-INF
ejb-jar.xml
EJB Classes
Remote, Home and
Bean classes

2-24

Contain the class files


for the EJBs, usually
in a package directory
structure

Copyright 2004, Oracle. All rights reserved.

EARs

The EAR files:


Are specialized archives for packaging J2EEcompliant enterprise applications for deployment
Have a deployment descriptor
May have Web modules
May have EJB modules
May have client modules

2-25

Copyright 2004, Oracle. All rights reserved.

EAR File Structure for a


J2EE Application: Example
<appname>
|-------META-INF
|
|-------application.xml
|-------<ejb_module>
|
|-------EJB classes
|
|-------META-INF
|
|-------ejb-jar.xml
|-------<web_module>
|
|-------index.html
|
|-------JSP pages
|
|-------WEB-INF
|
|----web.xml
|
|----classes
|
|-------Servlet classes
|-------<client_module>
|
|-------Client classes
|
|-------META-INF
|
|-------application-client.xml

2-26

Copyright 2004, Oracle. All rights reserved.

OC4J Architecture

Oracle HTTP
Server
HTTP

JNDI
AJP

mod_oc4j

AJP13

Web
container

JMS
JDBC
JTA

Client
JAAS
ORMI

EJB
container

JCA
JavaMail

ORMI
JAF
EJB client

2-27

OC4J server process

Copyright 2004, Oracle. All rights reserved.

OC4J Server Configuration Files


OC4J Server XML Files
Server Configuration
server.xml

Web site
Web
Website
site

jazn.xml*
jazn-data.xml*

default-website.xml

data-sources.xml
rmi.xml
jms.xml
Oracle HTTP Server
configuration files
mod_oc4j.conf

2-28

Copyright 2004, Oracle. All rights reserved.

Relation of Configuration Files

When an application is deployed, an entry is made in


the \config\server.xml file:

<application name="lesson02"
path="../applications/lesson02.ear" />

For each Web module within the application, a context


root is defined in \config\default-web-site.xml:
<web-app application="lesson02" name="webapp1"
root="/lesson02"/>

The modules of the application are defined in


\applications\lesson02\METAINF\application.xml:
<web><web-uri>webapp1.war</web-uri></web>

2-29

Copyright 2004, Oracle. All rights reserved.

Data Sources

A data source is the instantiation of an object that


implements the javax.sql.DataSource interface,
which enables you to retrieve a connection to a
database server.
OC4J data sources are defined in datasources.xml.

2-30

J2EE applications use JNDI to look up these


DataSource objects.

Copyright 2004, Oracle. All rights reserved.

Application Logging

Application logging in Oracle Application Server


10g is configured by specifying the location of a
log file in the application.xml file:
<log>
<file path="practice02-oc4j-app.log"/>
</log>

To create a log file formatted in XML, use Oracle


Diagnostic Logging (ODL):
<log>
<odl path="practice02-oc4j-app.log"/>
</log>

2-31

Copyright 2004, Oracle. All rights reserved.

J2EE Application Deployment to


Oracle Application Server 10g
Deploying to OC4J can be done in multiple ways:
Step 1: Create WAR,
EAR file

Step 2: Deploy
Step 2: Deploy

Use a commandline tool (such as


ANT).

Use Oracle Enterprise Manager


(installed with Oracle Application
Server 10g): Access the
Enterprise Manager Web site
Use JDeveloper specifyhttp://localhost:1810
an
Application Server and click
'Deploy'
(requires
login).
Use JDeveloper.
Use JDeveloper: Specify an
application server and click
Deploy.

2-32

Copyright 2004, Oracle. All rights reserved.

Oracle Enterprise Manager

localhost

2-33

Copyright 2004, Oracle. All rights reserved.

JDeveloper and J2EE


JDeveloper provides:
Integrated development, deployment, and testing
support for Web-tier and business-tier
components
A J2EE framework for rapid development
Application Development Framework (ADF)
business components
Data tags

2-34

Integration with Struts


UML modeling
JDeveloper
Visual editors for Web clients
Easy deployment to Oracle Application Server 10g

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g Environment

Customizable code editor


Wizards for
JSPs,
servlets, and
EJBs
Error
checking
for HTML
and JSP
EAR, WAR
deployment
to J2EE
server
2-35

Code insight
Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g


Visual Design Tools

Drag JSP, HTML


elements

Design in visual
or code views

2-36

Modify values
in property
inspector
Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned that:


J2EE is a set of Java technologies that support
end-to-end application development
Components are the foundation of the J2EE
architecture
Web components (servlets, JSPs) generate
dynamic content
Business components (EJBs) are server-side
components that contain business logic
Applications can be built by using Oracle
JDeveloper 10g and deployed to a J2EE server,
such as Oracle Application Server 10g
2-37

Copyright 2004, Oracle. All rights reserved.

Practice 2-1: Overview

This practice covers the following topics:


Navigating to the OC4J console by using Oracle
Enterprise Manager
Mapping a data source in OC4J
Restarting the OC4J server instance from Oracle
Enterprise Manager
Deploying an EAR file by using Oracle Enterprise
Manager

2-38

Copyright 2004, Oracle. All rights reserved.

Designing J2EE Applications

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe the various Java 2, Enterprise Edition
(J2EE) patterns
Use the Model View Controller (MVC) architecture
to design more efficient and maintainable
applications
Identify sample architectures and their merits and
demerits

3-2

Copyright 2004, Oracle. All rights reserved.

Realizing J2EE Benefits

To leverage the full benefits of J2EE, you must design


applications that are:
Portable: You should be able to redeploy the J2EE
applications to different servers, databases, and
so on.
Scalable: Web applications should be able to
handle large numbers of users.
Maintainable: A minimum amount of coding
should be necessary for a new business rule.
Reusable: A class that processes credit cards
should be reused by multiple applications.
Simple: The business need should be solved with
the least amount of complexity.
3-3

Copyright 2004, Oracle. All rights reserved.

J2EE Issues

It is important to follow certain guidelines for the


design and development of any new technology:
Implement generally accepted design patterns and
architectures.
Focus on real business needs rather than simply
adopting new technology.
Employ the simplest technology to solve a
business problem.

3-4

Copyright 2004, Oracle. All rights reserved.

J2EE Design Patterns

Recurring application development issues have led to


the acceptance of design patterns. The generally
accepted design patterns include (but are not limited
to) the following:
Presentation-tier patterns
Intercepting filter
Controller servlet

Business-tier patterns
Business delegate
Transfer object

3-5

Copyright 2004, Oracle. All rights reserved.

Implementing Design Patterns by


Using MVC
MVC is a framework that separately identifies the
components of an application as:

Business functionality (Model)

Presentation (View)

Control logic (Controller)

View

Controller

Model
3-6

Copyright 2004, Oracle. All rights reserved.

The Model

The model represents the enterprise data and


business rules, handling access and updates.
You can simplify the model by using two
mechanisms called faade class and command
pattern.
A faade encapsulates and hides the complexity,
and coordinates the operations between
cooperating classes.
A command pattern encapsulates each application
function in a separate class.

3-7

The model is often implemented as EJBs.

Copyright 2004, Oracle. All rights reserved.

The View

The view focuses on presentation and is


responsible for maintaining consistency between
data presentation and model changes. It enables:
Presentation to be changed without altering
programming logic
Development by Web page authors having only
visual design skills

3-8

The view is commonly implemented as JSPs.

Copyright 2004, Oracle. All rights reserved.

The Controller

The controller provides interaction with the client,


serving as a glue between the model and the
view.
The controller:
Interprets user requests, and controls business
objects to fulfill these requests
Removes navigation coding from the view
Can be implemented in the client, Web, or EJB tier
or in a combination of these tiers

3-9

The controller is usually implemented as a servlet.

Copyright 2004, Oracle. All rights reserved.

MVC in Oracle Application Server 10g


Containers for J2EE
View

Controller
Selected
view

Model
Method
invocation
Return
result

JSP
HTTP
request

Servlet

HTTP
response

Browser

3-10

Copyright 2004, Oracle. All rights reserved.

Enterprise
JavaBeans

Designing J2EE Applications

Use the following techniques when designing J2EE


applications:
Use case analysis: Identify the operations that
each component will perform.
Decide how to distribute application functionality
across tiers:
A JSP or servlet can access the database by using
JDBC, without interfacing with the EJB tier.
Creating EJBs relieves the developer from the task
of managing transactions.

3-11

Copyright 2004, Oracle. All rights reserved.

Flow Diagram: Example

Customer

Receive
order
status

Log in

Place
orders

Fill orders

Browse
products

Update
inventories

Administrator

Vendor

3-12

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Consider generally accepted patterns when
designing J2EE applications
Identify the model, the view, and the controller
components for a J2EE application

3-13

Copyright 2004, Oracle. All rights reserved.

Practice 3-1: Overview

This practice covers using J2EE design patterns and


the MVC architecture to identify components for a
proposed application.

3-14

Copyright 2004, Oracle. All rights reserved.

Creating the Web Tier: Servlets

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define the role of servlets in a J2EE application
Describe the servlet life cycle
Describe the request and response architecture
Implement HTTP servlet methods
List J2EE servlet mapping techniques
Handle errors in a servlet
Create and run a servlet in JDeveloper
Deploy a J2EE application to Oracle Application
Server 10g
4-2

Copyright 2004, Oracle. All rights reserved.

Overview

Requests

Client Web browser

Connects to

Servlet
Generates

Responds

Dynamic HTML
4-3

Copyright 2004, Oracle. All rights reserved.

About Java Servlets

A servlet is a Java class that implements the


Servlet interface.

A servlet runs in the context of a special process


called a servlet engine.
Servlets can be invoked simultaneously by
multiple clients.

Java application,
Servlet, JSP,
or HTML

Request
Servlet engine
Response

Client
Server
4-4

Copyright 2004, Oracle. All rights reserved.

Principal Features of Servlets

Concurrent requests are possible and common.


Servlet methods are run in threads.
Servlet instances are shared by multiple client
requests.
Request 1

Request 2

Request 3
Server

Clients
4-5

Copyright 2004, Oracle. All rights reserved.

Life Cycle of Servlets

All actions are carried out inside the server.


After initial setup, the response time is less.
1

Load

Initialize
init()

3
Execute
service()

4
Destroy
destroy()

4-6

Copyright 2004, Oracle. All rights reserved.

HTTP Servlets

HTTP servlets extend the HttpServlet class,


which implements the Servlet interface.

A client makes an HTTP request, which includes a


method type that:
Can be either a GET or POST method type
Determines what type of action the servlet will
perform

The servlet processes the request and sends back


a status code and a response.
Request

Client
4-7

Response
HTTP protocol

Copyright 2004, Oracle. All rights reserved.

Servlet

Inside an HTTP Servlet

The servlet overrides the doGet() or the


doPost() method of the HttpServlet class.
The servlet engine calls the service() method,
which in turn calls one of the appropriate doXxx()
methods.
These methods take two arguments as input:
HttpServletRequest
HttpServletResponse

HttpServlet subclass
doGet()

Request
service()

Browser
Response

4-8

Copyright 2004, Oracle. All rights reserved.

Servlet: Example

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimplestServlet extends
HttpServlet
{
public void doGet(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
4-9

Copyright 2004, Oracle. All rights reserved.

The doGet() Method

The most common HTTP request method type


made to a Web server is GET.
The service() method in your servlet invokes
the doGet() method. The service() method is
invoked on your behalf by the Web server and the
servlet engine.
The doGet() method receives two parameters as
input:
HttpServletRequest
HttpServletResponse

Pass parameters by appending them to the URL


http://www.oracle.com/servlet?param1=value1

4-10

Copyright 2004, Oracle. All rights reserved.

The doPost() Method

The doPost() method can be invoked on a servlet


from an HTML form via the following:
<form method="post" action=>

The service() method in your servlet invokes


the doPost() method. The service() method is
invoked by the Web server and the servlet engine.
The doPost() method receives two parameters as
input:
HttpServletRequest
HttpServletResponse

Pass parameters using the form field names


<input type="text" name="param1">

4-11

Copyright 2004, Oracle. All rights reserved.

The HttpServletRequest Object

The HttpServletRequest object encapsulates


the following information about the client:

Servlet parameter names and values


The remote host name that made the request
The server name that received the request
Input stream data

You invoke one of several methods to access the


information:
getParameter(String name)
getRemoteHost()
getServerName()

4-12

Copyright 2004, Oracle. All rights reserved.

The HttpServletResponse Object

The HttpServletResponse object encapsulates


information that the servlet has generated:
The content length of the reply
The MIME type of the reply
The output stream

You invoke one of several methods to produce the


information:
setContentLength(int length)
setContentType(String type)
getWriter()

4-13

Copyright 2004, Oracle. All rights reserved.

Methods for Invoking Servlets

Invoke servlets from a client by:


Typing the servlet URL in a browser
Embedding the servlet URL in an HTML or a
JavaServer Page (JSP) page, or another servlet (an
href link)
Submitting a form to the servlet (via the action tag)
Using URL classes in client Java applications

4-14

Invoke servlets inside the J2EE container by


defining a chain of servlets or JSPs.

Copyright 2004, Oracle. All rights reserved.

Your First Servlet


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
response.setContentType ("text/html");
PrintWriter out = response.getWriter();
out.println ("<html>");
out.println ("<body>");
out.println ("Hello World!");
out.println ("</body></html>");
}
}
4-15

Copyright 2004, Oracle. All rights reserved.

Handling Input: The Form

You can use an HTML form and the doPost() method


to modify the HelloWorld servlet.
<html><body>
<form method="post" action="newhelloworld">
Please enter your name. Thank you.
<input type="text" name="firstName"> <P>
<input type="submit" value="Submit">
</form>
</body>
</html>

4-16

Copyright 2004, Oracle. All rights reserved.

Handling Input: The Servlet

public class NewHelloWorld extends HttpServlet {


public void doPost(
HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println ("<html><body>");
String name = req.getParameter("firstName");
if ((name != null) && (name.length() > 0))
out.println ("Hello: " + name +
" How are you?");
else
out.println ("Hello Anonymous!");
out.println ("</body></html>");
}}
4-17

Copyright 2004, Oracle. All rights reserved.

Initialization and Destruction

Servlets also define the init() and destroy()


methods in addition to the service() method.
init():
Can be used to retrieve initialization parameters
Takes a ServletConfig object as a parameter
Is invoked when the servlet instance is created
Is useful for obtaining database connections from a
connection pool

destroy():
Takes no arguments
Is invoked when the servlet is about to be unloaded
Is useful for releasing resources

4-18

Copyright 2004, Oracle. All rights reserved.

Error Handling

ServletException:
Is generated to indicate a generic servlet problem
Is subclassed by UnavailableException to
indicate that a servlet is unavailable, either
temporarily or permanently
Is handled by the servlet engine in implementationdependent ways

4-19

IOException: Is generated if there is an input or


output error while processing the request

Copyright 2004, Oracle. All rights reserved.

Debugging a Servlet

Servlets can be debugged in the following ways:


Setting breakpoints and using the debugger in
JDeveloper
Viewing the source of the generated HTML

4-20

Copyright 2004, Oracle. All rights reserved.

SingleThreadModel

You can implement the SingleThreadModel


interface to prevent multithreaded access of data.
public class HelloWorld extends HttpServlet
implements SingleThreadModel{
public void doGet
}

4-21

Each concurrent request then has its own


dedicated servlet instance, which is randomly
assigned.

Copyright 2004, Oracle. All rights reserved.

JDeveloper Environment

The Servlet Wizard in JDeveloper makes it easy for you


to write servlets. The wizard:
Provides the doGet() and doPost() method
skeletons
Provides an environment for running the servlet
within the integrated development environment
(IDE)
Dynamically creates the web.xml file for running
the servlet from the IDE
Allows the creation of a deployment file that aids
in deploying to an OC4J server

4-22

Copyright 2004, Oracle. All rights reserved.

Servlet Mapping

Mapping a servlet refers to how a client can


access a servlet.
You can map a servlet:
To any URL that begins with a certain directory
name
By using the direct URL:
http://host:port/<contextroot>/servlet/<package>.<servlet>

By using the mapped URL:


http://host:port/<contextroot>/servlet/<mappedservletname>

4-23

<context-root> is the mapping for the Web module

Copyright 2004, Oracle. All rights reserved.

Servlet Mapping in JDeveloper


JDeveloper provides the standard J2EE model for
mapping servlets by using the web.xml file:
<?xml version = '1.0' encoding = 'UTF-8'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>package1.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/helloworld</url-pattern>
</servlet-mapping>

</web-app>

4-24

Copyright 2004, Oracle. All rights reserved.

Invoking a Servlet

4-25

Copyright 2004, Oracle. All rights reserved.

Specifying J2EE Web Module Settings

4-26

Copyright 2004, Oracle. All rights reserved.

Creating a Connection to Oracle


Application Server 10g

4-27

Copyright 2004, Oracle. All rights reserved.

Deploying to OC4J

4-28

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the servlet life cycle
Develop and run a servlet in JDeveloper
Map a servlet in a J2EE server
Collect information from a client
Respond to the client
Handle errors in a servlet
Deploy a servlet to Oracle Application Server 10g

4-29

Copyright 2004, Oracle. All rights reserved.

Practices 4-1, 4-2, and 4-3: Overview

These practices cover the following topics:


Creating a servlet that invokes the doPost()
method and running it from an HTML form
Creating a servlet that invokes the doGet()
method to create an HTML form
Deploying a servlet to Oracle Application Server
10g

4-30

Copyright 2004, Oracle. All rights reserved.

4-31

Copyright 2004, Oracle. All rights reserved.

Accessing the Database with Servlets

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Load and register a JDBC driver
Connect to an Oracle database by using data
sources
Navigate in a ResultSet
Use PreparedStatement

5-2

Create a pool of connections

Copyright 2004, Oracle. All rights reserved.

Review of JDBC

5-3

JDBC is a standard interface for connecting to


relational databases from Java.
The JDBC classes and interfaces are in the
java.sql package.

Copyright 2004, Oracle. All rights reserved.

Querying in JDBC

Connect

Query

Process results

Close

5-4

import java.sql.*;
DriverManager.registerDriver()
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin
Statement stmt =
conn.createStatement ();
ResultSet rset =
stmt.executeQuery (
"select * from EMPLOYEES");
while (rset.next ())
System.out.println(
rset.getString (2));
rset.close();
stmt.close();
conn.close();

Copyright 2004, Oracle. All rights reserved.

JDBC and Servlets

There are three ways to use JDBC in a servlet:


Register the JDBC driver within the servlet by hard
coding the driver name in either the servlet or in a
properties file.
Use the JDBC driver from the data-sources.xml
file that is provided with Oracle Application Server
10g.
Use a properties file to store connection details.

In all cases, optimize the connection:


Initialize the database connection in the servlets
init() method (or retrieve from a pool).
Close the database connection in the destroy()
method (or return to a pool).

5-5

Copyright 2004, Oracle. All rights reserved.

Synchronizing Shared Resources

Reuse PreparedStatement objects.


Sharing Statement objects may not be
thread safe.
Use a synchronized block.
PreparedStatement ps =

synchronized (ps) {
ps.clearParameters();
ps.setInt(1,3);
ps.setDouble(2, 3.14);
ps.executeUpdate();
}

5-6

Copyright 2004, Oracle. All rights reserved.

Transaction Handling

Initialize Connection in the servlets init() method.

Problems with transactions:


The Connection object in the servlets init()
method is shared.
The commit() method depends on the Connection
object.

Solutions for transactions:


Create a new Connection object.
Use the synchronized keyword.
Use the SingleThreadModel interface.
Use session tracking.

5-7

Copyright 2004, Oracle. All rights reserved.

Connection Pooling

Pooled Connection objects are used and released by


servlet instances. A connection pool performs the
following tasks:
Preallocates database connections
Manages available connections
Allocates new connections
Closes connections that are no longer in use

5-8

Copyright 2004, Oracle. All rights reserved.

Data Sources

Data sources provide logical mappings of


databases:
Developer uses the logical representation of a
database.
Deployer maps to the physical data sources.

J2EE applications use published DataSource


objects by:
Looking up the published name via Java Naming
and Directory Interface (JNDI).
Using JDBC Connection methods to connect to the
database.

5-9

Data sources are published in the JNDI tree.


Data sources come in different varieties.
Copyright 2004, Oracle. All rights reserved.

Data Source Definition

Global data sources are defined in the


OC4J_HOME/config/data-sources.xml file.
You specify each data source by using an XML tag.
Attributes specify values for the data source.

Application-specific data sources: Use the <datasources> tag in the application.xml file.
OC4J_HOME/applications
myapp
application.xml

Points to
data-sources.xml

5-10

Copyright 2004, Oracle. All rights reserved.

data-sources.xml: Example

<data-source
class="com.evermind.sql.DriverManagerDataSource"
connection-driver="oracle.jdbc.driver.OracleDriver"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleDS"
ejb-location="jdbc/OracleDS"
min-connections="5"
max-connections="25"
username="oe"
password="oe"
url="jdbc:oracle:thin:@<host>:<port>:<SID>"
/>

5-11

Copyright 2004, Oracle. All rights reserved.

Using Data Sources

To use a defined data source in a servlet:


1. Use the lookup method of the
javax.naming.Context class to retrieve the
named data source class.
2. Create the connection.
try {
Context ic = new InitialContext();
DataSource ds =
(DataSource)ic.lookup("jdbc/OracleDS");
Connection conn = ds.getConnection();
} catch (SQLException se) { }
catch (NamingException ne) { }

5-12

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Create a servlet to connect to the database by
using JDBC
Load and register a JDBC driver
Connect to an Oracle database by using data
sources
Navigate in a ResultSet
Use PreparedStatement

5-13

Improve database performance by using


connection pooling

Copyright 2004, Oracle. All rights reserved.

Practice 5-1: Overview

This practice covers the following topics:


Connecting to the database by using JDBC
Retrieving database information and formatting it
for output in a servlet

5-14

Copyright 2004, Oracle. All rights reserved.

Using Advanced Techniques in Servlets

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Use a cookie in a servlet
Send HTTP headers to the client
Use servlet filters
Define event listeners

6-2

Copyright 2004, Oracle. All rights reserved.

Overview

Request
getCookies()
getHeader()

Response
Client Web
browser

setHeader()
addCookie()

Servlet

Error handling
6-3

Copyright 2004, Oracle. All rights reserved.

HTTP Headers

6-4

Headers are HTTP details that are passed between


the browser and the server.
They can be response or request headers.
The getHeader() method of
HttpServletRequest retrieves the string value of
the header.
The setHeader() method of
HttpServletResponse sends a header to the
browser.

Copyright 2004, Oracle. All rights reserved.

Request Headers

Additional request headers include the following:

6-5

Accept

Specifies MIME types that the browser


supports

AcceptLanguage

Specifies the browsers preferred language

Cookie

Returns cookies to servers that previously


sent them to the browser

Referer

Indicates the URL of the referring Web page,


for tracking users

User-Agent

Identifies the browser that is making the


request, for checking browser features

Copyright 2004, Oracle. All rights reserved.

Sending a Response

There are three aspects to sending a response:


Sending HTTP headers
Sending a status code (an integer denoting the
nature of response)
Sending multimedia content

6-6

Copyright 2004, Oracle. All rights reserved.

Response Headers

6-7

The HttpServletResponse class is used to send


headers.
You have seen an example of setting header
information: setContentType("text/html");.
Other headers are set by using the setHeader()
method.
Do not confuse HTTP headers with the HEAD tag in
HTML pages.

Copyright 2004, Oracle. All rights reserved.

Setting Status Codes

If a servlet does not specify a status code, then


the Web server sends the default status code
(200).
You can explicitly set a status code by using the
setStatus() method.

Example:
int pageVersion =
Integer.parseInt(req.getParameter("pageVersion"));
if (pageVersion >= currentVersion){
response.setStatus(response.SC_NO_CONTENT);
}else{
//Send original page
}

6-8

Copyright 2004, Oracle. All rights reserved.

Example

Assume that the randomSite() method generates


a Web site randomly.
For example, http://www233.oracle.com

Requests to www.oracle.com can be sent to this


site to provide load balancing.

public void doGet(


HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException{
String tempSite = this.randomSite();
// implementation not shown
res.setStatus(res.SC_MOVED_TEMPORARILY);
res.setHeader("Location", tempSite);
}

6-9

Copyright 2004, Oracle. All rights reserved.

Sending Multimedia Content

6-10

Multimedia content usually contains binary


response data.
Use the getOutputStream() method instead of
the getWriter() method if you want to send
binary data, such as images.
Use the setContentType() method with the
image/gif MIME type to send a GIF-encoded
image.
Use other MIME types to send other types of
multimedia content.

Copyright 2004, Oracle. All rights reserved.

Cookies

6-11

A cookie is a name or value pair sent by a servlet


to a browser in the header.
Cookies are persistent (the information sent is
stored on the client, to be retrieved later).
Cookies are often used to obtain state information,
such as a username or preference.

Copyright 2004, Oracle. All rights reserved.

Setting Cookies

Use the Cookie() constructor to create a new


cookie.
Use the addCookie() method in the
HttpServletResponse class to add and send the
cookie to a browser.
Cookie userCookie = new Cookie ("user", "fred");
userCookie.setMaxAge(60*60); //one hour
response.addCookie(userCookie);

6-12

Copyright 2004, Oracle. All rights reserved.

Retrieving Cookies

Use the getCookies() method to fetch an array of


Cookie objects.
Cookie[] cookies = request.getCookies();
if (cookies != null) {
String readValue;
for (int i = 0; i < cookies.length; i++)
readValue = cookies[i].getValue();

6-13

Copyright 2004, Oracle. All rights reserved.

About State Preservation

6-14

Usually, the servlet engine instantiates the servlet


only once.
Any number of requests can be handled by the
same instance of the servlet class.
Values of any instance variable in the class persist
between HTTP requests from multiple browsers.
Values of variables in the doGet() or doPost()
method do not persist between multiple browser
requests.

Copyright 2004, Oracle. All rights reserved.

State Preservation: Example


public class StateServlet extends HttpServlet {
int counter = 0; //persistent variable
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("firstName");
// name is transient variable
out.println ("<html><body>");
out.println ("Hello: " + name);
out.println ("Hit count is: " + ++counter);
out.println ("</body></html>");
}}
6-15

Copyright 2004, Oracle. All rights reserved.

ServletContext

6-16

The ServletContext interface defines the servlet


within the Web application.
Methods in ServletContext allow for retrieving
the MIME type of a file, dispatching requests to
other servlets, or writing to a log file.

Copyright 2004, Oracle. All rights reserved.

RequestDispatcher

To forward the request to another servlet or JSP,


use the RequestDispatcher interface:
getServletContext().getRequestDispatcher(String
url).

RequestDispatcher contains two methods:


forward() and include().
Use the forward() method to transfer control to
the associated URL.

6-17

These methods take HttpServletRequest and


HttpServletResponse as arguments.

Copyright 2004, Oracle. All rights reserved.

RequestDispatcher: Example

public void doPost(HttpServletRequest request,


HttpServletResponse response) throws
ServletException, IOException
{
String name = request.getParameter("firstName");
if (name == null){
String url = "/loginerror.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
else {out.println ("Hello: " + name) ;}
}

6-18

Copyright 2004, Oracle. All rights reserved.

Servlet Filters

Filters dynamically change the content or header of a


request or response. A filter is used to:
Intercept a request before a servlet is called
Modify the request, response, and header values
Optionally, customize the response

6-19

Copyright 2004, Oracle. All rights reserved.

Using Filters

The javax.servlet.Filter interface is implemented


to use a filter, and contains three methods:
void init(FilterConfig)
void doFilter(ServletRequest,
ServletResponse, FilterChain)
void destroy()

6-20

Copyright 2004, Oracle. All rights reserved.

doFilter() Method

The doFilter() method:

6-21

Examines the request header


Modifies request headers by wrapping the
request object
Modifies the response by wrapping the response
object
Invokes the next filter in the filter chain

Copyright 2004, Oracle. All rights reserved.

Using Filters

import javax.servlet.*; import javax.servlet.Filter;


import java.io.*;
public class HelloFilter implements Filter {
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig){
System.out.println("Filter Initialized");
}
public void doFilter (ServletRequest request,
ServletResponse response, FilterChain chain) throws
IOException, ServletException {
System.out.println("Hello from Filter");
chain.doFilter(request, response);
}
public void destroy(){}
}
6-22

Copyright 2004, Oracle. All rights reserved.

Configuring Filters

To use a servlet filter, the web.xml deployment


descriptor is modified to include the <filter> tag:
<filter>
<filter-name>HelloFilter</filter-name>
<filter-class>filterpackage.HelloFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<servlet-name>StateServlet</servlet-name>
</filter-mapping>

6-23

Copyright 2004, Oracle. All rights reserved.

Application Lifecycle Events

6-24

Lifecycle Events are a new feature of the Servlet


2.3 API.
Event listeners are used to check for state
changes.
There are two types of events: ServletContext
and HttpSession.
Event listeners can be notified when objects are
initialized, destroyed, or when their attributes
change.

Copyright 2004, Oracle. All rights reserved.

ServletContext Events

Implement one or more ServletContext listener


interfaces to respond to ServletContext events. The
following methods are invoked when a
ServletContext event occurs:
contextInitialized()
contextDestroyed()
attributeAdded()
attributeRemoved()
attributeReplaced()

6-25

Copyright 2004, Oracle. All rights reserved.

HttpSession Events

Implement one or more HttpSession listener


interfaces to respond to HttpSession events. The
following methods are invoked when an HttpSession
event occurs:
sessionCreated()
sessionDestroyed()
attributeAdded()
attributeRemoved()
attributeReplaced()

6-26

Copyright 2004, Oracle. All rights reserved.

Example of an Event Listener

public class ConnectionManager implements


ServletContextListener {
public void
contextInitialized(ServletContextEvent
event) {
Connection conn = // create connection
event.getServletContext().setAttribute("conn",
conn);
}

6-27

Copyright 2004, Oracle. All rights reserved.

Error Handling

Java prevents a servlet from unintentionally or


maliciously damaging the servlet engine.
The Servlet API allows:
Logging of errors
Sending HTTP status codes to the client

In the doGet() method, Java requires that any


method that generates any exceptions must be
handled explicitly.
You can let the servlet engine handle only
IOException and ServletException, and not
any other exceptions (for example,
InterruptedException).

6-28

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Send headers and other content to the client
Use filters to modify servlet response
Handle state preservation
Handle errors that might arise during the
execution of your servlet

6-29

Copyright 2004, Oracle. All rights reserved.

Practices 6-1 and 6-2: Overview

These practices cover the following topics:


Creating a servlet that uses cookies
Using servlet filters to manipulate headers

6-30

Copyright 2004, Oracle. All rights reserved.

Maintaining State in J2EE Applications

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Maintain persistent activity from clients by using a
browser
Use the HttpSession object

7-2

Describe state preservation

Copyright 2004, Oracle. All rights reserved.

Overview

First request
Chris
Servlet
Second request
Chris

First request
Michelle
7-3

Copyright 2004, Oracle. All rights reserved.

Session Basics

7-4

The HTTP protocol is stateless.


The session mechanism guarantees that the
object that serves the client knows which client
has made a request.
User requests from the same browser are
considered to be from the same client.

Copyright 2004, Oracle. All rights reserved.

Session Basics

Options for identifying the client: Cookies, URL


rewriting, hidden fields, HttpSession

Result: A unique identity assigned to every client


Options for implementing sessions on the server:
Single-threaded model (not scalable)
HttpSession with a multithreaded server
(Each thread uses the unique identity to process the
request.)

7-5

Copyright 2004, Oracle. All rights reserved.

Threading

Multithreaded model

Single-threaded model

Client 1
Servlet instance 1

Client 1

Servlet instance 2

Client 2

Client 2
Both clients using
unique sessions, but
sharing the same
servlet instance

7-6

Both clients using


unique sessions and
unique instances

Copyright 2004, Oracle. All rights reserved.

URL Rewriting

URL rewriting:
Every URL that is accessed by the client is rewritten
so that it has the session ID.
Use the encodeURL() method to re-create the path
dynamically.

7-7

URL rewriting is used when a client turns off


cookie support in the browser.

Copyright 2004, Oracle. All rights reserved.

HttpSession

The unique identity for the client is an


HttpSession object.
The object is created by using the getSession()
method of the HttpRequest object.
HttpSession session = req.getSession(true);

7-8

Any servlet that responds to a client request can


create this object.
An object can be potentially shared across several
servlets. (Every servlet within an application can
identify with this client.)

Copyright 2004, Oracle. All rights reserved.

Session Objects

With session objects, you can:


Put items into the object (values persist across
multiple invocations from the same client)
Access items from the object
Obtain the session identity
Find out when the session was last accessed

Items put in a session object can:


Implement the Serializable interface
Be relocated to a different server
Persist across servlet crashes

7-9

Copyright 2004, Oracle. All rights reserved.

Session-Based Page Counter

public void doGet() {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String sessionid = session.getId();
Integer sessionCount =
(Integer)session.getAttribute("sessionCount");
if (sessionCount == null) {
sessionCount = new Integer(0);
} else { sessionCount =
new Integer(sessionCount.intValue() + 1);
}
session.setAttribute("sessionCount", sessionCount);
out.println("<p>Number of requests for the session with
the id of " + "<b>" + sessionid + "</b> is: " +
sessionCount);
}

7-10

Copyright 2004, Oracle. All rights reserved.

Session Life Cycle

A session can expire automatically, or you can


explicitly invalidate a session.
The HttpSession object gets invalidated when a
session expires.
Date dayAgo = new Date(
System.currentTimeMillis() - 24*60*60*1000);
Date hourAgo = new Date() // an hour ago
Date created = new Date(
session.getCreationTime());
Date accessed = new Date()
if (created.before(dayAgo)||
accessed.before(hourAgo)) {
session.invalidate(); session = //create new
}

7-11

Copyright 2004, Oracle. All rights reserved.

Session Tracking in OC4J

J2EE server vendors handle session tracking in


different ways.
Oracle Application Server 10g Containers for J2EE
(OC4J):
Uses cookies as the default method for session
tracking (can be disabled by a user or within the
application deployment descriptor)
Does not support auto-encoding, where session IDs
are automatically encoded into the URL by the
container (an expensive process)
Causes a session to expire in 20 minutes by default
(modified in the deployment descriptor)

7-12

Copyright 2004, Oracle. All rights reserved.

Sessions and Events


When a servlet stores an object in a session or
removes an object from a session, the session checks
whether that object implements the
HttpSessionBindingListener interface. If it does,
then the servlet notifies the object that it has been
either:
Bound to the session (by calling the objects
valueBound() method, which is a good place for
initializing client-specific resources)
Or
Unbound from a session (by calling the objects
valueUnbound() method, which is a good place
for releasing resources)
7-13

Copyright 2004, Oracle. All rights reserved.

Sessions and Events

An object is bound to a session after the object is


passed into the session.setAttribute()
method.
An object is unbound from a session:
After the object is removed by using the
session.removeAttribute() method
When a session is invalidated

7-14

Copyright 2004, Oracle. All rights reserved.

Sessions and Events

To use the event mechanism, you must perform the


following steps:
1. Create a class that implements the
HttpSessionBindingListener interface.
2. Instantiate the class.
3. Insert the instantiated object into the
HttpSession object by using the
setAttribute() method.

7-15

Copyright 2004, Oracle. All rights reserved.

Sessions and Events

Example:
public class EventObject
implements HttpSessionBindingListener {
public void valueBound(
HttpSessionBindingEvent event) {
// connect to the database using this client
sess = event.getSession()//which session?
// get values from this session object to
// identify client information
}
public void valueUnbound(
HttpSessionBindingEvent event) {
// release resources
}
}

7-16

Copyright 2004, Oracle. All rights reserved.

Creating Distributable Applications

Applications are deployed as distributable by


specifying the <distributable/> tag in the web.xml
file. These applications should be developed to run in
a distributed servlet container (such as OC4J) as
follows:
Because the ServletContext attributes exist
locally in one Java virtual machine (JVM), the
information that must be shared between servlets
should be placed in a session, a database, or an
EJB.
HttpSession objects must implement the
Serializable interface to be sent between JVMs.

7-17

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Instantiate the HttpSession object
Use the HttpSession object
Implement the HttpSessionBindingListener
interface

7-18

Copyright 2004, Oracle. All rights reserved.

Practice 7-1: Overview

This practice covers the following topics:


Creating an HttpSession object
Tracking an order based on the HttpSession
object

7-19

Copyright 2004, Oracle. All rights reserved.

Creating the Web Tier: JavaServer Pages

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Compare servlets and JavaServer Pages (JSP)
Build a simple JSP
Describe the JSP life cycle
List the basic JSP elements
Develop JSPs with declarations, expressions, and
scriptlets
List implicit objects
Use JavaBeans with JSP

8-2

Copyright 2004, Oracle. All rights reserved.

JavaServer Pages
Connects to

Request

JSP
Database
Client
Generates

Dynamic content

Response

8-3

Copyright 2004, Oracle. All rights reserved.

EJB

Comparing Servlets and JSPs

Servlets:
Are Java programs
with embedded
HTML
Generate dynamic
content
Do not separate
static and dynamic
content

8-4

JavaServer Pages:
Are HTML pages
with embedded Java
code or they can be
pure XML
Generate dynamic
content
Separate static and
dynamic content

Copyright 2004, Oracle. All rights reserved.

Invoking JSPs

HTML

Invoke
JSP

Servlet

JSP
8-5

Copyright 2004, Oracle. All rights reserved.

The Date JSP


<%@ page contentType="text/html;charset=WINDOWS-1252"%>
<html> <head>
<meta http-equiv="Content-Type" content="text/html;
charset=WINDOWS-1252">
<title> Show Date </title>
</head>
<body>
<h2> The current time is: </h2>
<p> <%= new java.util.Date() %> </p>
</body>
</html>

8-6

Copyright 2004, Oracle. All rights reserved.

The Date Servlet

...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Show Date
</title></head><body><h2>The current time
is:</h2><p>");
out.println(new java.util.Date());
out.println("</body></html>");
out.close();
}
...

8-7

Copyright 2004, Oracle. All rights reserved.

Automated JSP Features

A JSP is automatically converted into a servlet the


first time it is invoked:
Java source files are generated.
Java class files are generated.
The Java Just-In-Time compiler can be used.

A JSP can contain extensible components:


Tags: Libraries such as OC4J JSP (OJSP) or
custom-developed tags.
JavaBeans (Beans are reused and their properties
are automatically introspected.)

8-8

Copyright 2004, Oracle. All rights reserved.

JSP Life Cycle


J2EE container

First
time

OC4J

http://host/date.jsp

Yes
1
Create servlet
date.java

No

Compile servlet
date.class

Servlet life cycle

8-9

Copyright 2004, Oracle. All rights reserved.

Basic JSP Elements

A JSP contains three main elements:


Text elements
Directives
Scripting elements
Declarations
Expressions
Scriptlets

8-10

Copyright 2004, Oracle. All rights reserved.

Declarations

Are used to define methods or variables


Begin with the sequence <%!
End with the sequence %>

Are inserted into the body of the servlet class


during translation
Are used in conjunction with expressions or
scriptlets

<%! private int i=3; %>


<%! private String a="Hello", b=" World"; %>

8-11

Copyright 2004, Oracle. All rights reserved.

Expressions

Begin with the sequence <%=

Contain Java expressions that are evaluated and


inserted into the servlets output
End with the sequence %>

Do not end with a semicolon


<%= i+1 %>
1
<%= a + b %>
<%= new java.util.Date() %>

8-12

Copyright 2004, Oracle. All rights reserved.

Scriptlets

Begin with the sequence <%

Contain a block of Java code that is executed


every time a request is made
End with the sequence %>

<% if (i<3)
out.print("i<3");
if (i==3)
out.print("i==3");
else
out.print("i>3");
%>

8-13

Copyright 2004, Oracle. All rights reserved.

Implicit Objects

There are eight implicit objects, also known as


predefined variables, in JSP:
request
application
response
config
session
pageContext
out
page

8-14

Copyright 2004, Oracle. All rights reserved.

Example

8-15

Copyright 2004, Oracle. All rights reserved.

Directives

Are used to set global values such as class


declaration, method implementations, and so on
Begin with the sequence <%@
End with the sequence %>

Are of the following types:


page
include
taglib

8-16

Copyright 2004, Oracle. All rights reserved.

include: Example

8-17

Copyright 2004, Oracle. All rights reserved.

page Directive

You can define the following attributes by using the


page directive:
extends
import
info
contentType
errorPage
isThreadSafe
isErrorPage
session
language
buffer
autoflush

8-18

Copyright 2004, Oracle. All rights reserved.

JSP and JavaBeans

package lesson08;
import java.lang.*;
import java.util.*;
public class LuckyNumberBean {
private int luckyNum;
public LuckyNumberBean() {
luckyNum = (int) (1000 * Math.random());
}
public int getLuckyNum() {
return luckyNum;
}
public void setLuckyNum(int luckyNum) {
this.luckyNum = luckyNum;
}
}

8-19

Copyright 2004, Oracle. All rights reserved.

Using JavaBeans with JSP

Accessing JavaBeans with the <jsp:useBean> tag:


<jsp:useBean id="myBean" scope="session"
class="lesson08.LuckyNumberBean" />

8-20

Copyright 2004, Oracle. All rights reserved.

scope Attribute of <jsp:useBean> Tag


Client
Request

Response
Request

Response

Forward

Page 1

Page 2

Page 3

page scope

page scope

page scope

request scope

request scope

session scope
8-21

Copyright 2004, Oracle. All rights reserved.

Accessing and Setting Bean Property

Accessing bean property:


<jsp:getProperty name="myBean"
property=luckyNum" />

Setting bean property:


<jsp:setProperty name="myBean"
property=luckyNum" value="10" />

8-22

Copyright 2004, Oracle. All rights reserved.

JSP XML Document

Contains <jsp:root> as its root element

Includes only XML syntax and does not include


the traditional JSP tags
Can be processed directly by the JSP container
Can be used with XML development tools

8-23

Copyright 2004, Oracle. All rights reserved.

Traditional Syntax Versus XML Syntax

Traditional:
No root element

page directive
<%@ page %>

Declaration tag
<%!
%>
Expression tag
<%= expression %>
Scriptlet
<%
%>

8-24

XML:

<jsp:root> is the root


element
<jsp:directive.
page
/>
<jsp:declaration>
</jsp:declaration>
<jsp:expression>
</jsp:expression>
<jsp:scriptlet>
</jsp:scriptlet>

Copyright 2004, Oracle. All rights reserved.

JDeveloper and JSPs

Use the JSP Wizard in JDeveloper to create JSPs


containing skeleton code.
The structure pane helps to ensure that the JSP
and HTML tags are properly formatted.
Tag Insight automatically inserts end tags after
starting a scriptlet.
JSP code is automatically created and recompiled.
JDeveloper increases productivity while
debugging JSPs:
Automatically includes source Java files such as
your JavaBean source
Enables you to set breakpoints and watch
expressions in JSPs

8-25

Copyright 2004, Oracle. All rights reserved.

Creating JSPs Visually

8-26

Copyright 2004, Oracle. All rights reserved.

JSP Tag Insight

8-27

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Differentiate between servlets and JSPs
Build a simple JSP
Describe the JSP life cycle
Use JSP elements and implicit objects
Develop JSPs with declarations, expressions, and
scriptlets
Use JavaBeans with JSP

8-28

Copyright 2004, Oracle. All rights reserved.

Practices 8-1, 8-2, and 8-3: Overview

These practices cover the following topics:


Creating a JSP that counts the occurrence of each
character in a given string
Using JavaBean to calculate an equal discount on
the total amount of purchase
Creating a JSP that displays product_id,
product_name, and price in the form of a table

8-29

Copyright 2004, Oracle. All rights reserved.

Modularizing JavaServer Pages


Development with Tags

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define a custom tag
Use custom tags in a JavaServer Page (JSP)
Use the customizable Component Palette for JSP
Develop a JSP using the JSP Standard Tag Library
(JSTL)

9-2

Copyright 2004, Oracle. All rights reserved.

Custom Tags

Custom tags are developed in Java and defined


and used with XML syntax.
Tags are used in a JSP to reduce or constrain the
amount of Java scriptlets in the page.
Tags are useful for defining custom actions such
as:
Accessing a database
Defining recurring tasks
Sending e-mail

9-3

Collections of tags are grouped into JAR files


called Tag Libraries.

Copyright 2004, Oracle. All rights reserved.

Custom Tag Library Components

Custom Tag Libraries contain:


One or more tag handler class files
May contain additional supporting classes

A tag library descriptor (taglib.tld)


XML formatted

To use a tag in a JSP, perform the following:


1. Invoke the tag library by using the
<jsp:taglib/> directive.
2. Call the tag in the content of the JSP.
3. Include the location of the taglib.tld file in the
web.xml file.

9-4

Copyright 2004, Oracle. All rights reserved.

Tag Handler: Example


import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class HelloWorldTag extends TagSupport {
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("Hello from Custom Tag!!!");
}
catch(IOException io) {
System.out.println("Error in TagMessage: " + io);
}
return(SKIP_BODY);
}
public int doEndTag() {
return (SKIP_PAGE);
}
}

9-5

Copyright 2004, Oracle. All rights reserved.

Tag Library Descriptors

A tag library descriptor (.tld) is an XML document


that describes one or more tags and their attributes. It
contains the following elements:
<tlibversion> The tag librarys version
<jspversion>

The JSP specification version for the library

<shortname>

A default name for the library

<uri>

Identifies the tag library location

<info>

Documentation regarding the library

<tagclass>

Specifies the class for the individual tag

<bodycontent> Set to empty, tagdependent, or JSP

9-6

Copyright 2004, Oracle. All rights reserved.

Using a Custom Tag

<html>
<head>
<%@ taglib uri="webapp/taglib.tld"
prefix="mytags" %>
</head>
<body>
<h2>The following output is from the
HelloWorldTag:</h2>
<p>
<mytags:hellotag/>
</p>
</body>
</html>

9-7

Copyright 2004, Oracle. All rights reserved.

Tags with Attributes

Tags with attributes should include the get() and


set() methods for each attribute in the tag handler.

The tag library descriptor defines each attribute.


Supporting classes can validate attributes.
<tag> <name>hellotag</name>
<tagclass>HelloWorldTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>custName</name>
<required> true</required>
<rtexprvalue>true</rtexprvalue>
</attribute> </tag>

9-8

Copyright 2004, Oracle. All rights reserved.

Creating a Custom Tag in JDeveloper

To create a custom tag and a tag library in JDeveloper,


perform the following:
1. Create a tag library descriptor from the JavaServer
Pages category.
2. Right-click the .tld file in System Navigator and
select Add Tag to create a tag handler.
3. Right-click the .java file in System Navigator and
select Add Attribute or Add Scripting Variable
as necessary.
4. Add the tag library to the component palette.

9-9

Copyright 2004, Oracle. All rights reserved.

Tag Libraries in JDeveloper

9-10

Tag libraries are viewed in JDeveloper by using


the component palette.
Select View > Component Palette to enable the
palette in the integrated development environment
(IDE).

Copyright 2004, Oracle. All rights reserved.

Registering Tag Libraries

To add a tag library to the component palette, perform


the following:
1. Select Tools > Configure Palette.
2. Add a new palette page.
3. Name the page for display.

9-11

Copyright 2004, Oracle. All rights reserved.

Registering Tag Libraries

4. Select Tools > Manage Libraries.


5. Add the JAR and TLD files to the list of JSP Tag
Libraries.

9-12

Copyright 2004, Oracle. All rights reserved.

Registering Tag Libraries

9-13

Copyright 2004, Oracle. All rights reserved.

Using Tag Insight

9-14

Copyright 2004, Oracle. All rights reserved.

JSP Standard Tag Library (JSTL)

The JSP Standard Tag Library (JSTL) was developed


under the Java Community Process. It provides a
common and standard set of custom tags for:
Iteration, conditional processing, and expression
language support
Parsing and transforming XML documents
Formatting and parsing strings, dates, and
currencies for internationalization
Database access and data manipulation

9-15

Copyright 2004, Oracle. All rights reserved.

Core Tag Library


The Core library of JSTL is used for typical JSP
actions.
Reduces the need for scriptlet tags in a JSP
Contains four types of tags:
Generic (sets variables and display results of
expressions)
Conditional (makes blocks of code dependent on
some criteria)
Iteration (repeats actions on blocks of code)
URL-related (creates URLs for linking or redirection)

Use the prefix "c" in the taglib directive:


<%@ taglib uri="http://java.sun.com/jstl/core"
prefix="c" %>
9-16

Copyright 2004, Oracle. All rights reserved.

9-17

Copyright 2004, Oracle. All rights reserved.

Utilizing Core Tags

Use the <c:out> and <c:set> tags within your


JSP to display and create variables. The value
attribute defines what will be displayed or created
as a variable:
<c:out value="Hello World" />
<c:set var="name" value="${param.username}"
scope="session" />
Welcome <c:out value="${name}"
default="guest" />

9-18

The value attribute of the <c:set> tag uses


Expression Language (EL).

Copyright 2004, Oracle. All rights reserved.

Expression Language

JSTL tags can contain Expression Language (EL)


within attributes. Expression Language:
Is a simpler way of writing an expression in JSPs
Accesses object properties and collection
elements using dot notation
Has access to implicit objects
Uses a dollar sign and braces to create an
expression: ${expression}
<c:set var="name" value="${param.username}"
scope="session" />
Welcome <c:out value="${name}"
default="guest" />
9-19

Copyright 2004, Oracle. All rights reserved.

Using Iteration Tags

Use iteration tags to iterate over blocks of code:

<table>
<tr>
<c:forEach var="allparams" items="${param}" >
<c:out value="${allparams.key}" />
</c:forEach><tr>
<table>

9-20

Copyright 2004, Oracle. All rights reserved.

Using the URL Tags

The following three tags exist for working with URLs:


<c:import>: Accesses resources by specifying a
URL. It is preferred over the <jsp:include>
directive, because <c:import> can:
Access URLs that exist outside the same context as
the current pages Web application context
Access a relative URL with a foreign Web
application context
Include FTP resources

9-21

<c:url>: Handles encoding and rewriting of URLs


<c:redirect>: Redirects the client request

Copyright 2004, Oracle. All rights reserved.

9-22

Copyright 2004, Oracle. All rights reserved.

XML Tag Library

The XML tag library is used to parse and transform


XML documents.
XML tags in JSTL conform to XPath syntax.
XML tags include <x:out>, <x:set>, and other
tags similar to the core tag library, in addition to:
<x:parse> : Parses a specified XML document
<x:transform> : Creates a formatted page from an
XML source document by using an XSLT stylesheet
<x:param> : Sets transformation parameters
(nested in <x:transform>)

Use the prefix "x" in the taglib directive:


<%@ taglib uri="http://java.sun.com/jstl/xml"
prefix="x" %>
9-23

Copyright 2004, Oracle. All rights reserved.

SQL Tag Library

The SQL Tag Library contains tags for testing


database applications.
Only used for prototyping or low-volume
applications
Use the prefix sql in the taglib directive:
<%@ taglib uri="http://java.sun.com/jstl/sql"
prefix="sql" %>

9-24

Copyright 2004, Oracle. All rights reserved.

Accessing a Database with SQL Tags

To access a database from the SQL tags, you can


either:
Reference a defined J2EE data source by name in
the <sql:query> or <sql:update> tags
Or
Create a data source by using a
<sql:setDataSource> tag:
<sql:setDataSource
driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:ORCL"
user="oe" password="oe" var="myDS" />

9-25

Copyright 2004, Oracle. All rights reserved.

Querying Using SQL Tags

<sql:query datasource="jdbc/oeCoreDS"
var="customers" maxRows="10">
SELECT * FROM customers
</sql:query>
<table>
<c:forEach var="row"
items="${customers.rowsByIndex}">
<tr><c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>

9-26

Copyright 2004, Oracle. All rights reserved.

Inserting, Updating, and Deleting Data

Use the <sql:update> tag to insert, update, or delete


data. For example:

<sql:update var="rows">
UPDATE customers SET account_mgr_id=147
WHERE account_mgr_id=149
</sql:update>
<c:out value="${rows}"/> Rows Updated.

9-27

Copyright 2004, Oracle. All rights reserved.

Formatting Tags

Formatting Tags are used to specify how numbers,


dates, and times, should be formatted and parsed in a
locale-sensitive manner.
It is also called "i18n" tags.
Use either java.util.ResourceBundle
or java.util.Locale to format data.
Use the prefix fmt in the taglib directive:
<%@ taglib uri="http://java.sun.com/jstl/fmt"
prefix="fmt" %>

9-28

Copyright 2004, Oracle. All rights reserved.

Internationalization Concepts

There are three main considerations for


internationalizing an application:
Locale (geographical or political region)
Resource bundle (set of paired messages and
keys)
Basename (identifier for a resource bundle)

9-29

Copyright 2004, Oracle. All rights reserved.

Internationalizing Strings

To look up a message in a resource bundle, using


the current locale, specify the key attribute in the
<fmt:message> tag:
<fmt:message key="Hello" />

Alternatively, specify the basename to use with


the <fmt:bundle> tag:
<fmt:bundle basename="login">
<fmt:message key="Hello" />
</fmt:bundle>

9-30

Copyright 2004, Oracle. All rights reserved.

Formatting Numbers and Dates

There are several formatting tags for working with


numbers and dates, including:
<fmt:formatNumber>: Specify how a
percentage, currency, or number should appear
using patterns and locales
<fmt:formatDate>: Specify how a date and/or
time should appear using patterns, locales, and
time zones
<fmt:formatNumber type="percent"
value=".547" pattern="#.###" />

9-31

Copyright 2004, Oracle. All rights reserved.

9-32

Copyright 2004, Oracle. All rights reserved.

Formatting Numbers and Dates

To reverse the formatting that is executed by the


format tags, use the following tags:
<fmt:parseNumber>: Parses a number into a
currency, percent, or number
<fmt:parseDate>: Parses a date in a customized
or a locale-specific manner
Specify the way the date string should be formatted
by using the pattern or parseLocale attributes.

9-33

Copyright 2004, Oracle. All rights reserved.

Transforming XML Documents

XML uses XSLT stylesheets to transform data. You can


accomplish the same by using the <x:transform>
tag:

<c:import url="Customers.xml" var="xml"/>


<c:import url="customerDisplay.xsl"
var="MyStyleSheet" />
<x:transform xml="${xml}"
xslt="${MyStylesheet}" />

9-34

Copyright 2004, Oracle. All rights reserved.

JSTL in JDeveloper

9-35

JDeveloper includes all four


libraries of the JSP Standard Tag
Libraries in the Component
Palette.

The Design editor resolves the


output of the tag, as with any
other JSP element.

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Develop custom tags for use in JSP applications
Add custom tag libraries to the Component Palette
Use the JSTL custom tag libraries in JSP
applications

9-36

Copyright 2004, Oracle. All rights reserved.

Practice 9-1: Overview

This practice covers creating a JSP that uses the JSTL


custom tag library.

9-37

Copyright 2004, Oracle. All rights reserved.

Communicating in J2EE

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe Remote Method Invocation (RMI)
Define the role of RMI in Java 2, Enterprise Edition
(J2EE) applications
Describe Java Naming and Directory Interface
(JNDI)
Define the role of JNDI in J2EE applications
Write code to look up a Java object by a JNDI
name

10-2

Copyright 2004, Oracle. All rights reserved.

Overview of RMI
Remote Method Invocation (RMI) is a framework for
executing distributed objects in Java. RMI has the
following characteristics:
It uses RPC-like communication mechanisms.
It is designed for client applications to invoke
remote object methods, as easily as calling local
methods.
It comprises the following components:

10-3

Remote interface
Implementation class
Server application/class
Client application/class
Stub (proxy) and skeleton classes
Copyright 2004, Oracle. All rights reserved.

Role of RMI in J2EE

Distributed components or objects in J2EE are


implemented as Enterprise JavaBeans (EJB).
Oracle Application Server 10g Containers for J2EE
(OC4J) uses a custom form of the RMI wire
protocol known as ORMI. The J2EE 1.3
specification requires support for the RMI-IIOP
protocol as the type of communication used
between the client and server object.
EJBs have a remote interface and implementation
classes, which conform to RMI semantics:
They implement a remote interface.
Methods throw the java.rmi.RemoteException.
Object parameters or return values must be
serializable.

10-4

Copyright 2004, Oracle. All rights reserved.

Communication in a J2EE Environment

J2EE server
Naming

1
3

Creation

4 Client

5
Interface

Marshaled data
Skeleton

Stub
Local call

Marshaled data
7

6
Interface

Network protocol
(Java RMI)

10-5

Copyright 2004, Oracle. All rights reserved.

Server
object

How Clients Locate a Distributed


Component
In J2EE, a distributed component is bound to a name
when deployed.
The server object run-time environment provides a
naming service to help locate an object by a name:
In RMI, the RMI registry performs this task.
In J2EE, the container typically provides this
service.

10-6

Clients use the Java Naming and Directory


Interface (JNDI) API to locate a remote object by a
name.

Copyright 2004, Oracle. All rights reserved.

Java Naming and Directory


Interface (JNDI)
What is JNDI?
JNDI is a standard API that provides access to the
directory and naming functionality.
The JNDI Service Provider Interface (SPI)
implementation provides the mapping between the
naming servers and the JNDI APIs.
JNDI API
Client
JNDI SPI
RMI registry

COS Naming LDAP

Name and directory services


10-7

Copyright 2004, Oracle. All rights reserved.

J2EE Container and JNDI Interface

10-8

The container implements the J2EE environment


and makes the services and resources available
through a JNDI interface.
The JNDI service obtains names from the
Extensible Markup Language (XML) files and holds
them in memory.
JNDI allows developers to write application code
that is independent of vendor-specific underlying
protocols, connections, and other resources.
The JNDI interface provides a common naming
convention to access J2EE resources.

Copyright 2004, Oracle. All rights reserved.

Naming Service

A naming service allows clients or objects to locate


each other in a network by:
Storing objects published against their names,
known as binding a name to an object
Maintaining a mapping of logical names to actual
names of hierarchical objects
Using a directory service with a hierarchical
structure to maintain logical names for its data
Examples: Java Naming and Directory Interface (JNDI),
RMI registry, Lightweight Directory Access Protocol
(LDAP), CORBA naming service (COS Naming)

10-9

Copyright 2004, Oracle. All rights reserved.

JNDI Terminology
JNDI client

Initial context

ormi://host/AppCtx
Namespace

Context
env

jdbc
Atomic
names

Sub-context

OracleDS oeCoreDS

ejb

Employee

Cart

Binding
Objects

java:comp/env/jdbc/OracleDS
10-10

Compound name

Copyright 2004, Oracle. All rights reserved.

Main JNDI Class and Interface

The javax.naming.InitialContext class:


Is used to obtain the initial context for JNDI lookup
operations
Returns a reference to the object implementing the
java.naming.Context interface

The javax.naming.Context interface:


Provides methods to bind names to objects
Provides methods to create subcontexts
Provides methods to navigate the JNDI name
hierarchy
Looks up an object by a name that is relative to the
initial context or a subcontext

10-11

Copyright 2004, Oracle. All rights reserved.

Accessing an Object in JNDI Namespace

A client must perform the following steps to retrieve a


local object reference from the JNDI namespace:
1. Get the JNDI InitialContext object. Example:
Context ic = new InitialContext();

2. Form the URL for the bean home interface and call
the lookup() method to get the reference to the
local home interface object. Example:
DepartmentLocalHome home =
(DepartmentLocalHome) ic.lookup(
"java:comp/env/ejb/Dept");

10-12

lookup() returns an Object type that should be


cast to a desired type.

Copyright 2004, Oracle. All rights reserved.

Getting the JNDI InitialContext

When OC4J starts, a JNDI context is constructed


for each application deployed in the server.
An initial context obtained by the client is used to
access the subcontexts and objects.
Clients accessing objects in a remote OC4J
container typically require a set of environment
properties to obtain the InitialContext:

10-13

INITIAL_CONTEXT_FACTORY
PROVIDER_URL
SECURITY_PRINCIPAL
SECURITY_CREDENTIAL
dedicated.rmicontext
Copyright 2004, Oracle. All rights reserved.

Getting the JNDI InitialContext

Set environment properties for initial context in:


The system properties, set either by the OC4J
server or by the application container
A jndi.properties file contained in the
application EAR file, as part of the applicationclient.jar file
An environment specified explicitly in a Hashtable

The JNDI InitialContext has two constructors:


A no-arg constructor used by local clients to
execute code in the same J2EE container
A constructor with a Hashtable argument used by
remote clients to execute code in a remote J2EE
container

10-14

Copyright 2004, Oracle. All rights reserved.

Initial Context Factories

There are three JNDI initial context factories:


ApplicationClientInitialContextFactory
ApplicationInitialContextFactory
RMIInitialContextFactory

10-15

An initial context factory is used to construct an


InitialContext object.

The initial context factory class name is the string


value for the INITIAL_CONTEXT_FACTORY JNDI
property.

Copyright 2004, Oracle. All rights reserved.

lookup() Method

The lookup() method obtains a reference to the


required resource.
To reference a local resource, pass the URL with
the object name as parameter:
java:comp/env/subContext/resourceName
Examples:
java:comp/env/ejb/Dept
jdbc/oeCoreDS

Retrieve a reference to target EJB by using:


The actual bean name specified in the <ejb-name>
element or the <ejb-ref-name> element of ejbjar.xml
The logical bean name specified in the <ejb-refname> element of application-client.xml

10-16

Copyright 2004, Oracle. All rights reserved.

Obtaining a Reference to a Local Resource

Using the default InitialContext:


1. Obtain InitialContext:
Context ic = new InitialContext();
2. Obtain reference to a resource using lookup():
An EJB client referencing another local EJB
Object obj =
ic.lookup("java:comp/env/ejb/Dept");
An EJB client referencing a data source
Object obj = ic.lookup("jdbc/oeCoreDS");

3. Cast reference obtained from lookup():


DepartmentLocalHome dlh =
(DepartmentLocalHome) obj;
DataSource ds = (DataSource) obj;
10-17

Copyright 2004, Oracle. All rights reserved.

Obtaining a Reference to a
Remote Resource
Use initial context with appropriate JNDI properties:
1. Set JNDI properties for application:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY
, ...);
2. Obtain the InitialContext:
Context ic = new InitialContext(env);
3. Obtain a reference to a resource by using
lookup():
Object obj = ic.lookup("Dept");
4. Cast the reference to the returned Object type:
DepartmentHome dh = (DepartmentHome)
PortableRemoteObject.narrow(obj,
DepartmentHome.class);
10-18

Copyright 2004, Oracle. All rights reserved.

Setting JNDI Environment Properties

Do not set JNDI properties if:


The client exists in the same application as the
target
The target exists in the parent application of the
client

Setting JNDI properties:


Supply the properties through the
jndi.properties file. The path of the file must be
in the CLASSPATH, or JAVA_HOME/lib.
Supply properties in the client code by using a
Hashtable.

10-19

Copyright 2004, Oracle. All rights reserved.

Setting JNDI Environment Properties

Using the jndi.properties file:

Factory: Initial context factory to be used


java.naming.factory.initial =
com.evermind.server.
ApplicationClientInitialContextFactory

Location: URL used to look up the objects


java.naming.provider.url =
ormi://<hostname>:23891/<application-name>

Security: Valid credentials of the client to this


container
java.naming.security.principal=<username>
java.naming.security.credentials=<password>

10-20

Copyright 2004, Oracle. All rights reserved.

10-21

Copyright 2004, Oracle. All rights reserved.

Setting JNDI Environment Properties

Specify the JNDI properties in the client code by:


Using jndi.properties
Declaring properties in a Hashtable and passing
them to the InitialContext constructor
Hashtable env = new Hashtable();
env.put(Context.PROVIDER_URL,
"ormi://myhost/J2EECourse");
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.evermind.server.
ApplicationClientInitialContextFactory");
env.put(Context.SECURITY_PRINCIPAL, "guest");
env.put(Context.SECURITY_CREDENTIALS, "welcome");
Context ic = new InitialContext (env);
10-22

Copyright 2004, Oracle. All rights reserved.

Using RMI over HTTP Tunneling

OC4J supports tunneling of RMI over HTTP or HTTP-S.


Allows clients to communicate with remote
objects through a firewall
Makes the connection appear as if it is stateful
Clients use RMI over HTTP in JNDI requests by
prefixing PROVIDER_URL with http: as in the
following example:
Hashtable env = new Hashtable();
env.put(Context.PROVIDER_URL,
"http:ormi://<host>:<port>/Application");

10-23

Port used is the HTTP server port (by default 80)

Copyright 2004, Oracle. All rights reserved.

Using Environment References with JNDI

An environment reference is:


A static element accessible to applications at run
time
Defined as:
An environment variable
A resource manager (JDBC data source, JMS
services, or a URL)
An EJB reference (logical name for the EJB)

Bound in JNDI namespace at deployment time


Defined in the J2EE deployment descriptors
Mapped through OC4J-specific descriptor

10-24

Referenced by using the JNDI lookup() method


of an InitialContext
Copyright 2004, Oracle. All rights reserved.

Configuring Environment Variables

Environment variables are defined in the <enventry> section of the deployment descriptor (DD).
One entry for each variable; case-sensitive
Types can be the following classes: String, Integer,
Boolean, Double, Byte, Short, Long, or Float
<env-entry>

Deployment Descriptor

<env-entry-name>minBalance</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>500</env-entry-value>
</env-entry>
InitialContext ic = new InitialContext();
Integer minBal = (Integer)
ic.lookup("java:comp/env/minBalance");
10-25

Copyright 2004, Oracle. All rights reserved.

Client

Configuring Environment Variables

The J2EE name can be mapped to a different value


in the OC4J-specific deployment descriptor (DD).
The OC4J-specific DD overrides the value in the
J2EE deployment descriptor.
J2EE DD

<env-entry>
<env-entry-name>minBalance</env-entry-name>

<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>500</env-entry-value>
</env-entry>
<env-entry-mapping
name="minBalance">300
</env-entry-mapping>

10-26

Copyright 2004, Oracle. All rights reserved.

OC4J DD

Specifying an EJB Reference

Specify an EJB reference by using an <ejb-ref>


element in a J2EE client application deployment
descriptor:
<ejb-ref>
<ejb-ref-name>Employee</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>businesstier.EmployeeHome</home>
<remote> businesstier.Employee</remote>
</ejb-ref>

10-27

A logical name in an <ejb-ref-name> element must


be mapped to a JNDI name in an <ejb-name>
element of an EJB deployment descriptor.
The server side receives the JNDI name and resolves
it in its JNDI tree.
Copyright 2004, Oracle. All rights reserved.

Configuring EJB References

The <ejb-ref> element of a client J2EE


deployment descriptor can provide:
The actual name of the bean in <ejb-ref-name>
A logical name of the bean in <ejb-ref-name> and
the actual name in <ejb-link>
The logical name of the bean in <ejb-ref-name>,
to be mapped to the actual name of the bean in the
<ejb-ref-mapping> element in the OC4J-specific
deployment descriptor

Other elements of the EJB reference are:


Type: Session or entity bean
Home/LocalHome: Qualified home interface name
Remote/Local: Qualified remote/local interface
name

10-28

Copyright 2004, Oracle. All rights reserved.

Configuring Data Source References

10-29

Create an environment reference to each data


source that is used by a client through a JNDI
reference.
These references can be used only by the J2EE
application that defines these data sources.
The JNDI name is defined in the ejb-location
attribute of a <data-source> element in the
data-sources.xml file.
The J2EE deployment descriptor can use either
the JNDI name or a logical name.
A logical name must be mapped to the JNDI name
in the OC4J-specific deployment descriptor.
Copyright 2004, Oracle. All rights reserved.

Configuring Data Source References


1. Define in data-sources.xml.
<data-sources>
<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"
location="jdbc/OracleCoreDS" ...
ejb-location="jdbc/OracleDS" ... />
</data-sources>
2. Reference in J2EE Deployment Descriptor.
<resource-ref>
<res-ref-name>jdbc/oeCoreDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Application</res-auth>
<resource-ref>

JNDI Name

3. Map in OC4J-specific deployment descriptor.


<resource-ref-mapping
Logical Name
name="jdbc/oeCoreDB"
location= "jdbc/OracleDS" />
10-30

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe Remote Method Invocation (RMI)
Recognize the role of RMI in a J2EE environment
Explain the concepts of JNDI
Access an EJB or a data source object by using
JNDI techniques
Configure the JNDI names and environment
properties, such as environment variables, EJB
references, and data sources

10-31

Copyright 2004, Oracle. All rights reserved.

Practice 10-1: Overview

This practice covers the following topics:


Creating a JSP Java client to connect to and
invoke a remote Hello World EJB (the EJB is
provided) by using the ORMI protocol
Creating a stand-alone client to obtain a reference
to an EJB and JDBC data source

10-32

Copyright 2004, Oracle. All rights reserved.

Creating the Business Tier:


Enterprise JavaBeans

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define an Enterprise JavaBean
Describe the Enterprise JavaBeans (EJB)
architecture
Describe the types of EJBs and when they
are used
Explain EJB interfaces
Define the steps to deploy an EJB to Oracle
Application Server 10g

11-2

Copyright 2004, Oracle. All rights reserved.

Enterprise JavaBeans (EJB)

Enterprise JavaBeans are portable components,


which:
Enable faster application development
Allow reuse of business components
Encapsulate business logic that can be invoked
by clients
Execute in a container that provides services such
as support for transactions, persistence, and
access control for the beans

11-3

Copyright 2004, Oracle. All rights reserved.

When to Use EJBs

When developing a J2EE application, decide whether


to use EJBs based on the following requirements:
The applications are complex and would benefit
from the system-level services that are provided
by an EJB container.
The applications must be portable and scalable.
The applications must be accessed by different
types of clients.

11-4

Copyright 2004, Oracle. All rights reserved.

Types of EJBs

11-5

EJB Type

Purpose

Session Beans

Performs a task for a client

Entity Beans

Represents a business object


that exists in a database

Message-Driven Beans

Receives asynchronous Java


Message Service (JMS)
messages

Copyright 2004, Oracle. All rights reserved.

Session Beans
Session beans invoke methods for a single client.
There are two types of session beans:
Stateless Session Beans (SLSBs)
Conversation that spans a single method call
Single request business processes that do not
maintain client-specific state

Stateful Session Beans (SFSBs)


Conversation with one client that may invoke many
methods
Business processes that span multiple method
requests, thus maintaining state
EJB container
Pool of SLSBs

11-6

EJB container
SFSBs

Client 1

Client 1

Client 2

Client 2

Copyright 2004, Oracle. All rights reserved.

Entity Beans
Entity beans represent a business object in the
database. They are:
Sharable across multiple clients
Uniquely identifiable through a primary key
Persistentthe state survives an EJB server crash
There are two types of persistence in entity EJBs:
Container-managed persistence (CMP) beans:
The state of the bean is maintained by the
container.
The bean developer specifies the persistent fields.

Bean-managed persistence (BMP) beans:


The state of the bean is maintained by the bean
itself.
The bean developer writes the logic to manage
persistence by using Java Database Connectivity
(JDBC).

11-7

Copyright 2004, Oracle. All rights reserved.

Message-Driven Beans

Provide a facility for asynchronous


communication
Exist within a pool, and receive and process
incoming messages from a JMS queue or topic
Are invoked by the container to handle each
incoming message from the queue or topic
Are similar to stateless session beans
JMS queue

EJB container

Clients
Pool of MDBs

11-8

Copyright 2004, Oracle. All rights reserved.

EJB Architecture
EJB server
EJB container
Home/local
home
interface

Home/
local home
object

EJB client
Remote/
local
interface

Deployment
descriptor

11-9

EJB
Class

Remote/
local
object

Enterprise Services
Naming, Transaction, Security,
Messaging

Copyright 2004, Oracle. All rights reserved.

Database

EJB Server

Manages the EJB container


Provides a deployment and execution platform for
EJB components
Provides system services to containers that in
turn provide services to beans:
Transaction services
JNDI naming services

11-10

Can provide vendor-specific features such as


connection pooling

Copyright 2004, Oracle. All rights reserved.

EJB Container

Manages the life cycle of the enterprise beans


Isolates the enterprise beans from direct access
by client applications
Makes required services available to the EJB
classes through well-defined interfaces
EJB container
Home/local
home
interface

home/local
home
object

Remote/
local
interface

remote/
local
object

Client

11-11

EJB
class

Copyright 2004, Oracle. All rights reserved.

Container
generated

Services Provided by the EJB Container

11-12

Life-cycle management
Bean instance pooling
Client state management
Database connection pooling
Declarative transaction management
Security
Persistence

Copyright 2004, Oracle. All rights reserved.

EJB Client
An EJB client is a stand-alone application, servlet,
JSP, or another EJB that accesses the bean.
It can be a:
Local client:
Resides within the same Java virtual machine (JVM)
as the bean
Passes arguments by reference to the bean
Interacts with the EJB through methods defined in
the local interface

Remote client:
Is location independent
Passes arguments by value to the bean
Interacts with the EJB through methods defined in
the remote interface

11-13

Copyright 2004, Oracle. All rights reserved.

EJB Interfaces and Classes

Interfaces:
Remote interface/Local interface
Home interface/Local home interface

Classes:
Bean class
Primary key class (entity beans)

11-14

Copyright 2004, Oracle. All rights reserved.

Remote Interface and Remote Object

Remote interface:
Extends the javax.ejb.EJBObject interface that
extends the java.rmi.Remote interface
Describes the client view of an EJB
Declares the business methods that are accessible
to remote clients

EJB object:
Is a container-generated implementation of a
remote interface
Is a reference object that a client receives
Delegates the method calls to a bean class after
doing some infrastructure work

11-15

The remote interface and remote object are used


by session and entity beans.
Copyright 2004, Oracle. All rights reserved.

Home Interface and Home Object

Home interface:
Extends the javax.ejb.EJBHome interface that
extends the java.rmi.Remote interface
Contains the life-cycle methods for creating,
removing, and locating the instances of a bean
class
Contains home methods
Are accessed by remote clients

Home object:
Is a container-generated implementation of the
home interface
Uses callback methods on a bean class to perform
its functions

11-16

Copyright 2004, Oracle. All rights reserved.

Local Interface and Local Home Interface

Local interface:
Extends the javax.ejb.EJBLocalObject interface
Declares the business methods of the bean that are
accessible by a local client
Improves performance because the bean resides in
the same JVM, and parameters are passed by
reference

Local home interface:


Extends the javax.ejb.EJBLocalHome interface
Defines the life-cycle methods that are accessible
by local clients

11-17

These interfaces are used by session and entity


beans.
They enable relationships between entity beans.
Copyright 2004, Oracle. All rights reserved.

EJB Bean Class

A bean class extends


javax.ejb.EnterpriseBean.

A session/entity bean class:


Implements javax.ejb.SessionBean /
javax.ejb.EntityBean
Implements business/life-cycle methods
Contains methods to support container callbacks
Contains methods to set and unset the context of
the bean

A message-driven bean class:


Implements javax.ejb.MessageDrivenBean
Must implement the MessageListener interface
Contains business logic in the onMessage()
method

11-18

Copyright 2004, Oracle. All rights reserved.

The EJB Deployment Process


Home interface
Remote interface
Bean class
Other classes

Deployment
descriptor

Developers
responsibility
Component deployers
responsibility
Jar
command/
tool

EJB
JAR

Deployment
tools/
commands

Deployed EJB in the


Server

JNDI

11-19

Copyright 2004, Oracle. All rights reserved.

ejb-jar.xml File
<ejb-jar>
<enterprise-beans>
<session>|<entity>|<message-driven>
<description>Say Hello</description>
<display-name>HelloWorld</display-name>
<ejb-name>HelloWorld</ejb-name>
<home>lesson11.HelloWorldHome</home>
<remote>lesson11.HelloWorld</remote>
<ejb-class>lesson11.impl.HelloWorldBean</ejb-class>
</session>|</entity>|</message-driven>
</enterprise-beans>
<assembly-descriptor>
<security-role> </security-role>
<method-permission> </method-permission>
<container-transaction> </container-transaction>
</assembly-descriptor>
</ejb-jar>

11-20

Copyright 2004, Oracle. All rights reserved.

orion-ejb-jar.xml File

Oracle Application Server 10g uses the orion-ejbjar.xml file for deployment. This file:

11-21

Specifies run-time attributes of the bean for


deployment to the container
Enables customization of the run-time behavior of
enterprise beans

Copyright 2004, Oracle. All rights reserved.

Creating an EJB in JDeveloper

11-22

Copyright 2004, Oracle. All rights reserved.

Using the EJB Wizard

11-23

Copyright 2004, Oracle. All rights reserved.

Using the EJB Wizard

11-24

Copyright 2004, Oracle. All rights reserved.

Adding Methods to the Bean

To add methods to the bean, right-click and select Go


To Bean Class:

11-25

Copyright 2004, Oracle. All rights reserved.

Deploying to Oracle Application Server


10g from JDeveloper

11-26

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Define an EJB
Describe the EJB architecture
Describe the types of EJBs and when they are
used
Explain EJB interfaces
Define the steps to deploy an EJB to Oracle
Application Server 10g

11-27

Copyright 2004, Oracle. All rights reserved.

Practice 11-1: Overview

This practice covers the following topics:


Creating an EJB in JDeveloper
Testing an EJB

11-28

Copyright 2004, Oracle. All rights reserved.

11-29

Copyright 2004, Oracle. All rights reserved.

11-30

Copyright 2004, Oracle. All rights reserved.

Implementing Business Tasks with


Session EJBs

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe session beans
Differentiate stateless session beans from stateful
session beans
Develop a home interface, a remote interface, and
a bean class for session beans
Develop a client application to invoke the
business methods

12-2

Copyright 2004, Oracle. All rights reserved.

Session Beans

A session bean:
Implements business processes
Is short-lived and has the lifetime of a clients
session
Does not survive server, machine, or network
crashes
Is not saved in permanent storage
Implements the javax.ejb.SessionBean
interface

12-3

Copyright 2004, Oracle. All rights reserved.

javax.ejb.SessionBean Interface

The SessionBean interface contains the following


callback methods:
setSessionContext(SessionContext ctx)
ejbActivate()
ejbPassivate()
ejbRemove()

12-4

Copyright 2004, Oracle. All rights reserved.

Types of Session Beans

There are two types of session beans:


Stateless session bean: A stateless session bean
does not maintain the state for a client.
Stateful session bean: A stateful session bean
maintains the state for a client, and the instance
variable represents the state of a unique client.

12-5

Copyright 2004, Oracle. All rights reserved.

When to Use Session Beans

The state of the bean need not be persistent.


Use stateless session beans when:
The state need not be maintained for a client
A general task must be performed
Data is fetched only from a database, and data
manipulation is not necessary

Use stateful session beans when:


Interaction between bean and client must be
maintained across method calls and transactions
A bean works on logic based on entity beans that
represent persistent data

12-6

Copyright 2004, Oracle. All rights reserved.

Life Cycle of a Stateless Session Bean

Does not
exist

Container invokes
class.newInstance,
setSessionContext(sessCtx),
and ejbCreate().

Container invokes
ejbRemove() .

Ready

12-7

Copyright 2004, Oracle. All rights reserved.

Home Interface for Stateless


Session Beans
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatelessejbHome extends
EJBHome
{
Statelessejb create() throws RemoteException,
CreateException;
}

12-8

Copyright 2004, Oracle. All rights reserved.

Remote Interface for Stateless


Session Beans
import javax.ejb.EJBObject;
import java.rmi.*;
public interface Statelessejb extends
EJBObject
{
public String incrementValue() throws
RemoteException;
public int getValue()throws RemoteException;
}

12-9

Copyright 2004, Oracle. All rights reserved.

The Session Bean Class

The class must be defined as public, must not be


final, and must not be abstract.
The class must implement ejbCreate() methods:
There must be an ejbCreate() method for each
create() method of the home interface.
The signatures of the two methods mentioned
above should match.
The return type of the ejbCreate() method
should be void.
Remote or create exceptions need not be thrown.

12-10

The class can optionally implement the


SessionSynchronization interface.
Copyright 2004, Oracle. All rights reserved.

The Session Bean Class:


Business Methods

12-11

The bean class may define zero or more methods


to process the business logic.
The business methods that are to be accessed by
the client applications must be public.
The business methods must not be declared as
final or static.
The business methods that are to be accessed by
clients must be exposed through the component
interface.
The method arguments and return types must be
legal types for RMI.
Application-specific exceptions can be thrown.
Copyright 2004, Oracle. All rights reserved.

Bean Class for the Stateless


Session Bean
...
public class StatelessejbBean implements SessionBean
{
int value =0;
public void ejbCreate() { }
public void ejbActivate() { }
public void ejbPassivate(){ }
public void ejbRemove() { }
public void setSessionContext(SessionContext ctx) { }
public String incrementValue() {
value++;
return " value incremented by 1";
}
public int getValue()
{
return value;
}
}

12-12

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor

<?xml version = '1.0' encoding = 'windows-1252'?>


<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD
Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejbjar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<description>Session Bean ( Stateless ) </description>
<display-name>statelessejb</display-name>
<ejb-name>Statelessejb</ejb-name>
<home>StatelessejbHome</home>
<remote>Statelessejb</remote>
<ejb-class>StatelessejbBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>

12-13

Copyright 2004, Oracle. All rights reserved.

Client Application
To access methods on the bean instance, an EJB
client must perform the following operations:
Obtain access to the naming service (Java Naming
and Directory Interface [JNDI]) where the beans
home interface is published
Authenticate itself with the naming service
interface
Obtain a reference to the beans home interface
from the naming service by using the beans URL
Invoke the create() method on the home
interface
Invoke business methods

12-14

Copyright 2004, Oracle. All rights reserved.

Client Application for Stateless


Session Beans
...
public class StatelessejbClient
{
public static void main(String [] args)
{
StatelessejbClient statelessejbClient = new
StatelessejbClient();
try
{Context context = getInitialContext();
StatelessejbHome statelessejbHome =
(StatelessejbHome)PortableRemoteObject.narrow
(context.lookup("Statelessejb"),
StatelessejbHome.class);
//create 3 instances
Statelessejb obj[] = new Statelessejb[3];
for (int i=0;i<3;i++)
{ obj[i]= statelessejbHome.create(); }
...

12-15

Copyright 2004, Oracle. All rights reserved.

Client Application for Stateless


Session Beans
...
// Invoke the business methods with each of the
// instances created to observe the state of each
// instance
for (int i=0;i<3;i++)
{
System.out.println("Value before increment for
object" + i + " "+ obj[i].getValue());
System.out.println( "Calling incrementValue with
object" + i+" " +obj[i].incrementValue());
System.out.println("Calling getValue with
object" + i+" " +obj[i].getValue()+"\n");
}
for (int i=0;i<3;i++)
{ obj[i].remove(); }
...

12-16

Copyright 2004, Oracle. All rights reserved.

Life Cycle of a Stateful Session Bean

Does not
exist

setSessionContext(sessCtx),
and ejbCreate()

Container invokes
ejbRemove()

ejbPassivate()

Passivated
instances

Ready

ejbActivate()

12-17

Copyright 2004, Oracle. All rights reserved.

Home Interface for Stateful Session Bean

import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatefulejbHome extends
EJBHome
{
Statefulejb create(int x) throws
RemoteException, CreateException;
}

12-18

Copyright 2004, Oracle. All rights reserved.

Client Application for Stateful


Session Bean
...
Statefulejb obj[]= new Statefulejb[3];
for (int i=0;i<3;i++)
{ obj[i]= StatefulejbHome.create(0); }
for (int i=0;i<3;i++)
{
System.out.println("Value before increment for
object" + i + " "+ obj[i].getValue());
System.out.println( "Calling incrementValue with
object" + i+" " +obj[i].incrementValue());
System.out.println("Calling getValue with
object" + i+" " +obj[i].getValue()+"\n");
}
for (int i=0;i<3;i++)
{ obj[i].remove(); }
...

12-19

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe session beans
Differentiate stateless session beans from stateful
session beans
Develop a stateless session bean
Develop a client application to invoke a stateless
session bean

12-20

Copyright 2004, Oracle. All rights reserved.

Practices 12-1 and 12-2: Overview

These practices cover the following topics:


Creating a session bean to validate a card
Creating a session bean to display the
first_name, last_name, email, and
department_name of an employee whose
employee_id is provided

12-21

Copyright 2004, Oracle. All rights reserved.

Managing Persistent Data in


the Business Tier

Entity EJBs

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Identify the features of an entity bean
Distinguish between session beans and entity
beans
Decide when to use an entity bean
Describe the various components of an entity
bean
Differentiate bean-managed persistent beans from
container-managed persistent beans

13-2

Copyright 2004, Oracle. All rights reserved.

Entity Beans

13-3

Are objects that can be stored in permanent


storage
Represent persistent data in the database
Can be uniquely identified
Do not contain complex business logic
Do not model business processes but manage
data for such processes
Can serve multiple clients simultaneously

Copyright 2004, Oracle. All rights reserved.

Representing Data in Entity Beans

int x
String s
float f
int y
double d
Entity bean object
Table

13-4

Copyright 2004, Oracle. All rights reserved.

When to Use Entity Beans

You can use an entity bean in the following situations:


To represent a business entity
When the state of the bean must be persistent
When you need to represent a relationship
between entities

13-5

Copyright 2004, Oracle. All rights reserved.

Callback Methods to Load and Store Data

13-6

ejbLoad()loads the
data from the
persistent storage to
the bean.
ejbStore()saves the
data from the bean
instance to the
persistent storage.

Copyright 2004, Oracle. All rights reserved.

Session Beans Versus Entity Beans


Session Beans:
Entity Beans:
Are represented by
Are represented by
verbs because they
nouns because they
model workflow
model business data
Are short-lived and
Are long-lived and do
have a lifetime of a
not depend on a
client session
clients session
Manage their state, but Contain callback
do not contain
methods for
callback methods to
managing data
manage data because
(create, retrieve,
they do not represent
persist, and so on) in
data in the persistent
the persistent storage
storage
13-7

Copyright 2004, Oracle. All rights reserved.

Types of Entity Beans

13-8

Container-managed persistent (CMP) beans: The


container provides the logic to search and
manipulate the persistent data.
Bean-managed persistent (BMP) beans: The bean
provider codes the logic to search and manipulate
the persistent data in the callback methods.

Copyright 2004, Oracle. All rights reserved.

BMP Beans Versus CMP Beans

BMP beans:
Contain code for managing data persistence
Provide flexibility for bean developers to manage
state
Are complicated to program

CMP beans:
Do not contain code for managing persistence
because the container manages the persistence
Use abstract persistence schema and define the
data retrieval/manipulation logic in the deployment
descriptor
Are easier to program and contain lesser code

13-9

Copyright 2004, Oracle. All rights reserved.

Components of an Entity Bean

13-10

Home interface: Is used by clients to create, find,


and destroy EJB objects
Component interface: Contains the declaration of
all business methods in the bean class that can be
invoked by the client
Bean class: Represents persistent data and
contains methods to access or manipulate that
data
Primary key class: Is used to uniquely identify an
entity bean instance
Deployment descriptor: Contains information that
is used by the container

Copyright 2004, Oracle. All rights reserved.

Creating, Removing, Finding, and


Selecting Entity Beans

13-11

ejbCreate(): Initializes the entity bean in


memory. This method may also insert the
corresponding data into the persistent storage.
ejbRemove(): Removes the database data but
does not remove the in-memory entity bean
instance. The instance may return to the pool and
release all resources in the ejbPassivate()
method.
Finder methods: Used to find an entity bean.
Selector methods: Used to select entity beans and
values of CMP fields.

Copyright 2004, Oracle. All rights reserved.

Home Interface of an Entity Bean

Remote home interface:


Extends the javax.ejb.EJBHome interface
Can be accessed by remote clients by using Java
Naming and Directory Interface (JNDI)
Allows client to create handles for later reference

Local home interface:


Extends the javax.ejb.EJBLocalHome interface
Can be accessed by local clients

Remote/local home interface:


Contains methods to create, find, or remove entity
objects
Contains business methods that are not applicable
to a specific instance (home methods)

13-12

Copyright 2004, Oracle. All rights reserved.

Creating a Bean Instance

An entity bean can have one or more create()


methods, or none defined in its home interface.
The create() method:
Enables a client to create a row in the database
table that corresponds to the entity bean
Contains parameters that initialize the state of the
created entity object
Returns the remote/local interface reference of the
entity beans
Throws CreateException and any user-defined
exceptions
Throws RemoteException if it is part of a remote
home interface

13-13

Copyright 2004, Oracle. All rights reserved.

Finding an Entity Bean Instance


An entity bean:
Can have one or more finder methods in home
interface
Must have a findByPrimaryKey(primarykey)
method
Has finder methods that:
Find row or rows in the database table
Contain parameters that locate the requested entity
object
Return entity beans component interface reference
or collection of objects of component interface type
Must throw FinderException
Must throw RemoteException in a remote home
interface
Have find as a prefix in their names
13-14

Copyright 2004, Oracle. All rights reserved.

Removing an Entity Bean

An entity bean with remote home interface:


Can have one or more remove() methods:
remove(Handle handle) and remove(Object
primarykey)
Throws RemoteException and RemoveException
from remove() methods

An entity bean with local home interface:


Can have one remove() method: remove(Object
primarykey)
Throws RemoveException from the remove()
method

13-15

remove() methods remove the entity object and


the row from the underlying database.
Copyright 2004, Oracle. All rights reserved.

Home Methods of Entity Beans

13-16

Home methods are provided by a bean provider.


Home methods contain business logic that is not
specific to any bean instance.
An entity bean can have one or more home
methods, or none.
The arguments and return types of remote home
methods should be of RMI-IIOP type.

Copyright 2004, Oracle. All rights reserved.

Component Interfaces of an Entity Bean

Component interfaces define:


Business methods that are accessible by clients
Accessor methods for the bean attributes

Remote interfaces:
Are referenced by remote clients
Extend the javax.ejb.EJBObject interface

Local interfaces:
Are referenced by local clients
Extend the javax.ejb.EJBLocalObject interface

13-17

Copyright 2004, Oracle. All rights reserved.

Primary Key Class of an Entity Bean

Primary key:
Uniquely identifies each bean instance
Is used to find or remove an entity bean
Can be of any legal value type in RMI-IIOP

The primary key class:


Should implement java.io.Serializable
Can have a single primary key (a single field) to
identify the entity bean
Can have composite keys (multiple fields) to
identify the entity bean

13-18

Copyright 2004, Oracle. All rights reserved.

Bean Class of an Entity Bean

Initializes the bean instance through the


ejbCreate() and ejbPostCreate() methods

Implements:
Finder methods through ejbFindxxx() methods
Home methods through ejbHomexxx() methods
Callback methods from the EntityBean interface
Business and private methods

13-19

Copyright 2004, Oracle. All rights reserved.

Bean Class of an Entity Bean

Contains ejbCreate() and ejbPostCreate()


methods for each create() method.
The ejbCreate() method:
Is invoked when a client invokes the create()
method to initialize persistent fields
Has primary key as return type

The ejbPostCreate() method:


Is invoked after the entity bean is created and
before any other request from a client is processed
Has void as return type
Initializes any relationship fields for an entity bean

13-20

Copyright 2004, Oracle. All rights reserved.

javax.ejb.EntityBean Interface

All entity bean classes should implement the


javax.ejb.EntityBean interface.
public interface javax.ejb.EntityBean
implements javax.ejb.EnterpriseBean
{
public void ejbActivate();
public void ejbLoad();
public void ejbPassivate();
public void ejbRemove();
public void ejbStore();
public void setEntityContext(EntityContext
ctx);
public void unSetEntityContext();
}

13-21

Copyright 2004, Oracle. All rights reserved.

Life Cycle of an Entity Bean


Does not
exist
newInstance()
setEntityContext()

unsetEntityContext()

Pooled

ejbCreate()
ejbPostCreate() ejbActivate()

ejbLoad()

ejbPassivate() ejbRemove()

Ready

ejbStore()

Clients invoke
business methods
13-22

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE >
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>...</ejb-name>
<home>...</home>
<remote>...</remote>
<ejb-class>...</ejb-class>
<persistence-type>...</persistence-type>
<prim-key-class>...</prim-key-class>
<reentrant>False</reentrant>
<abstract-schema-name>...</abstract-schema-name>
<cmp-field> <field-name>...</field-name> </cmp-field>
<primkey-field>...</primkey-field>
</entity>
</enterprise-beans>
...

13-23

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor
...
<assembly-descriptor>
<security-role>
<description>Public</description>
<role-name>PUBLIC</role-name>
</security-role>
<method-permission>
<description>Public methods</description>
<role-name>PUBLIC</role-name>
<method>
<ejb-name>...</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
</assembly-descriptor>
</ejb-jar>

13-24

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Identify features of an entity bean
Use entity beans
Distinguish between a session bean and an entity
bean
Develop components of an entity bean
Differentiate BMP beans from CMP beans
Describe the life cycle of an entity bean

13-25

Copyright 2004, Oracle. All rights reserved.

Practice 13-1: Overview

This practice reviews entity bean concepts using


paper-based questions.

13-26

Copyright 2004, Oracle. All rights reserved.

Achieving State Management in the


Business Tier

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe the features of bean-managed persistent
(BMP) entity beans
Identify the features of a container-managed
persistent (CMP) entity bean
Describe the benefits of a CMP bean as compared
with a BMP bean
Develop and deploy a CMP bean
Develop a client for a CMP bean

14-2

Copyright 2004, Oracle. All rights reserved.

Features of BMP Entity Beans

14-3

The Bean provider provides the code for


persistence management.
BMP beans provide more flexibility in managing
persistent data.
The bean class of a BMP entity bean contains
code for data access and manipulation.
Callback methods contain code to map the entity
bean instance to the data, load the data, and store
the data in persistent storage.
BMP beans are less portable.

Copyright 2004, Oracle. All rights reserved.

Developing a BMP Entity Bean

To develop a BMP entity bean, you must create the


following:
A remote interface for the bean
A home interface
The primary key class
The bean class implementation
Support classes, such as exceptions
Necessary database tables
The J2EE deployment descriptor
A client application to access the EJB

14-4

Copyright 2004, Oracle. All rights reserved.

Features of CMP Entity Beans

Developers need not code the persistence logic in


the bean because the containers provide it.
CMP beans provide:
Portability across all EJB-compliant containers
A layer of data independence
Container-managed fields, which represent the
persistent fields in the database

14-5

Bean developers concentrate on the business


logic and provide empty implementations of the
callback methods.

Copyright 2004, Oracle. All rights reserved.

Implementing Methods in CMP Beans and


BMP Beans
Method

BMP

CMP

ejbFind()
ejbcreate()
ejbLoad()
ejbStore()
setXXX() and
getXXX()

14-6

abstract

Copyright 2004, Oracle. All rights reserved.

Developing a CMP Entity Bean

To develop a CMP entity bean, you must:


Create a component interface
Create a home interface
Define a primary key for the bean
Create the bean class implementation
Create optional support classes such as
exceptions
Create the bean deployment descriptor
Ensure that the correct database table exists for
the bean

14-7

Copyright 2004, Oracle. All rights reserved.

CMP Bean: Example

14-8

The example in this lesson creates a CMP entity


bean to represent the DEPARTMENTS table with the
following components:
Remote interface: Departments
Home interface: DepartmentsHome
Bean class: DepartmentsBean
Deployment descriptor: ejb-jar.xml
Client for Departments bean:
DepartmentsClient

Copyright 2004, Oracle. All rights reserved.

Bean Class of a CMP EJB: CMP Fields

The bean class of a CMP EJB is an abstract class


because it does not implement persistence logic.
CMP fields in the deployment descriptor:
Correspond to columns of the persistent data table
Have names starting with a lowercase letter
Must be Java primitive types or Java serializable
objects

CMP field accessor methods in the bean instance:


Must be abstract public methods; the container
implements these methods
Must have names in the following form:
getFieldname()or setFieldname()

14-9

Copyright 2004, Oracle. All rights reserved.

Remote Interface: Departments

...
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Departments extends EJBObject
{
// set and get methods for CMP fields
Long getDepartment_id() throws RemoteException;
void setDepartment_id(Long newDepartment_id)
throws RemoteException;
String getDepartment_name()throws
RemoteException;
void setDepartment_name(String
newDepartment_name) throws RemoteException;
...
}

14-10

Copyright 2004, Oracle. All rights reserved.

Home Interface: DepartmentsHome

import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
public interface DepartmentsHome extends EJBHome
{
Departments create() throws RemoteException,
CreateException;
Departments findByPrimaryKey(Long primaryKey) throws
RemoteException, FinderException;
Collection findAll() throws RemoteException,
FinderException;
Departments create(Long department_id, String
department_name) throws RemoteException,
CreateException;
}

14-11

Copyright 2004, Oracle. All rights reserved.

Bean Class: DepartmentsBean


...
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
public abstract class DepartmentsBean implements
EntityBean
{ private EntityContext context;
public void setEntityContext(EntityContext
ctx)
{
context = ctx;
}
public void unsetEntityContext()
{
context = null;
}
public abstract Long getDepartment_id();
public abstract void setDepartment_id(Long
newDepartment_id);
...

14-12

Copyright 2004, Oracle. All rights reserved.

Bean Class: DepartmentsBean


...
public Long ejbCreate()
{
return null; }
public void ejbPostCreate()
{ }
public Long ejbCreate(Long department_id,
String department_name)
{
setDepartment_id(department_id);
setDepartment_name(department_name);
return department_id;
}
public void ejbPostCreate(Long department_id,
String department_name)
{
}
...

14-13

Copyright 2004, Oracle. All rights reserved.

Bean Class: DepartmentsBean

...
public void ejbActivate()
{ }
public void ejbLoad()
{ }
public void ejbPassivate()
{ }
public void ejbRemove()
{ }
public void ejbStore()
{ }
}

14-14

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor ejb-jar.xml

The main tags of the deployment descriptor for a CMP


bean are:
<prim-key-class>: Type of primary key
<persistence-type>: Container
<cmp-version>: CMP 1.1 or 2.0 (default)
<abstract-schema-name>: For each entity bean
<cmp-field><field-name>: List of CMP field
names

14-15

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor ejb-jar.xml


...
<ejb-jar>
<enterprise-beans>
<entity> <description>Entity Bean
( CMP )</description>
<display-name>Departments</display-name>
<ejb-name>Departments</ejb-name>
<home>mypackage1.DepartmentsHome</home>
<remote>mypackage1.Departments</remote>
<ejb-class>
mypackage1.impl.DepartmentsBean</ejb-class>
<persistence-type>Container</persistencetype>
<prim-key-class>java.lang.Long</prim-keyclass>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
...
14-16

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor ejb-jar.xml


<cmp-field>
<field-name>department_id</field-name>
</cmp-field>
<cmp-field>
<field-name>department_name</field-name>
</cmp-field>
<cmp-field>
<field-name>manager_id</field-name>
</cmp-field>
<cmp-field>
<field-name>location_id</field-name>
</cmp-field>
<primkey-field>department_id</primkey-field>
</entity>
</enterprise-beans>
</ejb-jar>

14-17

Copyright 2004, Oracle. All rights reserved.

Mapping CMP Fields to


Database Table Columns

Accept the defaults that are supplied by the


container.
Map explicitly to the columns in a database table
by using the orion-ejb-jar.xml file:
Deploy the application by using only ejb-jar.xml
Modify the generated orion-ejb-jar.xml file with
the custom database, table, and column details
Use for more complex data representation of a bean

14-18

JDeveloper provides easy mapping of the


persistent fields to database tables.

Copyright 2004, Oracle. All rights reserved.

Default Mapping of CMP Fields


to Database Table Columns

Database: Default database as specified in the


data-sources.xml file, which can be customized
Table: Default table is created by a container with
a unique name that combines the following:

14-19

EJB name defined in the deployment descriptor


JAR file name including .jar extension
Application name defined during deployment
An underscore and five-character hash code
Example: DeptBean_dept_jar_dept_xxxxx

Column: With the same name as the CMP fields


defined in the deployment descriptor; Java data
types are translated to database data types in
oracle.xml
Copyright 2004, Oracle. All rights reserved.

Explicit Mapping of CMP Fields


to Database Table Columns
<enterprise-beans>
<entity-deployment name="Departments"
data-source="jdbc/hrDS" table="DEPARTMENTS">
<primkey-mapping>
<cmp-field-mapping name="department_id
persistence-name="DEPARTMENT_ID"
persistence-type="NUMBER(4)"/>
</primkey-mapping>
<cmp-field-mapping name="department_id
persistence-name="DEPARTMENT_ID"
persistence-type="NUMBER(4)"/>
<cmp-field-mapping name="department_name
persistence-name="DEPARTMENT_NAME
persistence-type="VARCHAR2(30)"/>
...

14-20

Copyright 2004, Oracle. All rights reserved.

14-21

Copyright 2004, Oracle. All rights reserved.

Client for Departments Bean


import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
...
public class DepartmentsClient
{
public static void main(String [] args)
{
DepartmentsClient departmentsClient =
new DepartmentsClient();
try
{
Context context = getInitialContext();
DepartmentsHome departmentsHome =
(DepartmentsHome)PortableRemoteObject.narrow
(context.lookup("Departments"), DepartmentsHome.class);
Departments departments;
...

14-22

Copyright 2004, Oracle. All rights reserved.

Client for Departments Bean

System.out.println(" CREATING A NEW DEPARTMENT WITH


ID 404... ") ;
departments =departmentsHome.create(new Long(404),
"Security");
System.out.println(" SUCCESSFUL ");
System.out.println("Get the DEPARTMENT_NAME " +
departments.getDepartment_name());
System.out.println("Changing the DEPARTMENT_NAME to
Security Services " );
departments.setDepartment_name("Security Services");
System.out.println("PRINTING THE DEPARTMENT_ID AND
DEPARTMENT_NAME");
System.out.println(departments.getDepartment_id() +
"
" + departments.getDepartment_name());
...

14-23

Copyright 2004, Oracle. All rights reserved.

Client for Departments Bean


// Retrieve all instances using the findAll() method
Collection coll = departmentsHome.findAll();
Iterator iter = coll.iterator();
while (iter.hasNext())
{
departments = (Departments)iter.next();
System.out.println("department_id = " +
departments.getDepartment_id());
System.out.println("department_name = " +
departments.getDepartment_name());
System.out.println("manager_id = " +
departments.getManager_id());
System.out.println("location_id = " +
departments.getLocation_id());
System.out.println();
}
}
catch(Throwable ex)
{...

14-24

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the features of a BMP entity bean
List the components that have to be created to
develop a BMP bean
Describe the features of a CMP entity bean
List the steps in developing a CMP bean
Develop and deploy a CMP bean
Develop a client for CMP EJB

14-25

Copyright 2004, Oracle. All rights reserved.

Practice 14-1: Overview

This practice covers the following topics:


Developing a CMP entity bean to represent and
update the EMPLOYEES table

14-26

Creating a remote interface, and a home interface


for a CMP entity bean by using Oracle JDeveloper
10g
Implementing the create() methods, callback
methods, and methods of the remote interface in
the entity bean class
Testing the entity bean with a client application

Copyright 2004, Oracle. All rights reserved.

Container-Managed Relationships (CMRs)

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define relationships between entity beans
Determine the cardinality and direction of a
relationship
Identify various elements of the deployment
descriptor that define the relationship
Develop CMR entity beans

15-2

Copyright 2004, Oracle. All rights reserved.

Relationships

15-3

Copyright 2004, Oracle. All rights reserved.

Implementing Relationships

Data manipulation in the beans may involve a


more complex data model, with a relationship
between entity beans.
The important aspects of a relationship are:
Cardinality: Number of data instances that can
participate in a relationship

Direction: Direction in which a relationship is


navigated

15-4

Copyright 2004, Oracle. All rights reserved.

Cardinality and Direction of Relationships

Cardinality:
One-to-one
One-to-many or many-to-one
Many-to-many

Directionality:
Unidirectional
Bidirectional

15-5

Copyright 2004, Oracle. All rights reserved.

One-to-One Relationships

The phone_num column is the foreign key in the EMP


entity that is referencing the PHONE entity.

Each employee has only one phone number and


each phone number belongs to only one employee.
EMP
emp_id

name

phone_num

100

Smith

111 1111

area_code

service

650

MCI

PHONE
phone_num
111 1111

15-6

Copyright 2004, Oracle. All rights reserved.

One-to-Many Relationships
Each department exists in only one location identified
by location_id, whereas each location can contain
many departments (1:M).
LOCATIONS
location_id
1700
DEPARTMENTS
department_id

15-7

city

Seattle

department_name

location_id

10

Administration

1700

30

Purchasing

1700

Copyright 2004, Oracle. All rights reserved.

Many-to-Many Relationships
Each employee may be assigned many jobs and each
job may be assigned to many employees.
EMPLOYEES
employee_id
176

Jonathon

ASSIGNMENTS
assign_pk
A1
JOBS_HISTORY
job_id

employee_id

job_id

176

SA_REP

...

SA_REP
15-8

Name

...

Copyright 2004, Oracle. All rights reserved.

Oracle TopLink
Oracle TopLink run-time framework:
Facilitates data integration with enterprise
applications
Facilitates rapid development, deployment, and
execution of all persistence-related aspects of any
Java application
SQL
TopLink

JDBC
Rows

Java
application

15-9

Copyright 2004, Oracle. All rights reserved.

TopLink: Integration of J2EE Applications


with Data Sources at Run Time

SQL server

J2EE
Application Server

EIS

Servlets/JSPs

Oracle

EJBs
XML
Data mapping and integration
DB2
15-10

Copyright 2004, Oracle. All rights reserved.

TopLink: Integrated with Oracle


JDeveloper 10g

15-11

Copyright 2004, Oracle. All rights reserved.

Implementing Relationships

Relationship restrictions:
Define only for CMP 2.0 entity beans
Declare related CMP beans in one deployment
descriptor
Use only local interfaces to define the relationship

Define abstract get() and set() accessor


methods in the bean class for each relationship
field
In the deployment descriptor, define:
Name of each relationship
Cardinality and direction for each relationship
One section for each side of a bidirectional
relationship
Cascade delete operations on one side of the
relationship

15-12

Copyright 2004, Oracle. All rights reserved.

Defining Abstract Accessor Methods

Name:
get<cmrfieldname> and set<cmrfieldname>
Example: getDepartment(),
setEmployees(EmpLocal emp)

Return type:
Local interface of the target bean for single object
retrieval
Collection or set of local interface objects for multiple
object retrieval

Location where it is defined:


Only in the source bean for unidirectional relationship
In both beans for bidirectional relationship

15-13

Copyright 2004, Oracle. All rights reserved.

Accessor Methods in 1:1 Relationships


For bidirectional relationships, define abstract get()
and set() accessor methods for CMR fields in both
the abstract bean classes.
public abstract class Emp implements EntityBean
{
...
public abstract PhoneLocal getPhone_PhoneNo();
public abstract void setPhone_PhoneNo(PhoneLocal p);

...
public abstract class Phone implements EntityBean
{
...
public abstract EmpLocal getEmp_EmployeeID();
public abstract void setEmp_EmployeeID(EmpLocal e);
...

15-14

Copyright 2004, Oracle. All rights reserved.

Accessor Methods in 1:M Relationships


public abstract class DepartmentsBean implements
EntityBean
{
...
public abstract LocationsLocal getLocations_locationId();
public abstract void setLocations_locationId
(LocationsLocal locations_locationId);
...
public abstract class LocationsBean implements EntityBean
{
...
public abstract Collection getDepartments_locationId();
public abstract void setDepartments_locationId(Collection
departments_locationId);

...

15-15

Copyright 2004, Oracle. All rights reserved.

Checking Relationship Mappings


in JDeveloper

15-16

Copyright 2004, Oracle. All rights reserved.

Accessor Methods in M:N Relationships

public abstract class EmployeesBean implements


EntityBean
{ ...
public abstract Collection getJobHistory_employeeId();
public abstract void setJobHistory_employeeId
(Collection jobHistory_employeeId);
... }
public abstract class JobHistoryBean implements EntityBean
{ ...
public abstract Collection getEmployees_employeeId();
public abstract void setEmployees_employeeId
(Collection employees_employeeId);
... }

15-17

Copyright 2004, Oracle. All rights reserved.

Implementing a Relationship in
the Deployment Descriptor

15-18

Copyright 2004, Oracle. All rights reserved.

Implementing 1:1 Relationships


Emp to Phone
...
<relationships>
<ejb-relation>
<ejb-relation-name>EMP-PHONE</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>
Emp-has-Phone
</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>Emp</ejb-name>
</ relationship-role-source>
<cmr-field>
<cmr-field-name>Phone</cmr-field-name>
<cmr-field-type>PhoneLocal</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
...

15-19

Copyright 2004, Oracle. All rights reserved.

Implementing 1:1 Relationships


Phone to Emp
...
<ejb-relationship-role>
<ejb-relationship-role-name>
Phone-has-Emp
</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<cascade-delete />
<relationship-role-source>
<ejb-name>Phone</ejb-name>
</ relationship-role-source>
<cmr-field>
<cmr-field-name>Emp</cmr-field-name>
<cmr-field-type>EmpLocal</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships> ...

15-20

Copyright 2004, Oracle. All rights reserved.

Implementing 1:M Relationships


Departments to Locations
<relationships>
<ejb-relation>
<ejb-relation-name>Departments-Locations
</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Locations-hasdepartments_locationId
</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>Locations</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>departments_locationId
</cmr-field-name>
<cmr-field-type>java.util.Collection
</cmr-field-type>
</cmr-field>
</ejb-relationship-role>...

15-21

Copyright 2004, Oracle. All rights reserved.

Implementing 1:M Relationships


Locations to Departments
...
<ejb-relationship-role>
<ejb-relationship-role-name>Departments-owned-bylocations_locationId
</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>Departments</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>locations_locationId
</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
...

15-22

Copyright 2004, Oracle. All rights reserved.

Implementing M:N Relationships


...
<ejb-relation>
<ejb-relation-name>JobHistory Employees
</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>
JobHistory-has-employees_employeeId
</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>JobHistory</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>employees_employeeId
</cmr-field-name>
<cmr-field-type>java.util.Collection
</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
...

15-23

Copyright 2004, Oracle. All rights reserved.

Implementing M:N Relationships


<ejb-relationship-role>
<ejb-relationship-role-name>
Employees-has-jobHistory_employeeId
</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>Employees</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>jobHistory_employeeId
</cmr-field-name>
<cmr-field-type>java.util.Collection
</cmr-field-type>
</cmr-field>
</ejb-relationship-role>

15-24

Copyright 2004, Oracle. All rights reserved.

Mapping Relationship Fields to Database

15-25

Accept default mapping provided by container


(specify relationship fields in ejb-jar.xml)

Explicitly map the fields to existing table columns


in orion-ejb-jar.xml

Copyright 2004, Oracle. All rights reserved.

Default Mapping of Relationship Fields

Database: Specified in data-sources.xml

Each table in relationship: Same as for CMP entity


Columns in each table: Based on <cmr-field>,
which represents a bean in the relationship
For each <cmr-field> of an entity, the container
creates a foreign key to the primary key of the
related entity:

In the source bean table for one-to-one mapping


In a container-generated association table for oneto-many and many-to-many relationships

15-26

User-defined or automatically generated primary


key
Copyright 2004, Oracle. All rights reserved.

Explicit Mapping of Relationship Fields

1. Deploy your application with only the ejbjar.xml elements configured.


2. Copy the container-created orion-ejb-jar.xml
file to your development environment.
3. Modify the <entity-deployment> element in the
orion-ejb-jar.xml file to use the database table
and columns that you specify.
4. Rearchive and redeploy your application.

15-27

Copyright 2004, Oracle. All rights reserved.

Using JDeveloper to Create CMR Beans

Using JDeveloper, you can create a containermanaged relationship between entity beans in the
following ways:
Create CMP beans from tables and generate
default relationships between entities.
Use the EJB Module Editor to specify the
relationship or use TopLink Mapping Editor.
Create an EJB Diagram for CMP beans and
generate default relationships.

15-28

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Determine the cardinality and direction of a
relationship
Define and implement relationships between CMR
entity beans

15-29

Copyright 2004, Oracle. All rights reserved.

Practice 15: Overview

This practice covers creating a one-to-many


relationship between the Employees and
Departments entity beans.

15-30

Copyright 2004, Oracle. All rights reserved.

Developing Message-Driven Beans

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe the need for a message-oriented
middleware (MOM) type
Define Java Message Service (JMS)
Describe and create a message-driven bean (MDB)
Differentiate between a stateless session
Enterprise JavaBean and a message-driven bean
Configure JMS resource provider

16-2

Copyright 2004, Oracle. All rights reserved.

Overview of Messaging Systems

16-3

Messaging is a way for software components


and/or applications to communicate.
Messaging systems are peer-to-peer in nature.
Clients can send or receive messages from other
clients.
JMS was designed to allow applications to create,
send, and receive messages synchronously or
asynchronously.
Java Message Service allows access to existing
MOM services, such as the OC4J in-memory JMS
server.

Copyright 2004, Oracle. All rights reserved.

Types of Message Consumption

Messaging systems are inherently asynchronous, but


JMS allows messages to be consumed in two ways:
Synchronously
Receiver thread blocks until a message can be
consumed or times out.
Receiver acknowledges message receipt.
There is tightly coupled interaction.

Asynchronously
Receiver listens for messages. When a message is
delivered, the listener message handler is invoked.
Receiver thread does not block.
There is loosely coupled interaction.

16-4

Copyright 2004, Oracle. All rights reserved.

Java Message Service (JMS)

Is a J2EE standard messaging system


Can guarantee message delivery
Supports messaging across multiple platforms
Supports two models of communication
Point-to-point model
Publish-and-subscribe model
Client application
Messaging API
JMS client

16-5

MOM

Copyright 2004, Oracle. All rights reserved.

JMS client

JMS Application Architecture


The main components of a JMS application are:
JMS clients
JMS provider
Administered objects (in the Java Naming and
Directory Interface [JNDI] namespace)
Connection factories
Destinations (queues or topics)
Producer

Consumer

Application JMS

JMS Application
Queue/Topic

JMS client

16-6

JMS provider

Copyright 2004, Oracle. All rights reserved.

JMS client

Point-to-Point Model

Senders send messages to virtual destinations.


There is only one receiver for a message from a
queue.
S1

M1

Queue1

M2

M1

M2

S2

R1

R2

M3
Queue2
Messaging server
Queue sender
M* - Message

16-7

M3

Queues
(virtual destinations)

Copyright 2004, Oracle. All rights reserved.

R3

Queue receiver

Publish-and-Subscribe Model

Publishers send messages to virtual destinations.


One or more subscribers receive the messages.
M1
P1

M1

S1

Topic1
S2

P2

Topic2
M2

Topic publisher
M* - Message

16-8

M2

Messaging server

S3

Topics
(virtual destinations)

Topic subscriber

Copyright 2004, Oracle. All rights reserved.

Using JMS Interfaces

The JMS API service uses the following objects and


interfaces that are located in the javax.jms package:

JMS-administered objects:
Connection Factory: Creates connections
Destination: Target/source of messages

16-9

Connection: Creates sessions


Session: Creates a message producer or
consumer
Message Producer: Sends to a destination
Message Consumer: Receives from a destination
Message: The body of the information to be
communicated
Copyright 2004, Oracle. All rights reserved.

JMS Message Structure


JMS messages are composed of the following parts:
A header containing a common set of header
fields
Field examples: JMSMessageID and
JMSDestination
Field values are used by clients and providers for
identification and routing information.

16-10

Properties for application-defined property values,


which can be used for message filtering purposes
A body for the contents of the message, whose
contents can be structured as a StreamMessage,
MapMessage, TextMessage, ObjectMessage, or
ByteMessage
Copyright 2004, Oracle. All rights reserved.

Sending a Message to a Queue

The code steps to send a message to a JMS queue


are:
1. Connect to the naming server using JNDI.
2. Obtain a QueueConnectionFactory.
3. Obtain the name and location of Queue.
4. Open a QueueConnection and start it.
5. Create a QueueSession.
6. Create a QueueSender from the session.
7. Create the Message and set the header, body, and
properties.
8. Send the message and close resources.
16-11

Copyright 2004, Oracle. All rights reserved.

Receiving Messages

The following are the steps to receive a message from


a topic for non-MDB applications:
1. Connect to the JNDI naming service.
2. Look up for the connection factory and the source
of the message.
3. Create a TopicConnection object.
4. Create a TopicSession object.
5. Create a TopicSubscriber (or queue receiver) to
receive a message.
6. Subscribe (or receive) a message.
7. Write code to process the message contents.

16-12

Copyright 2004, Oracle. All rights reserved.

Asynchronous Message Delivery

16-13

In an asynchronous messaging model, the


consumer implements a MessageListener
interface.
The MessageListener interface declares an
onMessage() method and notifies the consumer
of the arrival of messages.
MDBs are J2EE implementations for message
listeners.
A sender is not notified when the MDB processes
the message.

Copyright 2004, Oracle. All rights reserved.

Message-Driven Beans

MDBs:
Are programmed for receiving and processing
asynchronous messages through the JMS
Destination
Are stateless, server-side, transaction-aware
components
Are not accessible directly by any client
Do not contain home and component interfaces
Are triggered by a container when a message
arrives
Implement the javax.ejb.MessageDrivenBean
and javax.jms.MessageListener interfaces
16-14

Copyright 2004, Oracle. All rights reserved.

MDB Architecture

OC4J

Client

JMS resource
provider
MDB
Queue/Topic

16-15

Copyright 2004, Oracle. All rights reserved.

Associating JMS Resources with an MDB

Use the J2EE and OC4J deployment descriptors to


specify the JMS resources associated with an MDB.
ejb-jar.xml:
<message-driven> ...
<ejb-name>MessageProcessor</ejb-name> ...
<message-driven-destination>
<destination-type>javax.jms.Queue</destination-type>
</message-driven-destination>
</message-driven>

orion-ejb-jar.xml:
<enterprise-beans>
<message-driven-deployment max-instances="-1"
name="MessageProcessor" connection-factorylocation="jms/QueueConnectionFactory" destinationlocation="jms/demoQueue" min-instances="0"/>
</enterprise-beans>

16-16

Copyright 2004, Oracle. All rights reserved.

State Diagram of an MDB

Does not exist


Container invokes
Class.newInstance,
setMessageDrivenContext(context)
and
ejbCreate()

Container invokes
ejbRemove()

Method-ready pool

Container invokes
onMessage()

16-17

Copyright 2004, Oracle. All rights reserved.

Developing MDBs

1. Configure Oracle Application Server 10g


Containers for J2EE (OC4J) with the JMS provider
details.
2. Implement the bean class.
3. Configure deployment descriptors:
a. Destination type for the bean in ejb-jar.xml
b. Connection factory and destination JNDI locations
in orion-ejb-jar.xml

4. Create the EJB JAR file that contains the bean and
the deployment descriptors.
5. Create the .ear file and deploy the bean.

16-18

Copyright 2004, Oracle. All rights reserved.

Interfaces to Be Implemented for MDBs

MessageDrivenBean interface:

package javax.ejb;
public interface MessageDrivenBean extends
javax.ejb.EnterpriseBean
{
public void setMessageDrivenContext
(MessageDrivenContext context) throws EJBException;
public void ejbRemove() throws EJBException;

MessageListener interface:

package javax.jms;
public interface MessageListener {
public void onMessage(Message message);
}

16-19

Copyright 2004, Oracle. All rights reserved.

Implementing an MDB Class

The MessageLogger MDB example:


package com.evermind.logger;
import javax.ejb.*;
import javax.jms.*;

public class MessageLogger


implements MessageDrivenBean, MessageListener {
private MessageDrivenContext messageContext;
public void ejbCreate() { }
public void ejbRemove() { }
public void setMessageDrivenContext(
MessageDrivenContext context) {
this.messageContext = context;
}

16-20

Copyright 2004, Oracle. All rights reserved.

Receiving Messages in an MDB Class

The onMessage() method processes the received


message.
public void onMessage(Message msg){
TextMessage msgText=null;
try {
msgText = (TextMessage) msg;
String txt = (msgText).getText();
System.out.println("Message received=" + txt);
}
catch (Exception e) {
throw new RuntimeException("onMessage error");
}
}

16-21

Copyright 2004, Oracle. All rights reserved.

Creating the Deployment Descriptor

MDB-related elements in the ejb-jar.xml file:


<message-driven>
<ejb-name>...</ejb-name>
<ejb-class>...</ejb-class>
<transaction-type>...</transaction-type>
<message-selector>...</message-selector>
<acknowledge-mode>...</acknowledge-mode>
<message-driven-destination>
<destination-type>...</destination-type>
</message-driven-destination>
<ejb-ref> ... </ejb-ref>
<security-identity> ... </ security-identity>
<resource-ref> ... </resource-ref>
</message-driven>
16-22

Copyright 2004, Oracle. All rights reserved.

ejb-jar.xml: Example
...
<enterprise-beans>
<message-driven>
<ejb-name>MessageLogger</ejb-name>
<ejb-class>btier.impl.MessageLogger</ejb-class>
<acknowledge-mode>Auto-acknowledge
</acknowledge-mode>
<message-driven-destination>
<destination-type> javax.jms.Queue
</destination-type>
<subscription-durability>Durable
</subscription-durability>
</message-driven-destination>
</message-driven>
...

16-23

Copyright 2004, Oracle. All rights reserved.

Mapping in OC4J-Specific
Deployment Descriptor
In the orion-ejb-jar.xml file, associate a JMS
Destination with the MDB in the <message-drivendeployment> element by using the following
attributes:
Name: MDB name as defined in the <ejb-name>
connection-factory-location: JMS
Destination Connection Factory
destination-location: JMS Destination
subscription-name: Subscription name
(required only if the JMS Destination is a topic)

16-24

Copyright 2004, Oracle. All rights reserved.

orion-ejb-jar.xml: Example

<enterprise-beans>
<message-driven-deployment
name="MessageLogger"
connection-factory-location=
"jms/QueueConnectionFactory">
destination-location=
"jms/demoQueue"
</message-driven-deployment>
...
</enterprise-beans>

16-25

Copyright 2004, Oracle. All rights reserved.

Creating an MDB with JDeveloper


2

16-26

Copyright 2004, Oracle. All rights reserved.

Creating an MDB with JDeveloper

ejb-jar.xml

16-27

Copyright 2004, Oracle. All rights reserved.

Creating an MDB with JDeveloper

Map the destination details in orion-ejb-jar.xml.

orion-ejb-jar.xml
16-28

Copyright 2004, Oracle. All rights reserved.

Testing the MDB


1. Deploy the session and the MDBs.
2. Create a client to invoke the message-sending
functionality.
3. Run the client application to send the message to
the JMS Destination.
4. Observe the output in the run-time environment.

16-29

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the different types of MOM:
Point-to-point
Publish-and-subcribe (pub/sub)

16-30

Create an MDB
Compare a stateless session EJB and an MDB
Describe JMS
Configure a JMS resource provider in the OC4J
jms.xml file

Copyright 2004, Oracle. All rights reserved.

Practice 16-1: Overview

This practice covers the following topics:


Creating a simple MDB to accept a message from
an OC4J JMS queue, and writing the message to a
log table by using an entity bean
Configuring the message-bean deployment
descriptor to use an OC4J JMS resource
Writing and configuring a JavaServer Pages (JSP)
application to send a message from an HTML form
to the OC4J JMS queue

16-31

Copyright 2004, Oracle. All rights reserved.

Integrating J2EE Components

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Create JavaServer Pages (JSP) clients for EJBs
Use Enterprise JavaBeans (EJB) tags in JSPs
Modify the configuration files in OracleAS 10g
Containers for J2EE (OC4J)

17-2

Copyright 2004, Oracle. All rights reserved.

Overview
Web tier

JSP

HttpServlet
Request

EJB tier

Controller
servlet
To EIS

HttpServlet
Response

17-3

Employees
JSP

Copyright 2004, Oracle. All rights reserved.

Employees
EJB

Creating Remote Clients for EJBs

To create a remote JSP client for an Enterprise


JavaBean, perform the following steps :
1. Import the EJB home interface.
2. Override the jspInit() method.
Use the lookup() method to create a reference to
the EJB.
Create the EJB remote object.

3. Retrieve the necessary parameters from the


request object and pass the parameters to the
EJB method.
4. Define a reference to the EJB in the web.xml file.

17-4

Copyright 2004, Oracle. All rights reserved.

Importing the EJB Home Interface

Use the page directive to import the naming package


and the home interface for the EJB:
<%@ page import="mypackage.Employees,
mypackage.EmployeesHome, javax.ejb.*,
javax.naming.*,
javax.rmi.PortableRemoteObject,
java.rmi.RemoteException" %>

17-5

Copyright 2004, Oracle. All rights reserved.

Create a Reference to the EJB

To create an EJB reference, use the lookup method.


Override the jspInit() method as follows:
<%! Employees employees = null;
public void jspInit() {
try {
InitialContext ic = new InitialContext();
EmployeesHome employeesHome = (EmployeesHome)
PortableRemoteObject.narrow
(ic.lookup("java:comp/env/Employees"),
EmployeesHome.class);
employees = employeesHome.create(); }
catch (RemoteException ex) {
ex.printStackTrace();
}
}
%>

17-6

Copyright 2004, Oracle. All rights reserved.

Passing Arguments to the EJB Method

Calling an EJB method from a JSP expression


evaluates the return value of the EJB method and
displays it, as follows:
<html><body><h1>Insert an Employee Number:</h1>
<form method="get">
<p><input type="text" name="empno">
<p><input type="Submit" value="Submit">
</form>
<% String empno = request.getParameter("empno");
if (empno != null && empno.length() >0) {
int i = Integer.parseInt(empno);%>
<%= employees.getDetails(i) %>
<% } %>
</body></html>

17-7

Copyright 2004, Oracle. All rights reserved.

Creating an EJB Reference


To obtain an EJB reference for the Web tier
components, create an <ejb-ref> element for the
EJB in the web.xml file:

17-8

Copyright 2004, Oracle. All rights reserved.

Creating Local Clients for EJBs

Creating JSP clients for local EJBs is similar to


creating remote clients, with the following exceptions:
The EJB object does not have to be cast to a
PortableRemoteObject.
Because the create() method does not throw a
RemoteException exception, this does not have
to be caught in the client.
Instead of <ejb-ref>, an <ejb-local-ref>
element is created in the client web.xml file.

17-9

Copyright 2004, Oracle. All rights reserved.

ejb-local-ref Element

Right-click web.xml to create an EJB local reference.

17-10

Copyright 2004, Oracle. All rights reserved.

EJB Tags

Oracle Application Server 10g provides a tag library


that contains custom tags for referencing EJBs in
JSPs:

17-11

EJB Tag

Purpose

useHome

Looks up the home interface for the EJB and


creates an instance of it

useBean

Instantiates the EJB

createBean

Nests an EJB createBean tag within the


useBean tag to create the EJB instance

iterate

Iterates through a collection of EJB


instances

Copyright 2004, Oracle. All rights reserved.

useHome Tag

The useHome tag has no body. The attributes are:


id (required)
type (required)
location (required)
<EJB:useHome id="empHome"
type="mypackage.EmployeesHome"
location="java:comp/env/ejb/Employees"
local="false" />

17-12

Copyright 2004, Oracle. All rights reserved.

useBean Tag

The attributes of the useBean tag include:


id (required)
type (required)
value
scope
<EJB:useBean id="bean"
type="mypackage.EmployeesBean"
scope="session" />

17-13

Copyright 2004, Oracle. All rights reserved.

createBean Tag

The createBean tag contains only one required


attribute named instance.
<EJB:useBean id="bean"
type="mypackage.EmployeesBean"
scope="session">
<EJB:createBean
instance="<%=EmployeesHome.create()%>" />
</EJB:useBean>

17-14

Copyright 2004, Oracle. All rights reserved.

iterate Tag

The following are the attributes of the iterate tag:


id (required)
type (required)
collection (required)
max
<EJB:iterate id="empdetails"
type="mypackage.Employees"
collection="<%=bean.getDetails(pk)%>"
max="100"> <jsp:getProperty name="empdetails"
property="id" /> </EJB:iterate>

17-15

Copyright 2004, Oracle. All rights reserved.

Using the EJB Tags

To use the EJB tags, perform the following steps:


1. Add the Oracle9iAS library to your project in
JDeveloper.
a. Double-click the project and select libraries.
b. Make sure that Oracle9iAS is included in your
project.

2. Use the OJSP EJB Library provided in the


component palette to add the necessary tags to
your JSP file. (This adds the bean as well as the
taglib directive to the JSP.)

17-16

Copyright 2004, Oracle. All rights reserved.

Deploying an Application: Web Tier


To deploy the Web tier components of a Java 2,
Enterprise Edition (J2EE) application, perform the
following steps:
1. Make sure that the ejb-ref or ejb-local-ref
elements exist in the web.xml file.
2. Create a WAR deployment profile (.deploy) in
JDeveloper.
3. Right-click the .deploy file and select either of
the following:
Deploy to WAR file
Deploy to OracleAS10g (where OracleAS10g is the
name of your application server connection)

17-17

Copyright 2004, Oracle. All rights reserved.

Deploying an Application: EJB Tier

1. Make sure that the ejb-jar.xml file contains


unique mappings for each EJB in the application.
2. Create a JAR deployment profile (.deploy) in
JDeveloper.
3. Right-click the .deploy file and select either of
the following:
Deploy to JAR file
Deploy to OracleAS10g

17-18

Copyright 2004, Oracle. All rights reserved.

Deploying an Application: EAR File

1. Create an EAR file in JDeveloper.


2. Specify the EJB JAR and WAR files that are to be
included in this EAR file.
3. Right-click the .deploy file and select either of
the following:
Deploy to EAR file
Deploy to OracleAS10g

17-19

Copyright 2004, Oracle. All rights reserved.

Deploying from Oracle Enterprise Manager

From the Enterprise Manager home page, click Home,


then Application, and then select Deploy EAR file:

17-20

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Create JSP clients for EJBs
Modify deployment descriptors for looking up an
EJB client
Deploy a J2EE application to Oracle Application
Server 10g

17-21

Copyright 2004, Oracle. All rights reserved.

Practice 17-1 and 17-2: Overview

These practices cover the following topics:


Creating JSP clients that access EJBs
Deploying a Web application to Oracle Application
Server 10g

17-22

Copyright 2004, Oracle. All rights reserved.

Distributing Modular Applications:


Introduction to Web Services

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe the Web services technology
Identify the standards used by Web services
Identify the benefits of Web services
Distinguish between remote procedure call (RPC)style and document-style Web services
Discuss the role of Simple Object Access Protocol
(SOAP), Web Services Description Language
(WSDL), and Universal Description, Discovery, and
Integration (UDDI) in Web services

18-2

Copyright 2004, Oracle. All rights reserved.

What Is a Web Service?

HTML

Web
presentation

HTTP client

Business
logic
XML

External
applications

18-3

Web
service

Application Server

Copyright 2004, Oracle. All rights reserved.

Databases

Web Service

A Web service is:


A software component whose technology is based
on a set of standards for building interoperable
distributed applications
A set of self-describing business functions
Service oriented
Component based

18-4

Copyright 2004, Oracle. All rights reserved.

Service-Oriented Architecture
Service
registry
Publish

Find

Service
provider

18-5

Invoke

Service
requestor

Copyright 2004, Oracle. All rights reserved.

Web Services Constituents

18-6

Internet for communication

XML as universal data format

SOAP for XML messaging

WSDL for describing the service

UDDI for publishing the Web services

Copyright 2004, Oracle. All rights reserved.

Benefits of Web Services

Distributed component model with interoperability


XML format for representing data. The request and
response messages are in the XML format.
Programming language independent
Easily accessible with standard protocols such as
HTTP, HTTPS, SMTP, and FTP
Communication through firewalls
Existing components can be exposed as
Web services to save development time.
Different communication styles:
RPC style (synchronous)
Message style (asynchronous)

18-7

Copyright 2004, Oracle. All rights reserved.

Web Services Model


Client application

2
Find

XML interface (WSDL)

Web services
directory
(UDDI)

Invoke

Publish

XML interface (WSDL)


Web service

18-8

Copyright 2004, Oracle. All rights reserved.

RPC-Style Web Services

18-9

RPC-style Web services are loosely coupled.


SOAP messages model the call and response
semantics.
This style of communication can be described in
WSDL.

Copyright 2004, Oracle. All rights reserved.

Document-Style Web Services

18-10

Document-style Web services are loosely coupled.


SOAP messages carry arbitrary XML documents.
This style of communication can be described in
WSDL.

Copyright 2004, Oracle. All rights reserved.

Oracle Support for Web Services

Oracle Application
Server 10g is the
infrastructure for:
Describing Web
services
Deploying Web
services
Publishing Web
services
Invoking Web
services

18-11

Oracle JDeveloper 10g


provides tools for:
Developing, deploying,
publishing, and
invoking Web services
Modeling, testing, and
debugging Web
services
Browsing UDDI registry
to locate Web services
Generating stub files to
consume Web services

Copyright 2004, Oracle. All rights reserved.

SOAP: XML Messaging for Web Services

Introduces a self-describing data representation


format in XML
Represents request and response as XML
messages
Supports both RPC-style and document-style
invocation
Uses HTTP and other protocols at transport layer
Supports data encoding and literal styles
SOAP hides details of implementations; works
with:
Any programming language
Any operating system
Any hardware platform

18-12

Copyright 2004, Oracle. All rights reserved.

Communication with SOAP

Communication by using SOAP protocol includes:


Requests to invoke a service
Responses from service method
Fault from a service

Request

Response
SOAP client

18-13

Firewall

Copyright 2004, Oracle. All rights reserved.

Web server

SOAP Messages

A SOAP message is an
XML document that
consists of:
A mandatory
envelope as a toplevel element
An optional header
A mandatory body

18-14

An optional fault

HTTP headers
SOAP envelope
SOAP header
Headers
SOAP body
Message name, data,
and fault element

Copyright 2004, Oracle. All rights reserved.

Web Services Description


Language (WSDL)

Is a description language to define Web service


interfaces and how to invoke them
Is an XML Schema for describing Web services:
Service interface definition: Describes what
message must be sent and what message is
returned
Service implementation definition: Describes to
which address the message must be sent

Allows both the messages and the operations on


the messages to be defined abstractly in XML
Answers three key questions about a Web service:
What does a service do?
How is a service accessed?
Where is a service located?

18-15

Copyright 2004, Oracle. All rights reserved.

WSDL
<?xml version=1.0 encoding=UTF-8 ?>
<definitions name=Hello ...
targetNamespace=http://tempuri.org/Hello.wsdl ...>
<types>
<schema targetNamespace=http://tempuri.org/Hello.xsd
...
xmlns:xsd=http://www.w3.org/2001/XMLSchema />
</types>
<message name=sayHelloOutput>... </message>
<message name=sayHelloInput> ... </message>
<portType name=HelloPortType>
<operation name=sayHello> .... </operation>
</portType>
<binding name=HelloBinding>
<operation> <input>..</input> <output>..</output>
</operation> </binding>
<service ..> <port> <soap:address location=.. />
</port>
</service>
</definitions>

18-16

Copyright 2004, Oracle. All rights reserved.

UDDI Registry

18-17

Is an online electronic registry for registering


businesses and Web services
Is a specification for description and discovery
Supports the Publishing and Inquiry APIs to
publish and inquire about a Web service

Copyright 2004, Oracle. All rights reserved.

How UDDI Is Used


Business portals and
marketplaces

UDDI Business
Registry

UDDI Registry
Business
descriptions

Business user

18-18

Service
types

Software developer

Copyright 2004, Oracle. All rights reserved.

Searching for a Web Service by


Using UDDI

Provider info
Contact Info
Directory of
names
White pages

Search using
context such as
location, service
type. Point to
White pages for
details.

Information about
business model
Technical details
of provided
service
Information on
business process

Yellow pages

18-19

Copyright 2004, Oracle. All rights reserved.

Green pages

UDDI Specification

18-20

UDDI Programmers API


UDDI Data Structure Specification and XML
Schema
UDDI Replication Specification and UDDI XML
Replication Schema
UDDI Operators Specification

Copyright 2004, Oracle. All rights reserved.

tModel

18-21

Provides metadata information about a Web


service specification
Contains references to the specification locations
Is used for compliance check

Copyright 2004, Oracle. All rights reserved.

tModel

<tModel
tModelKey="uuid:7716711A-1231-483F-A4B936104341BA78" operator= authorizedName=>
<name>Airport Weather</name>
<description xml:lang="en">
Web Service to check weather on intl. airports
</description>
<overviewDoc>
<description ></description>
<overviewURL>
http://live.capescience.com/wsdl/AirportWeather.wsdl

</overviewURL>
</overviewDoc>
...
</tModel>

18-22

Copyright 2004, Oracle. All rights reserved.

UDDI Support in Oracle JDeveloper 10g

JDeveloper provides a UDDI browser with which


you can:
Define a connection to a UDDI registry instance
Search for services:
Look up tModel by name or category
Locate a service implementing this tModel
Add a business providing this service to the UDDI
browser

For the located service:


Generate Web service stub/skeleton
View WSDL
View a business that provides the service

18-23

Copyright 2004, Oracle. All rights reserved.

UDDI Browsing with Oracle JDeveloper 10g

18-24

Copyright 2004, Oracle. All rights reserved.

UDDI Publishing and Browsing with


Oracle Enterprise Manager
Using Oracle Enterprise Manager Application Server
Control, you can:
Browse and register services within the UDDI
registry
Publish Web services and deploy them to a J2EE
container
Monitor and administer Web services

18-25

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Provide an overview of Web services technology
Identify the standards used by Web services
Identify the benefits of Web services
Locate and invoke Web services by using SOAP,
WSDL, and UDDI
Distinguish between RPC-style and Documentstyle Web service

18-26

Copyright 2004, Oracle. All rights reserved.

Practice 18-1: Overview

This practice covers revision questions on Web


services technology and standards such as SOAP,
WSDL, and UDDI.

18-27

Copyright 2004, Oracle. All rights reserved.

Distributing Modular Applications:


Developing Web Services

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Identify the components that can be exposed as
Web services with Oracle Application Server 10g
Develop, deploy, and test a stateless Java class
Web service by using Oracle JDeveloper 10g
Use the Web services home page to test the
deployed Web service
Identify the steps that are involved in exposing a
PL/SQL stored procedure as a Web service

19-2

Copyright 2004, Oracle. All rights reserved.

Oracle Application Server 10g


Web Services
Oracle Application Server
10g Web services can be
implemented as any of the
following:
Stateless and stateful
Java classes
Stateless PL/SQL
packages
Stateless session
Enterprise JavaBeans
(EJBs)
Java Message Service
(JMS) destinations
19-3

Copyright 2004, Oracle. All rights reserved.

Developing a Web Service with a Stateless


Java Class
1.
2.
3.
4.

19-4

Define an interface.
Define a stateless Java class.
Generate an .ear file.
Deploy the generated .ear file to Oracle
Application Server 10g.

Copyright 2004, Oracle. All rights reserved.

Defining an Interface

19-5

Copyright 2004, Oracle. All rights reserved.

Defining an Interface

19-6

Copyright 2004, Oracle. All rights reserved.

Defining a Stateless Java Class

19-7

Copyright 2004, Oracle. All rights reserved.

Defining a Stateless Java Class

19-8

Copyright 2004, Oracle. All rights reserved.

Creating the Web Service

19-9

Copyright 2004, Oracle. All rights reserved.

Creating the Client Application

19-10

Copyright 2004, Oracle. All rights reserved.

Creating the Client Application

19-11

Copyright 2004, Oracle. All rights reserved.

Deploying the Web Service

19-12

Copyright 2004, Oracle. All rights reserved.

Testing the Web Service

19-13

Copyright 2004, Oracle. All rights reserved.

Web Service Home Page

A Web service home page provides:


A link to the service description (WSDL file)
Links to Web service test pages to test the
available operations of the Web service
Links to the Web service client-side Proxy Jar
Links to the Web service client-side Proxy Source

19-14

Copyright 2004, Oracle. All rights reserved.

Testing the Deployed Web Service with


Home Page

19-15

Copyright 2004, Oracle. All rights reserved.

Testing the sayHello Operation

19-16

Copyright 2004, Oracle. All rights reserved.

Testing the sayHello Operation

19-17

Copyright 2004, Oracle. All rights reserved.

Serializing and Encoding Parameters


and Results

19-18

Oracle Application Server 10g Web services


support a prepackaged implementation for
handling encoding, decoding, serialization, and
deserialization.
Oracle Application Server 10g supports the
following encoding mechanisms:
Standard SOAP v.1.1 encoding
Literal XML encoding

Copyright 2004, Oracle. All rights reserved.

Developing a Stored Procedure


Web Service
1. Set up data sources in OC4J by configuring the
data-sources.xml file in the
ORACLE_HOME\j2ee\home\config folder.
2. Generate the Java wrapper classes for the PL/SQL
package and generate the EAR file.
3. Deploy the EAR file to Oracle Application Server
10g or stand-alone OC4J to expose it as a Web
service.

19-19

Copyright 2004, Oracle. All rights reserved.

Generating Wrapper Classes


Using JPublisher

Database

19-20

JPublisher

Copyright 2004, Oracle. All rights reserved.

Java classes

Exposing a Function as a Web Service by


Using Oracle JDeveloper 10g

19-21

Copyright 2004, Oracle. All rights reserved.

Publishing the Package as a Web Service

19-22

Copyright 2004, Oracle. All rights reserved.

JMS Web Services

Oracle Application Server 10g supplies a servlet to


support two operations on messages:

Send operation
Receive operation

The JMS Web service determines how to handle


incoming and outgoing messages from JMS
destinations.
JMS messages can be processed on the server
side by:
Message-Driven Bean (MDB)
JMS client

19-23

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Expose a stateless Java class as a Web service
Test the Web service with the Web service home
page
Use Oracle JDeveloper 10g to develop, deploy,
and test Web services
Expose a PL/SQL stored procedure as a Web
service

19-24

Copyright 2004, Oracle. All rights reserved.

Practice 19-1: Overview

This practice covers the following topics:


Exposing a stateless session bean as Web service
by using Oracle JDeveloper 10g
Deploying the Web service to an embedded OC4J
server and testing it with a client application
Deploying the Web service to Oracle Application
Server 10g and testing it with the Web services
home page

19-25

Copyright 2004, Oracle. All rights reserved.

Implementing Security in J2EE


Applications

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define Java Authentication and Authorization
Service (JAAS)
Define security issues regarding Web applications
and Enterprise JavaBeans (EJB)
List the security attributes of the Java Naming and
Directory Interface (JNDI) Context interface

20-2

Copyright 2004, Oracle. All rights reserved.

Goals of J2EE Security Architecture

20-3

Lessen the burden of the application developer in


securing applications
Ensure fine-grained access control to the EJB
resources
Enable portable and secured Web applications
and EJBs

Copyright 2004, Oracle. All rights reserved.

Overview of J2EE Security Architecture

Use Java Authentication and Authorization Service


(JAAS) APIs to:
Authenticate a client to access the system
Define security identities (principal/users), groups,
and roles to identify clients to the container
Associate principals to the client to enable access
to the bean methods

Authorize clients to access the bean methods


Define logical roles, set method permissions, and
map roles to users in the deployment descriptors
Use containers to authorize the client requests to
the methods

20-4

Copyright 2004, Oracle. All rights reserved.

Java Authentication and Authorization


Service (JAAS)
JAAS is a framework that:
Provides a Java API package to enable
applications to authenticate and enforce security
Allows definition of logical security names that are
mapped in deployment descriptors to users or
roles defined in the run-time environment
Controls access to Web applications based on
URL patterns
Allows fine-grained authorization to manage how
clients can access bean methods
A JAAS provider implements the JAAS framework and
applies the Java2 Security Model.
20-5

Copyright 2004, Oracle. All rights reserved.

Java Authentication and Authorization


Service (JAAS)
JAAS supports the following authorization,
authentication, and user community (realm) features:
Principals
Subjects
Login module authentication
Roles
Realms
Policies
Permissions

20-6

Copyright 2004, Oracle. All rights reserved.

Authorization of a Client

The authorization is specified in the J2EE-specific


and OC4J-specific deployment descriptors.
Security roles
Define the security view of the application to the
deployer
Must be mapped to the appropriate security
principals in the target environment

20-7

Every client obtains a security principal.


A client can invoke a URL or a method only if the
clients role has the associated invocation rights.
The container provider enforces the security
policies and provides the tools for managing
security.
Copyright 2004, Oracle. All rights reserved.

JAAS Provider Types in OC4J

The JAAS provider in Oracle Application Server 10g


Containers for J2EE (OC4J) supports two provider
types:
The LDAP-based provider type that is used to
access an Oracle Internet Directory (OID)
repository
The XML-based provider type that is used to
access an XML file repository by using:
The jazn-data.xml file
The principals.xml file

The repositories store the realm (users and roles) and


the policy (permissions) information.
20-8

Copyright 2004, Oracle. All rights reserved.

Configuring Security

20-9

Define users and groups in jazn-data.xml (or


principals.xml).

Define security view or logical roles in J2EE


deployment descriptor (web.xml or ejbjar.xml).

Map logical roles to users and groups in OC4Jspecific deployment descriptor (orion-web.xml
or orion-ejb-jar.xml).

Provide a user or group with read and write


access to the Java Naming and Directory Interface
(JNDI) namespace in application.xml (or
application-specific orion-application.xml).

Copyright 2004, Oracle. All rights reserved.

Defining the Users, Groups, and Roles

The identities (users and groups) are known to the


container by using the jazn-data.xml.
The identities can be specific to an application.

<jazn-realm>
<realm><name>jazn.com</name>
<users>
<user><name>admin</name>
<display-name>OC4J Administrator</display-name>
<description>OC4J Administrator</description>
<credentials>{903}5NwtZOAJa2Ty7Ksbmu3IUOfK9PgK/Kxi
</credentials>
</user>
<user><name>user</name>
<description>The default user</description>
<credentials>{903}/pQcVBQ6+AN+NNF2MzYb/0+gR4lOVwwh
</credentials>
</user> ...

20-10

Copyright 2004, Oracle. All rights reserved.

Managing Users and Groups


with the JAZN Admintool
The JAZN Admintool can manage users, roles, and
groups and can assign roles to users in XML or LDAPbased data.
It modifies jazn-data.xml or the LDAP
repository.
It prompts for admin username and password.
Examples:
java
Adding
a user: adduser jazn.com ora1 oracle
jar jazn.jar
java
Adding
a role (oraddrole
a group):jazn.com managers
jar jazn.jar
java
Granting
a role to
a user (assign
user
to a group):
jar jazn.jar
grantrole
manager
jazn.com
ora1
20-11

Copyright 2004, Oracle. All rights reserved.

Defining the Logical Roles

The logical security roles defined in the J2EE


deployment descriptors are:
Specified in the web.xml file for Web applications,
or in the ejb-jar.xml file for EJB components.
Defined in the <security-role> element for the
application. One or more roles can be specified.
Authorized to invoke methods that are listed in the
<method-permissions> element for the security
role.
Scoped at the level of the application or
all the enterprise beans in the jar file.

20-12

Copyright 2004, Oracle. All rights reserved.

Defining and Using Logical Roles in Web


Applications (web.xml)

Define logical role in the <security-role>


element
Use role in <security-constraint> element
<security-role>
<role-name>hr_managers</role-name> <!--define-->
</security-role>
<security-constraint> <web-resource-collection>
<web-resource-name>UpdEmployee</web-resourcename>
<url-pattern>/UpdEmployees.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>hr_managers</role-name> <!--apply-->
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint></security-constraint>

20-13

Copyright 2004, Oracle. All rights reserved.

Defining and Using Logical Roles in EJBs


(ejb-jar.xml)

Define logical role in <security-role> element.


Assign access in <method-permission> element.

<assembly-descriptor>
<security-role>
<description>HR Manager</description>
<role-name>hr_managers</role-name>
</security-role>
<method-permission>
<role-name>hr_managers</role-name>
<method><ejb-name>HrApp</ejb-name>
<method-name>incrementSalary</method-name>
<method-params><method-param>int</method-param>
<method-param>int</method-param></method-params>
</method></method-permission> ...
<assembly-descriptor> ...

20-14

Copyright 2004, Oracle. All rights reserved.

Mapping Logical Roles to


Users and Groups
Mapping is done in the OC4J deployment descriptors.
A logical role to a group:
<security-role-mapping name = "hr_managers">
<group name="managers"/>
</security-role-mapping>

A logical role to a user:

<security-role-mapping name = "hr_managers">


<user name="ora1"/>
</security-role-mapping>

A logical role to a group or a specific user:

<security-role-mapping name = "hr_managers">


<group name="managers"/>
<user name="ora1"/>
</security-role-mapping>

20-15

Copyright 2004, Oracle. All rights reserved.

Programmatic Access to a Callers


Security Context

Not all security policies can be expressed


declaratively.
Use a programmatic interface to access the
security context of the calling client from the bean
methods.
To access the security information of the caller,
the javax.ejb.EJBContext interface defines the
following two methods:
java.security.Principal getCallerPrincipal();
boolean isCallerInRole(java.lang.String roleName);

20-16

Copyright 2004, Oracle. All rights reserved.

Client Authentication

For Web applications:


Use Web application server security mechanisms,
where credentials are passed through to the J2EE
environment
Use OC4J container Web security
Examples: Basic or Digest Authentication, HTML
form fields, and Client SSL certificates

For EJB components:


Stand-alone (remote) clients define credentials in
InitialContext, and the jndi.properties file or
settings in a Hashtable.
Local clients, such as servlets, JSPs, or other EJBs,
pass their credentials by using the Context object.

20-17

Copyright 2004, Oracle. All rights reserved.

EJB Client Authentication with the


jndi.properties file

In the jndi.properties file:


java.naming.security.principal=ora1
java.naming.security.credentials=welcome
java.naming.factory.initial=com.evermind.server.\
ApplicationClientInitialContextFactory
java.naming.provider.url=ormi://localhost/hrApp

Client accessing the EJB with the above JNDI


properties:
Context ic = new InitialContext();
EmployeeHome = (EmployeeHome) ic.lookup(
"java:comp/env/Employee");

20-18

Copyright 2004, Oracle. All rights reserved.

EJB Client Authentication with a


Hashtable
Hashtable env = new Hashtable();
env.put("java.naming.provider.url",
"ormi://localhost/hrApp");
env.put("java.naming.factory.initial",
"com.evermind.server." +
"ApplicationClientInitialContextFactory");
env.put(Context.SECURITY_PRINCIPAL, "ora1");
env.put(Context.SECURITY_CREDENTIALS, "welcome");
Context ic = new InitialContext (env);
EmployeeHome = (EmployeeHome) ic.lookup(
"java:comp/env/Employee");

20-19

Copyright 2004, Oracle. All rights reserved.

Setting Access Control with JDeveloper

You can set security roles to access a Web


application or an EJB by using JDeveloper
deployment descriptor editors:
Use the Web Application Deployment Descriptor
editor for Web applications.
Use the EJB Module Editor for EJBs.

20-20

For Web applications, set the access permissions


as constraints defining URL patterns for a Web
resource.
For EJBs, set the access permissions for either
individual methods or all the methods of the bean.

Copyright 2004, Oracle. All rights reserved.

Creating Web Application Security Roles

1. Right-click web.xml, select Properties.


2. In the Security Roles section, click Add.

20-21

Copyright 2004, Oracle. All rights reserved.

Web Application Login Authentication

Typically done using Oracle HTTP Server using either


Basic, Digest, Login Form, Single-Sign On, and so on.

20-22

Copyright 2004, Oracle. All rights reserved.

Web Application Authorization

20-23

Define a Web resource (URLs and HTTP methods).


Grant security roles access to the Web resource.

Copyright 2004, Oracle. All rights reserved.

Creating EJB Security Roles


1. Select the Security Roles section.
2. Click Add to create and enter a new logical role
name and description in the Create Security Role
dialog window.

20-24

Copyright 2004, Oracle. All rights reserved.

Setting Method Permissions

In the Method Permissions section, select the roles


and the methods that are accessible for those roles.

20-25

Copyright 2004, Oracle. All rights reserved.

Method Access in EJB


Deployment Descriptors

20-26

The example shows the hr_managers role granted


access to the incrementSalary() method.

Explicit settings have precedence over default


method access in the OC4J deployment descriptor.

Copyright 2004, Oracle. All rights reserved.

Creating a Mapping for the Logical Roles

In JDeveloper, edit the orion-ejb-jar.xml file.


1. Right-click the file and select Properties.
2. Select Security Role Mapping, and then click Add.

3. Enter a logical role name (e.g., hr_managers).

20-27

Copyright 2004, Oracle. All rights reserved.

Mapping JAZN Identities to a Logical Role

20-28

Copyright 2004, Oracle. All rights reserved.

Mapping JAZN Identities to a Logical Role

20-29

Copyright 2004, Oracle. All rights reserved.

Mapping Results in orion-ejb-jar.xml

The OC4J XML Deployment Descriptor holds the


details for mapping the logical role to the allowed
identities (groups or users).
For example:

20-30

Copyright 2004, Oracle. All rights reserved.

Accessing the EJB with New Permissions

Any client with a role other than those specified in


the deployment descriptor receives the exception
com.evermind.server.rmi.OrionRemoteException.

20-31

Clients without read/write access to the namespace


receive the exception
javax.naming.NoPermission.

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Use the J2EE security architecture to remove from
the developer the burden of implementing security
Define Web applications and EJB security
mechanisms such as security roles
Define users, groups, and logical roles; map the
logical and concrete roles for client authorization
Access security information of the caller by using
methods in the javax.ejb.EJBContext interface

20-32

Authenticate EJB client applications by using the


jndi.properties file and InitialContext

Copyright 2004, Oracle. All rights reserved.

Practice 20-1: Overview

This practice covers the following topics:


Using the Web Application Deployment Descriptor
to create logical security roles for a Web
application
Enabling basic authentication in an OC4J
container
Programmatically determining the user credentials
and using it to control access to information
Using EJB security to control access to methods
in a bean

20-33

Copyright 2004, Oracle. All rights reserved.

Oracle Application Server 10g Transaction


Support

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Identify the use of bean-managed transactions
(BMT)
Identify the use of container-managed
transactions (CMT)
Describe how Oracle Application Server 10g
Containers for J2EE (OC4J) supports one-phase
and two-phase transaction protocols

21-2

Copyright 2004, Oracle. All rights reserved.

What Is a Transaction?

A transaction:
Is a single logical unit of work or a set of tasks
that are executed together
May access one or more shared resources, such
as databases
Must be atomic, consistent, isolated, and durable
(ACID)

21-3

Copyright 2004, Oracle. All rights reserved.

Enterprise JavaBeans (EJB) Support


for Transactions

21-4

The EJB architecture supports declarative and


programmatic transactions.
The bean provider is not exposed to the
complexity of distributed transactions.
The EJB container provides a transaction
infrastructure.
EJBs do not support a nested transaction model.

Copyright 2004, Oracle. All rights reserved.

EJB Transaction Model

Demarcating a transaction determines:


Who begins and ends a transaction
When each of these steps occur

A bean-managed (explicit) transaction:


Is demarcated by the bean
Is specified programmatically in the bean through
JTA interface or Java Database Connectivity (JDBC)
interface

A container-managed (declarative) transaction:


Is demarcated by the container
Is specified declaratively (implicit) through the XML
deployment descriptor

21-5

Copyright 2004, Oracle. All rights reserved.

Demarcating Transactions

Container-managed transactional demarcation:


The <transaction-type> element set to container
in the deployment descriptor
No transactional management code in the bean
Transaction management depends on value of the
<trans-attribute> element
Available to entity, session, and message-driven
beans (MDBs)

Bean-managed transactional demarcation:


The <transaction-type> element set to bean in
the deployment descriptor
Bean implementation must demarcate the begin,
commit, or rollback for the transaction
Available to session bean and MDBs, but not entity
beans

21-6

Copyright 2004, Oracle. All rights reserved.

Container-Managed Transactions
<session>
<ejb-name>hrApp</ejb-name>
<home>demos.hrAppHome</home> ...
<transaction-type>Container</transaction-type>
<resource-ref>
<res-ref-name>jdbc/hrCoreDS</res-ref-name> ...
</session>
<assembly-descriptor> ...
<container-transaction>
<description>no description</description>
<method>
<ejb-name>HrApp</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>RequiresNew</trans-attribute>
</container-transaction>
</assembly-descriptor> ...
21-7

Copyright 2004, Oracle. All rights reserved.

CMT: Transaction Attributes

The following are the EJB-specified values of


transaction attributes:

21-8

NotSupported
Required
Supports
RequiresNew
Mandatory
Never

The transactional behavior of a bean can be


changed with these attributes during deployment
time.

Copyright 2004, Oracle. All rights reserved.

CMT: Transaction Attributes

You specify the transaction attributes as follows:


Specify for all the methods of a stateful session
bean or an entity beans component interface and
all direct and indirect superinterfaces of the
component interface.
Do not specify for:
The methods of the javax.ejb.EJBObject
interface and the beans home interface in an
stateful session bean
The getEJBHome, getHandle, getPrimaryKey,
isIdentical, getEJBMetaData, and
getHomeHandle methods in an entity bean

21-9

Copyright 2004, Oracle. All rights reserved.

Transaction Attribute: NotSupported

A client has:
No transaction: The bean does not start one.
A transaction: The bean suspends it. The
transaction resumes when the client gains control.
Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context
21-10

Threads of
execution

Bean

No transactional context
Suspended
Bean
Resumed
No transactional context

Copyright 2004, Oracle. All rights reserved.

Transaction Attribute: Required

A client has:
No transaction: The bean starts a new one.
A transaction: The bean uses it.

Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context
21-11

Threads of
execution

Bean

New transactional context


Threads of
execution

Bean

Client transactional context

Copyright 2004, Oracle. All rights reserved.

Transaction Attribute: Supports

A client has:
No transaction: The bean does not start new one.
A transaction: The bean uses it.

Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context
21-12

Threads of
execution

Bean

No transactional context
Threads of
execution

Bean

Client transactional context

Copyright 2004, Oracle. All rights reserved.

Transaction Attribute: RequiresNew

A client has:
No transaction: The bean starts a new one.
A transaction: It is suspended, the bean starts a
new one and commits it, and then the old one
resumes.
Client
(bean or servlet)

Threads of
execution

Bean transactional context

No transactional context
Client
(bean or servlet)

Suspended

Client Transactional context


21-13

Bean

Bean
Resumed
Bean transactional context

Copyright 2004, Oracle. All rights reserved.

Transaction Attribute: Mandatory

A client has:
No transaction: The bean requires one. It throws the
javax.transaction.TransactionRequiredException

exception.
A transaction: The bean uses it.
Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context

21-14

Threads of
execution

Bean

EXCEPTION THROWN
Threads of
execution

Bean

Client transactional context

Copyright 2004, Oracle. All rights reserved.

Transaction Attribute: Never

A client has:
No transaction: The container calls the method in
an unspecified transaction context.
A transaction: The container throws the
java.rmi.RemoteException exception.

Client
(bean or servlet)
Transactional context

21-15

Threads of
execution

Bean

java.rmi.RemoteException

Copyright 2004, Oracle. All rights reserved.

CMT: The setRollbackOnly() Method

21-16

The setRollbackOnly() method can control the


transaction state in the bean for a CMT.
The setRollbackOnly() method marks the
current transaction for rollback.
If a transaction is marked for rollback, then the
container rolls back the transaction before
returning to the caller.

Copyright 2004, Oracle. All rights reserved.

JDeveloper: Setting Transaction Attributes


1. Open the EJB Module Editor for a selected EJB.
2. Select the Container Transactions section.
3. Use the buttons on the top-right corner to add,
edit, or remove transaction attributes.

21-17

Copyright 2004, Oracle. All rights reserved.

JDeveloper: Setting Transaction Attributes

1. Select the Transaction Attribute type from the list.


2. Select methods from the list and associate them
with the necessary transaction attributes.

21-18

Copyright 2004, Oracle. All rights reserved.

Java Transaction API (JTA)

JTA is used for managing transactions in J2EE.


JTA transactions involve:
Enlisting resources: Single-phase commit or twophase commit
Demarcating transactions: BMT or CMT

21-19

The JTA package provides an application interface


(UserTransaction).

Copyright 2004, Oracle. All rights reserved.

JTA: The UserTransaction Interface

Allows applications to explicitly manage


transaction boundaries
Encapsulates most of the functionality of a
transaction manager

public interface javax.transaction.UserTransaction{


public abstract void begin ();
public abstract void commit ();
public abstract int getStatus ();
public abstract void rollback ();
public abstract void setRollbackOnly ();
public abstract void setTransactionTimeout(
int secs); }

21-20

Copyright 2004, Oracle. All rights reserved.

Bean-Managed Transactions Demarcation

Is indicated by the value Bean for the


<transaction-type> element in the deployment
descriptor
Uses the UserTransaction interface of JTA to
demarcate and manage the transactions
programmatically
By using a UserTransaction object, the bean:

21-21

Initializes a transaction context on the client


Invokes the begin(), commit(), or rollback()
methods on the current transaction context to
manage the transactions

Copyright 2004, Oracle. All rights reserved.

BMT Demarcation: Process

1. Retrieve the UserTransaction object from the


bean code by using a JNDI name.
2. Start a transaction by invoking the begin()
method on the UserTransaction object.
3. Execute the business logic to be included in the
transaction.
4. End the transaction by invoking the commit() or
rollback() methods of the UserTransaction
object.

21-22

Copyright 2004, Oracle. All rights reserved.

Using UserTransaction Support in EJBs

Code example using BMT:


SessionContext ctx;
public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
}
public beanMethodA() {
UserTransaction utx = ctx.getUserTransaction();
utx.begin();
do work
utx.commit();
}

21-23

Copyright 2004, Oracle. All rights reserved.

Client-Demarcated Transactions
Using UserTransaction
For Web applications (or EJB client) demarcation:
Get an InitialContext object
Look up java:comp/UserTransaction, and cast
to javax.transaction.UserTransaction
Context ctx = new InitialContext ();
// Retrieve the UserTransaction object.
// Use its methods for transaction demarcation
UserTransaction ut = (UserTransaction)
ictx.lookup("java:comp/UserTransaction");
ut.begin(); //Start the transaction
//Look up bean & access logic to perform sql
// If everything went well, commit the transaction
ut.commit();

21-24

Copyright 2004, Oracle. All rights reserved.

BMT Demarcation: Restrictions

Session and message-driven EJBs can have beanmanaged transactions if their <transactiontype> element is set to Bean.

An instance that starts a transaction must


complete the transaction before it starts a new
transaction.
A stateful session bean can commit a transaction
before a business method ends.
A stateless session bean must commit the
transaction before the business method returns.

21-25

Copyright 2004, Oracle. All rights reserved.

Local and Global Transactions

A local transaction:
Is started and coordinated internally by the
resource manager
Has a single-phase commit

A global transaction:
Is controlled by a transaction manager external to
the resources involved
Has a two-phase commit

21-26

Copyright 2004, Oracle. All rights reserved.

Single-Phase Commit

Configure a data source:


Use the default emulated data source configuration.
Modify the url attribute with the URL of your
database.

Enlist a resource (database): Retrieve a


connection to the data source in the bean after the
transaction has begun.
Look up the data source in the JNDI namespace.
Retrieve the connection by using the JTA/JDBC
interface.

21-27

Copyright 2004, Oracle. All rights reserved.

Data Source Revisited

A data source is an instantiation of an object that


implements the javax.sql.DataSource
interface.
You can use a data source to retrieve a connection
to a database server.
A data source offers a portable, vendorindependent method for creating JDBC
connections.
J2EE applications use JNDI to look up
DataSource objects.
Data sources are defined in data-sources.xml.

Data sources can be emulated or nonemulated.

21-28

Copyright 2004, Oracle. All rights reserved.

Default data-sources.xml

<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleXADS"
ejb-location="jdbc/OracleDS"
connectiondriver="oracle.jdbc.driver.OracleDriver"
username="scott"
password="tiger"
url="jdbc:oracle:thin:@localhost:5521:oracle"
inactivity-timeout="30"
/>

21-29

Copyright 2004, Oracle. All rights reserved.

Emulated Versus Nonemulated


Data Sources

An emulated data source:

Is valid for a single database and local transactions


Is a wrapper around the Oracle data source
Is useful for Oracle and other databases
Has the
com.evermind.sql.DriverManagerDataSource
class

A nonemulated data source:


Is pure Oracle data source implementation
Is needed for two-phase commit and global
transactions
Provides XA and JTA global transaction support
Has the com.evermind.sql.OrionCMTDataSource
class

21-30

Copyright 2004, Oracle. All rights reserved.

Retrieve Connection to Data Source


<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="hrCourseDS"
location="jdbc/CoreDS"
xa-location="jdbc/xa/hrCoreXADS"
ejb-location="jdbc/hrCoreDS" ...
/>
data-sources.xml
<resource-ref>
<res-ref-name>jdbc/hrCoreDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
ejb-jar.xml
</resource-ref>
Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/hrCoreDS");
Connection conn = ds.getConnection();
Bean Code
21-31

Copyright 2004, Oracle. All rights reserved.

Retrieve Connection to Data Source


<data-source ...
ejb-location="jdbc/hrCoreDS"...
/>

data-sources.xml

<resource-ref-mapping
name="jdbc/HumanResourcesDS"
location="jdbc/hrCoreDS"/>

orion-ejb-jar.xml

<resource-ref>
<res-ref-name>jdbc/HumanResourceDS </res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
ejb-jar.xml
Bean Code
Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/HumanResourceDS");
21-32

Copyright 2004, Oracle. All rights reserved.

Global Transaction Resource


Request Flow

When an EJB requests a JDBC connection or


some other transactional resource, it gets
associated with the global transaction.
Consider an EJB with a container-managed
transactions (CMT). Assume that:
The client invokes a bean with the transaction
attribute Required
The client is not associated with a global
transaction

21-33

Copyright 2004, Oracle. All rights reserved.

Resource Request Flow

Client

Application
(Bean)

4
8
OC4J

Transaction
manager
(Oracle10g DB)

21-34

5
Resource
adapter

Copyright 2004, Oracle. All rights reserved.

Enlisting Database Resources

21-35

The process of including SQL updates in a


transaction is called enlisting.
JTA automatically enlists databases opened with a
DataSource object in a global UserTransaction
object.
Since JDK 1.2, a DataSource published into a
JNDI namespace is the recommended way to
make connections.
If your global transaction involves more than one
database, then you must configure a two-phase
commit engine.

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe bean-managed and container-managed
transactions
Explain how OC4J supports one-phase and twophase transaction protocol logic

21-36

Copyright 2004, Oracle. All rights reserved.

Practice 21-1: Overview

This practice covers the following topics:


Deploying a Web application and entity bean with
CMT
Altering the transaction attributes of the methods
in the entity bean, and testing behavior
Optionally, creating a session bean to mediate a
transaction between the Web application and the
entity bean methods

21-37

Copyright 2004, Oracle. All rights reserved.

Appendix B

Schema Descriptions

Copyright 2004, Oracle. All rights reserved.

BMP Entity EJBs


J2EE Connector Architecture

Copyright 2004, Oracle. All rights reserved.

BMP Bean: Example

D-2

The example in this lesson creates a BMP entity


bean with the following components:
Remote interface: JobsBMP
Home interface: JobsBMPHome
Bean class: JobsBMPBean
Primary key class: JobsBMPPK
Exception class: JobSalException
Deployment descriptor: ejb-jar.xml
Client for the JobsBMP bean: JobsBMPClient

Copyright 2004, Oracle. All rights reserved.

Remote Interface: JobsBMP


...
public interface JobsBMP extends EJBObject
{
void incrMinSal(double amt) throws
JobSalException, RemoteException;
void incrMaxSal(double amt) throws
RemoteException;
String getJobTitle()throws RemoteException;
void setJobTitle(String title)throws
RemoteException;
double getMinSal()throws RemoteException;
void setMinSal(double amt)throws RemoteException;
double getMaxSal()throws RemoteException;
void setMaxSal(double amt)throws RemoteException;
}

D-3

Copyright 2004, Oracle. All rights reserved.

Home Interface: JobsBMPHome


...
public interface JobsBMPHome extends EJBHome
{
JobsBMP create() throws RemoteException,
CreateException;
JobsBMP create(String id, String title, double
minSal, double maxSal) throws
CreateException,RemoteException;
JobsBMP findByPrimaryKey(JobsBMPPK primKey)
throws FinderException, RemoteException;
Collection findByMaxSalLimit (double salLimit)
throws FinderException, RemoteException;
double getAvgMaxSal() throws JobSalException,
RemoteException;
}

D-4

Copyright 2004, Oracle. All rights reserved.

Primary Key Class: JobsBMPPK


import java.io.Serializable;
public class JobsBMPPK implements Serializable
{ public String jobId;
public JobsBMPPK(String id)
{ this.jobId = id; }
public boolean equals(Object job)
{...}
public int hashCode()
{
return super.hashCode();
}
public String toString()
{ return jobId; }
}

D-5

Copyright 2004, Oracle. All rights reserved.

User-Defined Exception:
JobSalException
public class JobSalException extends Exception
{
public JobSalException()
{ super(); }
public JobSalException(Exception e)
{ super(e.toString()); }
public JobSalException(String s)
{ super(s); }
}

D-6

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


...
public class JobsBMPBean implements EntityBean {
public String id;
public String jobTitle;
public double maxSal;
public double minSal;
private Connection conn = null;
private EntityContext context;
private PreparedStatement ps = null;
private ResultSet rset = null;
public JobsBMPBean()
{
System.out.println("New bean instance
created");
}
...

D-7

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


...
public JobsBMPPK ejbCreate(String id, String title,
double minSal, double maxSal)
{ try {
this.id = id;
this.jobTitle = title;
this.minSal = minSal;
this.maxSal = maxSal;
conn = getConnection();
ps = conn.prepareStatement("INSERT INTO jobs
VALUES(?,?,?,?)");
ps.setString(1, id);
ps.setString(2, jobTitle);
ps.setDouble(3, minSal);
ps.setDouble(4, maxSal);
ps.executeUpdate();
}
catch (Exception e) { e.printStackTrace(); }
finally { closeConnection(); }
return new JobsBMPPK(id);
}
...

D-8

Copyright 2004, Oracle. All rights reserved.

create() and ejbCreate()


EJB Container
1

2 ejbCreate()

create()
Home
object
EJB Object

Client

primary key
4

Entity Bean
instance

EJB
object

Table in database
D-9

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


public void ejbPostCreate(String id, String title,
double minSal, double maxSal)
{ }
public JobsBMPPK ejbFindByPrimaryKey(JobsBMPPK primKey)
{ try {
conn = getConnection();
ps = conn.prepareStatement(
"SELECT job_id FROM jobs WHERE job_id = ?");
ps.setString(1, primKey.toString());
rset = ps.executeQuery();
if (!rset.next()) {
throw new ObjectNotFoundException("no job with job
ID " + primKey); }
ps.close();
}
catch (Exception e) { ... }
finally { closeConnection(); }
return primKey;
}

D-10

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


public void ejbActivate() { }
public void ejbPassivate() { }
public void setEntityContext(EntityContext ctx)
{
this.context = ctx;
}
public void unsetEntityContext()
{ this.context = null; }
public void ejbRemove(){
JobsBMPPK jobId = (JobsBMPPK)context.getPrimaryKey();
try {
conn = getConnection();
ps = conn.prepareStatement("DELETE FROM jobs WHERE
job_id = ?");
ps.setString(1, jobId.toString());
ps.executeUpdate();
}
catch (Exception e1) {...}
finally { closeConnection(); }
}

D-11

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


public void ejbLoad() {
JobsBMPPK key=(JobsBMPPK)context.getPrimaryKey();
this.id = key.jobId;
try {
conn = getConnection();
ps = conn.prepareStatement(
"SELECT job_title,min_salary, max_salary " +
"FROM jobs WHERE job_id = ? ");
ps.setString(1, id);
rset = ps.executeQuery();
rset.next();
jobTitle = rset.getString("job_title");
minSal = rset.getDouble("min_salary");
maxSal = rset.getDouble("max_salary");
}
...
}

D-12

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean

public void ejbStore() {


JobsBMPPK key= (JobsBMPPK)context.getPrimaryKey();
String id = key.jobId;
try {
conn = getConnection();
ps = conn.prepareStatement(
"UPDATE jobs SET job_title=?, min_salary=?,
max_salary=? WHERE job_id = ?");
ps.setString(1, jobTitle);
ps.setDouble(2, minSal);
ps.setDouble(3, maxSal);
ps.setString(4, id);
ps.executeUpdate();
}
...
}

D-13

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


public void incrMinSal(double amt)
throws JobSalException {
if ((minSal + amt) > maxSal)
{ throw new JobSalException ("You cannot
increase min salary to be more than " +
maxSal);}
else { minSal += amt; } }
public void incrMaxSal(double amt)
{ maxSal += amt; }
public String getJobTitle()
{ return jobTitle; }
public void setJobTitle(String title)
{ this.jobTitle = title; }
public double getMinSal()
{ return minSal; }

D-14

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


public void setMinSal(double amt)
{ this.minSal = minSal; }
public double getMaxSal() { return maxSal; }
public void setMaxSal(double amt)
{ this.maxSal = maxSal; }
private Connection getConnection() throws SQLException
{ DataSource ds=null;
try { Context ctx = new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/hrDS");
}
catch (NamingException e)
{ System.out.println("Could not get connection");
e.printStackTrace();
throw new SQLException(e.getMessage());
}
return ds.getConnection();
}

D-15

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean

private void closeConnection ()


{
try { if (rset != null) rset.close();}
catch (Exception e) {...}
try { if (ps != null) ps.close();}
catch (Exception e) {...}
try { if (conn != null) conn.close(); }
catch (Exception e) {...}
}

D-16

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean

public double ejbHomeGetAvgMaxSal()


throws JobSalException
{
try {
conn = getConnection();
ps = conn.prepareStatement
("SELECT AVG(max_salary) as AvgMax FROM jobs");
rset = ps.executeQuery();
if (rset.next()) return rset.getDouble("AvgMax");
}
catch (Exception e) {
e.printStackTrace();
throw new JobSalException(); }
finally { closeConnection(); }
throw new JobSalException ("Error in the method");
}

D-17

Copyright 2004, Oracle. All rights reserved.

Bean Class: JobsBMPBean


public Collection ejbFindByMaxSalLimit

(double salLimit)
{
Vector v = null;
try {
v = new Vector();
conn = getConnection();
ps = conn.prepareStatement ("SELECT job_id
FROM jobs WHERE max_salary > ? ");
ps.setDouble(1,salLimit);
rset = ps.executeQuery();
while (rset.next()) {
String id = rset.getString("job_id");
v.addElement(new JobsBMPPK(id));
}
} catch (Exception e) {...}
finally { closeConnection(); }
return v;
}
}
D-18

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor
...
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>JobsBMP</ejb-name>
<home> demos.JobsBMPHome</home>
<remote>demos.JobsBMP</remote>
<ejb-class>demos.JobsBMPBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>demos.JobsBMPPK
</prim-key-class>
<reentrant>False</reentrant>
<resource-ref>
<res-ref-name>jdbc/hrDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Application</res-auth>
</resource-ref> </entity> ...

D-19

Copyright 2004, Oracle. All rights reserved.

Deployment Descriptor

...
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>JobsBMP</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>

D-20

Copyright 2004, Oracle. All rights reserved.

Creating Data Source data-sources.xml


<?xml version="1.0" standalone='yes'?>
...
<data-sources>
<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleXADS"
ejb-location="jdbc/hrDS"
connectiondriver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="hr"
password="hr"
inactivity-timeout="30"
/>
</data-sources>

D-21

Copyright 2004, Oracle. All rights reserved.

Client Class: JobsBMPClient


import javax.ejb.*;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.*;
import javax.naming.*;
public class JobsBMPClient {
public static void main(String[] args)
{
JobsBMP jobs = null;
try {
Context context = getInitialContext();
JobsBMPHome jobsBMPHome = (JobsBMPHome)
PortableRemoteObject.narrow
(context.lookup("JobsBMP"),JobsBMPHome.class);
JobsBMP jobsBMP;
jobsBMP = jobsBMPHome.create
("job_dev", "Bean Developer", 3000, 5000);
...

D-22

Copyright 2004, Oracle. All rights reserved.

Client Class: JobsBMPClient


...
jobsBMP.incrMinSal( 200.0 );
System.out.println ("min_salary after incrementing
" + jobsBMP.getMinSal( ));
jobsBMP.incrMaxSal( 600.0 );
System.out.println ("max_salary after incrementing
" + jobsBMP.getMaxSal( ));
System.out.println("printing job_title "+
jobsBMP.getJobTitle( ));
Collection
col=jobsBMPHome.findByMaxSalLimit(15000);
Iterator it = col.iterator();
while (it.hasNext())
{
JobsBMP jobSals = (JobsBMP)it.next();
System.out.println(jobSals.getMaxSal());
} }
catch(Throwable ex) {...} }
...

D-23

Copyright 2004, Oracle. All rights reserved.

Overview of J2EE Connector Architecture

The J2EE Connector Architecture (JCA) enables


J2EE components to interact with Enterprise
Information Systems (EISs) such as:
Enterprise resource planning (ERP)
Mainframe transaction processing
Databases and nonrelational systems, and so on

D-24

JCA simplifies the integration of diverse EISs.


Adherence to the JCA specification makes an EIS
implementation portable across compliant J2EE
servers.

Copyright 2004, Oracle. All rights reserved.

OC4J J2EE Connector Architecture

Basic J2EE Connector Architecture:


Application
Contract

OC4J

Resource
Adapter
J2EE Application
Component

D-25

System
Contracts
(Quality of
Service)

Copyright 2004, Oracle. All rights reserved.

Enterprise
Information
System

What Is a Resource Adapter?


It is a driver used by a client application to connect to
a specific EIS.
OC4J provides support for two J2EE 1.3 types:
A stand-alone resource adapter, which is found in a
Resource Adapter Archive (RAR) file for use by all
deployed applications
An embedded resource adapter, which is bundled in
an EAR file for a specific enterprise application

Examples of resource adapters:


JDBC or SQL for Java (SQLJ) drivers for database
connections
ERP adapter to connector a specific ERP

D-26

Copyright 2004, Oracle. All rights reserved.

Resource Adapter Deployment Descriptors

OC4J provides the following deployment descriptors


for resource adapters:
ra.xml: A standard J2EE deployment descriptor
for developing an adapter
oc4j-ra.xml: Contains deployment
configurations for deploying an adapter to OC4J
oc4j-connectors.xml
One oc4j-connectors.xml file: Contains a list of
stand-alone resource adapters deployed. It is
located in the
ORACLEAS_HOME/j2ee/home/config directory.

D-27

Copyright 2004, Oracle. All rights reserved.

Deploying Stand-Alone
Resource Adapters
When deploying stand-alone adapters:
Give the resource adapter a unique name, to
simplify future operations such as removal of a
deployed resource adapter
Deploy in one of the following two ways:
Using the Admin command-line tool (admin.jar)
Manually through directory manipulation, by
expanding the .rar file contents into a userspecified directory name <connector-name> below
the ORACLEAS_HOME/j2ee/home/<connector
directory> (which defaults to
ORACLEAS_HOME/j2ee/home/connectors)

D-28

Copyright 2004, Oracle. All rights reserved.

Deploying Embedded Resource Adapters

D-29

Embedded resource adapters are packaged and


deployed inside an Enterprise Application Archive
(EAR) file.
Each application (from an EAR file) has one oc4jconnectors.xml file.
The application oc4j-connectors.xml file lists
all the resource adapters deployed in the EAR file.
The oc4j-connectors.xml file is automatically
generated if not already included in the EAR file.

Copyright 2004, Oracle. All rights reserved.

Common Client Interface (CCI) API

CCI is defined by the J2EE Connector Architecture


specification as:
A set of interfaces and classes to allow a J2EE
component to perform data access operations
with an EIS
Main interfaces and classes are:

ConnectionFactory
Connection
Interaction
RecordFactory
Record

(Use Suns Java J2EE Tutorial for more information.)


D-30

Copyright 2004, Oracle. All rights reserved.