Professional Documents
Culture Documents
Electronic Presentation
D17247GC10
Production 1.0
May 2004
D39458
Authors
Lynn Munsinger
Sunitha Patel
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
Course Objectives
1-2
Course Objectives
1-3
Course Environment
1-4
Course Overview
1-5
Course Overview
1-6
Course Overview
1-7
1-8
1-9
1-10
Employee entity
No
Process
log in
View
employees
process
Administrator?
Yes
Insert
employees
process
1-11
Summary
1-12
J2EE Overview
Objectives
2-2
2-3
J2EE Platform
Web clients
JSP Page
Web components
Application
Enterprise
Beans
Browser
2-4
EJB clients
EJB components
Client tier
Middle tier
EIS tier
2-5
2-6
J2EE Components
2-7
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
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
What Is a Servlet?
Servlet
Browser
Request
Process results
(access database)
Format results and produce
HTML
Success or failure
A JSP:
Is a text-based document that includes:
HTML
JSP tags
Java code (including calls to JavaBeans
and servlets)
2-13
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
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
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
2-17
J2EE Server
2-18
2-19
J2EE Applications
2-20
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
JARs
2-22
WARs
welcome.jsp
2-23
EJB JARs
2-24
EARs
2-25
2-26
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
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
<application name="lesson02"
path="../applications/lesson02.ear" />
2-29
Data Sources
2-30
Application Logging
2-31
Step 2: Deploy
Step 2: Deploy
2-32
localhost
2-33
2-34
Code insight
Copyright 2004, Oracle. All rights reserved.
Design in visual
or code views
2-36
Modify values
in property
inspector
Copyright 2004, Oracle. All rights reserved.
Summary
2-38
Objectives
3-2
J2EE Issues
3-4
Business-tier patterns
Business delegate
Transfer object
3-5
Presentation (View)
View
Controller
Model
3-6
The Model
3-7
The View
3-8
The Controller
3-9
Controller
Selected
view
Model
Method
invocation
Return
result
JSP
HTTP
request
Servlet
HTTP
response
Browser
3-10
Enterprise
JavaBeans
3-11
Customer
Receive
order
status
Log in
Place
orders
Fill orders
Browse
products
Update
inventories
Administrator
Vendor
3-12
Summary
3-13
3-14
Objectives
Overview
Requests
Connects to
Servlet
Generates
Responds
Dynamic HTML
4-3
Java application,
Servlet, JSP,
or HTML
Request
Servlet engine
Response
Client
Server
4-4
Request 2
Request 3
Server
Clients
4-5
Load
Initialize
init()
3
Execute
service()
4
Destroy
destroy()
4-6
HTTP Servlets
Client
4-7
Response
HTTP protocol
Servlet
HttpServlet subclass
doGet()
Request
service()
Browser
Response
4-8
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
4-10
4-11
4-12
4-13
4-14
4-16
destroy():
Takes no arguments
Is invoked when the servlet is about to be unloaded
Is useful for releasing resources
4-18
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
Debugging a Servlet
4-20
SingleThreadModel
4-21
JDeveloper Environment
4-22
Servlet Mapping
4-23
</web-app>
4-24
Invoking a Servlet
4-25
4-26
4-27
Deploying to OC4J
4-28
Summary
4-29
4-30
4-31
Objectives
5-2
Review of JDBC
5-3
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();
5-5
synchronized (ps) {
ps.clearParameters();
ps.setInt(1,3);
ps.setDouble(2, 3.14);
ps.executeUpdate();
}
5-6
Transaction Handling
5-7
Connection Pooling
5-8
Data Sources
5-9
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
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
5-12
Summary
5-13
5-14
Objectives
6-2
Overview
Request
getCookies()
getHeader()
Response
Client Web
browser
setHeader()
addCookie()
Servlet
Error handling
6-3
HTTP Headers
6-4
Request Headers
6-5
Accept
AcceptLanguage
Cookie
Referer
User-Agent
Sending a Response
6-6
Response Headers
6-7
Example:
int pageVersion =
Integer.parseInt(req.getParameter("pageVersion"));
if (pageVersion >= currentVersion){
response.setStatus(response.SC_NO_CONTENT);
}else{
//Send original page
}
6-8
Example
6-9
6-10
Cookies
6-11
Setting Cookies
6-12
Retrieving Cookies
6-13
6-14
ServletContext
6-16
RequestDispatcher
6-17
RequestDispatcher: Example
6-18
Servlet Filters
6-19
Using Filters
6-20
doFilter() Method
6-21
Using Filters
Configuring Filters
6-23
6-24
ServletContext Events
6-25
HttpSession Events
6-26
6-27
Error Handling
6-28
Summary
6-29
6-30
Objectives
7-2
Overview
First request
Chris
Servlet
Second request
Chris
First request
Michelle
7-3
Session Basics
7-4
Session Basics
7-5
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
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
HttpSession
7-8
Session Objects
7-9
7-10
7-11
7-12
7-14
7-15
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
7-17
Summary
7-18
7-19
Objectives
8-2
JavaServer Pages
Connects to
Request
JSP
Database
Client
Generates
Dynamic content
Response
8-3
EJB
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
Invoking JSPs
HTML
Invoke
JSP
Servlet
JSP
8-5
8-6
...
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
8-8
First
time
OC4J
http://host/date.jsp
Yes
1
Create servlet
date.java
No
Compile servlet
date.class
8-9
8-10
Declarations
8-11
Expressions
8-12
Scriptlets
<% if (i<3)
out.print("i<3");
if (i==3)
out.print("i==3");
else
out.print("i>3");
%>
8-13
Implicit Objects
8-14
Example
8-15
Directives
8-16
include: Example
8-17
page Directive
8-18
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
8-20
Response
Request
Response
Forward
Page 1
Page 2
Page 3
page scope
page scope
page scope
request scope
request scope
session scope
8-21
8-22
8-23
Traditional:
No root element
page directive
<%@ page %>
Declaration tag
<%!
%>
Expression tag
<%= expression %>
Scriptlet
<%
%>
8-24
XML:
8-25
8-26
8-27
Summary
8-28
8-29
Objectives
9-2
Custom Tags
9-3
9-4
9-5
<shortname>
<uri>
<info>
<tagclass>
9-6
<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
9-8
9-9
9-10
9-11
9-12
9-13
9-14
9-15
9-17
9-18
Expression Language
<table>
<tr>
<c:forEach var="allparams" items="${param}" >
<c:out value="${allparams.key}" />
</c:forEach><tr>
<table>
9-20
9-21
9-22
9-24
9-25
<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
<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
Formatting Tags
9-28
Internationalization Concepts
9-29
Internationalizing Strings
9-30
9-31
9-32
9-33
9-34
JSTL in JDeveloper
9-35
Summary
9-36
9-37
Communicating in J2EE
Objectives
10-2
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.
10-4
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
Server
object
10-6
10-8
Naming Service
10-9
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
10-11
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
10-13
INITIAL_CONTEXT_FACTORY
PROVIDER_URL
SECURITY_PRINCIPAL
SECURITY_CREDENTIAL
dedicated.rmicontext
Copyright 2004, Oracle. All rights reserved.
10-14
10-15
lookup() Method
10-16
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
10-19
10-20
10-21
10-23
10-24
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
Client
<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
OC4J DD
10-27
10-28
10-29
JNDI Name
Summary
10-31
10-32
Objectives
11-2
11-3
11-4
Types of EJBs
11-5
EJB Type
Purpose
Session Beans
Entity Beans
Message-Driven Beans
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
11-6
EJB container
SFSBs
Client 1
Client 1
Client 2
Client 2
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.
11-7
Message-Driven Beans
EJB container
Clients
Pool of MDBs
11-8
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
Database
EJB Server
11-10
EJB Container
home/local
home
object
Remote/
local
interface
remote/
local
object
Client
11-11
EJB
class
Container
generated
11-12
Life-cycle management
Bean instance pooling
Client state management
Database connection pooling
Declarative transaction management
Security
Persistence
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
Interfaces:
Remote interface/Local interface
Home interface/Local home interface
Classes:
Bean class
Primary key class (entity beans)
11-14
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
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
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
11-17
11-18
Deployment
descriptor
Developers
responsibility
Component deployers
responsibility
Jar
command/
tool
EJB
JAR
Deployment
tools/
commands
JNDI
11-19
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
orion-ejb-jar.xml File
Oracle Application Server 10g uses the orion-ejbjar.xml file for deployment. This file:
11-21
11-22
11-23
11-24
11-25
11-26
Summary
11-27
11-28
11-29
11-30
Objectives
12-2
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
javax.ejb.SessionBean Interface
12-4
12-5
12-6
Does not
exist
Container invokes
class.newInstance,
setSessionContext(sessCtx),
and ejbCreate().
Container invokes
ejbRemove() .
Ready
12-7
12-8
12-9
12-10
12-11
12-12
Deployment Descriptor
12-13
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
12-15
12-16
Does not
exist
setSessionContext(sessCtx),
and ejbCreate()
Container invokes
ejbRemove()
ejbPassivate()
Passivated
instances
Ready
ejbActivate()
12-17
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
12-19
Summary
12-20
12-21
Entity EJBs
Objectives
13-2
Entity Beans
13-3
int x
String s
float f
int y
double d
Entity bean object
Table
13-4
13-5
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.
13-8
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
13-10
13-11
13-12
13-13
13-15
13-16
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
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
13-18
Implements:
Finder methods through ejbFindxxx() methods
Home methods through ejbHomexxx() methods
Callback methods from the EntityBean interface
Business and private methods
13-19
13-20
javax.ejb.EntityBean Interface
13-21
unsetEntityContext()
Pooled
ejbCreate()
ejbPostCreate() ejbActivate()
ejbLoad()
ejbPassivate() ejbRemove()
Ready
ejbStore()
Clients invoke
business methods
13-22
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
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
Summary
13-25
13-26
Objectives
14-2
14-3
14-4
14-5
BMP
CMP
ejbFind()
ejbcreate()
ejbLoad()
ejbStore()
setXXX() and
getXXX()
14-6
abstract
14-7
14-8
14-9
...
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
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
14-12
14-13
...
public void ejbActivate()
{ }
public void ejbLoad()
{ }
public void ejbPassivate()
{ }
public void ejbRemove()
{ }
public void ejbStore()
{ }
}
14-14
14-15
14-17
14-18
14-19
14-20
14-21
14-22
14-23
14-24
Summary
14-25
14-26
Objectives
15-2
Relationships
15-3
Implementing Relationships
15-4
Cardinality:
One-to-one
One-to-many or many-to-one
Many-to-many
Directionality:
Unidirectional
Bidirectional
15-5
One-to-One Relationships
name
phone_num
100
Smith
111 1111
area_code
service
650
MCI
PHONE
phone_num
111 1111
15-6
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
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
...
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
SQL server
J2EE
Application Server
EIS
Servlets/JSPs
Oracle
EJBs
XML
Data mapping and integration
DB2
15-10
15-11
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
15-12
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
15-13
...
public abstract class Phone implements EntityBean
{
...
public abstract EmpLocal getEmp_EmployeeID();
public abstract void setEmp_EmployeeID(EmpLocal e);
...
15-14
...
15-15
15-16
15-17
Implementing a Relationship in
the Deployment Descriptor
15-18
15-19
15-20
15-21
15-22
15-23
15-24
15-25
15-26
15-27
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
Summary
15-29
15-30
Objectives
16-2
16-3
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
16-5
MOM
JMS client
Consumer
Application JMS
JMS Application
Queue/Topic
JMS client
16-6
JMS provider
JMS client
Point-to-Point Model
M1
Queue1
M2
M1
M2
S2
R1
R2
M3
Queue2
Messaging server
Queue sender
M* - Message
16-7
M3
Queues
(virtual destinations)
R3
Queue receiver
Publish-and-Subscribe Model
M1
S1
Topic1
S2
P2
Topic2
M2
Topic publisher
M* - Message
16-8
M2
Messaging server
S3
Topics
(virtual destinations)
Topic subscriber
JMS-administered objects:
Connection Factory: Creates connections
Destination: Target/source of messages
16-9
16-10
Receiving Messages
16-12
16-13
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
MDB Architecture
OC4J
Client
JMS resource
provider
MDB
Queue/Topic
16-15
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
Container invokes
ejbRemove()
Method-ready pool
Container invokes
onMessage()
16-17
Developing MDBs
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
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
16-20
16-21
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
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
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
16-26
ejb-jar.xml
16-27
orion-ejb-jar.xml
16-28
16-29
Summary
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
16-31
Objectives
17-2
Overview
Web tier
JSP
HttpServlet
Request
EJB tier
Controller
servlet
To EIS
HttpServlet
Response
17-3
Employees
JSP
Employees
EJB
17-4
17-5
17-6
17-7
17-8
17-9
ejb-local-ref Element
17-10
EJB Tags
17-11
EJB Tag
Purpose
useHome
useBean
createBean
iterate
useHome Tag
17-12
useBean Tag
17-13
createBean Tag
17-14
iterate Tag
17-15
17-16
17-17
17-18
17-19
17-20
Summary
17-21
17-22
Objectives
18-2
HTML
Web
presentation
HTTP client
Business
logic
XML
External
applications
18-3
Web
service
Application Server
Databases
Web Service
18-4
Service-Oriented Architecture
Service
registry
Publish
Find
Service
provider
18-5
Invoke
Service
requestor
18-6
18-7
2
Find
Web services
directory
(UDDI)
Invoke
Publish
18-8
18-9
18-10
Oracle Application
Server 10g is the
infrastructure for:
Describing Web
services
Deploying Web
services
Publishing Web
services
Invoking Web
services
18-11
18-12
Request
Response
SOAP client
18-13
Firewall
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
18-15
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
UDDI Registry
18-17
UDDI Business
Registry
UDDI Registry
Business
descriptions
Business user
18-18
Service
types
Software developer
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
Green pages
UDDI Specification
18-20
tModel
18-21
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
18-23
18-24
18-25
Summary
18-26
18-27
Objectives
19-2
19-4
Define an interface.
Define a stateless Java class.
Generate an .ear file.
Deploy the generated .ear file to Oracle
Application Server 10g.
Defining an Interface
19-5
Defining an Interface
19-6
19-7
19-8
19-9
19-10
19-11
19-12
19-13
19-14
19-15
19-16
19-17
19-18
19-19
Database
19-20
JPublisher
Java classes
19-21
19-22
Send operation
Receive operation
19-23
Summary
19-24
19-25
Objectives
20-2
20-3
20-4
20-6
Authorization of a Client
20-7
Configuring Security
20-9
Map logical roles to users and groups in OC4Jspecific deployment descriptor (orion-web.xml
or orion-ejb-jar.xml).
<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
20-12
20-13
<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
20-15
20-16
Client Authentication
20-17
20-18
20-19
20-20
20-21
20-22
20-23
20-24
20-25
20-26
20-27
20-28
20-29
20-30
20-31
Summary
20-32
20-33
Objectives
21-2
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
21-4
21-5
Demarcating Transactions
21-6
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
21-8
NotSupported
Required
Supports
RequiresNew
Mandatory
Never
21-9
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
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
Bean
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
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
No transactional context
Client
(bean or servlet)
Suspended
Bean
Bean
Resumed
Bean transactional context
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
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
21-16
21-17
21-18
21-19
21-20
21-21
21-22
21-23
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
Session and message-driven EJBs can have beanmanaged transactions if their <transactiontype> element is set to Bean.
21-25
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
Single-Phase Commit
21-27
21-28
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
21-30
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
21-33
Client
Application
(Bean)
4
8
OC4J
Transaction
manager
(Oracle10g DB)
21-34
5
Resource
adapter
21-35
Summary
21-36
21-37
Appendix B
Schema Descriptions
D-2
D-3
D-4
D-5
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
D-7
D-8
2 ejbCreate()
create()
Home
object
EJB Object
Client
primary key
4
Entity Bean
instance
EJB
object
Table in database
D-9
D-10
D-11
D-12
D-13
D-14
D-15
D-16
D-17
(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
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
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
D-21
D-22
D-23
D-24
OC4J
Resource
Adapter
J2EE Application
Component
D-25
System
Contracts
(Quality of
Service)
Enterprise
Information
System
D-26
D-27
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
D-29
ConnectionFactory
Connection
Interaction
RecordFactory
Record