oracle10g build j2ee applications - electronic presentation.pdf
TRANSCRIPT
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 1/596
Oracle10g: Bui ld J2EE Applications
Electronic Presentation
D17247GC10
Production 1.0
May 2004
D39458
®
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 2/596
Copyright © 2004 Oracle. All rights reserved.
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:
Restricted Rights Legend
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).
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 Data-
General, 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.
Oracle and all references to Oracle Products are trademarks or registered trademarks of Oracle
Corporation.
All other products or company names are used for identification purposes only, and may be
trademarks of their respective owners.
Authors
Lynn Munsinger
Sunitha Patel
Technical Contributors and
Reviewers
Anna AtkinsonScott BrewtonKenneth Cooper
Craig Hollister Taj-ul Islam
Istvan KissPeter LaseauGlenn Maslen
Monica Motley-Mosser Nagavalli PataballaHolger Dindler-RasmussenGlenn Stokol
Vasiliy Strelnikov
Venkat Tallapragada
Publisher
S. Domingue
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 3/596
Copyright © 2004, Oracle. All rights reserved.
Introduction
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 4/596
1-2 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 usingJ2EE components: servlets, JavaServer Pages
(JSP), and Enterprise JavaBeans (EJB)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 5/5961-3 Copyright © 2004, Oracle. All rights reserved.
Course Objectives
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 6/5961-4 Copyright © 2004, Oracle. All rights reserved.
Course Environment
• 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 7/5961-5 Copyright © 2004, Oracle. All rights reserved.
Course Overview
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 8/5961-6 Copyright © 2004, Oracle. All rights reserved.
Course Overview
• 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)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 9/5961-7 Copyright © 2004, Oracle. All rights reserved.
Course Overview
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 10/5961-8 Copyright © 2004, Oracle. All rights reserved.
About the Course Applications
• The course uses applications that are derived
from the Order Entry and Human Resourcessample schemas.
• In the practices, you write applications that allow
users to:
– 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 11/5961-9 Copyright © 2004, Oracle. All rights reserved.
Order Entry Schema
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 12/5961-10 Copyright © 2004, Oracle. All rights reserved.
Human Resources (HR) Schema
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 13/5961-11 Copyright © 2004, Oracle. All rights reserved.
HR Application Flow Diagram
Insert
employees
process
View
employeesprocess
Processlog in
Yes
No
Employee entity
Administrator?
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 14/5961-12 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 Javaclients
• Implement J2EE security in applications
• Deploy J2EE applications to Oracle Application
Server 10g
• Develop Web services, and provide access to
them
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 15/596
Copyright © 2004, Oracle. All rights reserved.
J2EE Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 16/596
2-2 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 f iles of OC4J
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 17/596
2-3 Copyright © 2004, Oracle. All rights reserved.
Java 2, Enterprise Edition Platform
The Java 2, Enterprise Edition (J2EE) platform is a
standard for developing and implementingenterprisewide applications:
• It provides multitier applications support.
• It is designed to help improve the process of
developing, deploying, and implementing
enterprisewide applications.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 18/596
2-4 Copyright © 2004, Oracle. All rights reserved.
J2EE Platform
• Is a multit iered, distributed application model
• Supports component-based J2EE applications
Client tier
EJB clients
Application
Middle tier
Web components
Servlet
JSP Page
EJB components
EnterpriseBeans
Web clients
EIS tier
Browser
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 19/596
2-5 Copyright © 2004, Oracle. All rights reserved.
Benefits of the J2EE Platform
• “ 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 mult iple development and design
scenarios.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 20/596
2-6 Copyright © 2004, Oracle. All rights reserved.
Benefits of the J2EE Platform
• 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 21/596
2-7 Copyright © 2004, Oracle. All rights reserved.
J2EE Components
• J2EE is a component-based architecture for the
development and deployment of enterprisewideapplications.
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 22/596
2-8 Copyright © 2004, Oracle. All rights reserved.
J2EE 1.3 Components
The J2EE 1.3 Specification lists the following
components:• Servlet 2.3
• JavaServer Pages 1.2
• EnterpriseJavaBeans 2.0
• JDBC 2.0
• RMI-IIOP
• JNDI 1.2
• Web services 1.1
• Java Message Service
1.0.2
• Java Transaction API 1.0
• Java Authentication and
Authorization Service
1.0
• J2EE Connector Architecture 1.0
• SOAP with Attachments
API for Java 1.1
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 23/596
2-9 Copyright © 2004, Oracle. All rights reserved.
J2EE Architecture
Client Machine
J2EE Server
Business container EJB
Java Servlet/JSP
Web Container
EJB
APIs
Browser
Application
Client
Container
Application
Client
DatabaseJNDI
RMI JDBC
JTA
JAF
JMS
JavaMail
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 24/596
2-10 Copyright © 2004, Oracle. All rights reserved.
Client-Tier Components
• A Web browser:
– Is used for a Web-based J2EE application – Downloads static or dynamic Web pages from Web-
tier components
– Is a thin client
• An application client:
– 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 25/596
2-11 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 26/596
2-12 Copyright © 2004, Oracle. All rights reserved.
Client info (host name,form data)
Success or failure
Process results(access database)
Format results and produce
HTML
Send page back to client
Browser Servlet
What Is a Servlet?
Request
Response
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 27/596
2-13 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)
• Cleanly separates content creation from
presentation logic
• Focuses on rapid development and easymodification of the user interface
• Provides presentation-centric method of
developing servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 28/596
2-14 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 29/596
2-15 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 30/596
2-16 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 31/596
2-17 Copyright © 2004, Oracle. All rights reserved.
J2EE Communication APIs
• J2EE provides component communication
through APIs.• The APIs include:
– RMI
– JNDI
– JDBC
• These APIs facili tate communication between the
J2EE components.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 32/596
2-18 Copyright © 2004, Oracle. All rights reserved.
J2EE Server
The J2EE server provides:
• Containers for each component type of a J2EEapplication
• 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)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 33/596
2-19 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:
– 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 availabili ty and failover
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 34/596
2-20 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 35/596
2-21 Copyright © 2004, Oracle. All rights reserved.
Packaging J2EE Application Components
1. ejb.jarBean class, Home and Remote
interfaces, other supported fi les, DD
2. webtier.warJava servlets, JSP fi les, HTML, GIF fi les,
DD (references to EJBs)
3. J2EEappClient.jarJ2EE application client (Java class),
DD (references to EJBs)
4. DD for J2EE application (.xml)
DD = XML Deployment
Descriptor
5. Resource adapter (.rar)
J2EEapplication.ear
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 36/596
2-22 Copyright © 2004, Oracle. All rights reserved.
JARs
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 37/596
2-23 Copyright © 2004, Oracle. All rights reserved.
WARs
• Are specialized archives for packaging J2EE-
compliant Web applications
• Have a fixed directory structure
• Have a deployment descriptor for the Web
application
lib
Contain servlet code andJavaBeans not in standard
JAR filesContains required classesthat are packaged instandard JAR files
classes
WEB-INF
web.xml
index.html
welcome.jsp
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 38/596
2-24 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
EJB Classes
Contain the class filesfor the EJBs, usually
in a package directory
structureRemote, Home and
Bean classes
ejb-jar.xml
myEJB
META-INF
EAR
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 39/596
2-25 Copyright © 2004, Oracle. All rights reserved.
EARs
The EAR files:
• Are specialized archives for packaging J2EE-compliant enterprise applications for deployment
• Have a deployment descriptor
• May have Web modules
• May have EJB modules
• May have client modules
EAR Fil St t f
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 40/596
2-26 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
OC4J A hit t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 41/596
2-27 Copyright © 2004, Oracle. All rights reserved.
OC4J Architecture
Webcontainer
JNDI
JMS
EJB
container
AJP13
ORMI
JDBC
JTA
JavaMailJAF
mod_oc4j
Client
EJB client
Oracle HTTP
Server
ORMI
AJP
HTTP
OC4J server process
JAAS
JCA
OC4J S C fi ti Fil
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 42/596
2-28 Copyright © 2004, Oracle. All rights reserved.
OC4J Server Configuration Files
OC4J Server XML Files
Web site
Web site
Server Configuration
jazn.xml*
Web site
default-web-
site.xml
Oracle HTTP Serverconfiguration files
mod_oc4j.conf
jazn-data.xml*
server.xml
data-sources.xml
rmi.xml
jms.xml
Relation of Configuration Files
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 43/596
2-29 Copyright © 2004, Oracle. All rights reserved.
Relation of Configuration Files
<web-app application="lesson02" name="webapp1"
root="/lesson02"/>
<web><web-uri>webapp1.war</web-uri></web>
<application name="lesson02"
path="../applications/lesson02.ear" />
• When an application is deployed, an entry is made inthe \config\server.xml file:
• For each Web module within the application, a context
root is defined in \config\default-web-site.xml:
• The modules of the application are defined in\applications\lesson02\META-
INF\application.xml:
Data Sources
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 44/596
2-30 Copyright © 2004, Oracle. All rights reserved.
Data Sources
A data source is the instantiation of an object thatimplements the javax.sql.DataSource interface,
which enables you to retrieve a connection to a
database server.
• OC4J data sources are defined in data-
sources.xml.• J2EE applications use JNDI to look up these
DataSource objects.
Application Logging
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 45/596
2-31 Copyright © 2004, Oracle. All rights reserved.
Application Logging
• Application logging in Oracle Application Server
10g is configured by specifying the location of alog file in the application.xml file:
• To create a log file formatted in XML, use Oracle
Diagnostic Logging (ODL):
<log>
<file path="practice02-oc4j-app.log"/>
</log>
<log>
<odl path="practice02-oc4j-app.log"/>
</log>
J2EE Application Deployment to
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 46/596
2-32 Copyright © 2004, Oracle. All rights reserved.
J2EE Application Deployment to
Oracle Application Server 10g
Deploying to OC4J can be done in multiple ways:
Step 2: Deploy
Use JDeveloper – specify an
Application Server and click 'Deploy'
Step 1: Create WAR,EAR file
Step 2: Deploy
Use a command-
line tool (such as ANT).
Use JDeveloper.
Use Oracle Enterprise Manager
(installed with Oracle ApplicationServer 10g): Access the
Enterprise Manager Web sitehttp://localhost:1810
(requires login).
Use JDeveloper: Specify an
application server and click
“Deploy.”
Oracle Enterprise Manager
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 47/596
2-33 Copyright © 2004, Oracle. All rights reserved.
Oracle Enterprise Manager
localhost
JDeveloper and J2EE
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 48/596
2-34 Copyright © 2004, Oracle. All rights reserved.
JDeveloper and J2EE
JDeveloper provides:
• Integrated development, deployment, and testing
support for Web-tier and business-tiercomponents
• A J2EE framework for rapid development
– Application Development Framework (ADF)
business components
– Data tags
• Integration with Struts
• UML modeling• Visual editors for Web clients
• Easy deployment to Oracle Application Server 10g
JDeveloper
Oracle JDeveloper 10g Environment
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 49/596
2-35 Copyright © 2004, Oracle. All rights reserved.
Oracle JDeveloper 10g Environment
Wizards for
JSPs,servlets, and
EJBs
Errorchecking
for HTML
and JSP
Code insight
EAR, WAR
deployment
to J2EE
server
Customizable code editor
Oracle JDeveloper 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 50/596
2-36 Copyright © 2004, Oracle. All rights reserved.
Oracle JDeveloper 10g
Visual Design Tools
Drag JSP, HTML
elements
Modify values
in property
inspector
Design in visual
or code views
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 51/596
2-37 Copyright © 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned that:
• J2EE is a set of Java technologies that supportend-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
Practice 2-1: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 52/596
2-38 Copyright © 2004, Oracle. All rights reserved.
Practice 2 1: Overview
This practice covers the following topics:
• Navigating to the OC4J console by using OracleEnterprise 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 53/596
Copyright © 2004, Oracle. All rights reserved.
Designing J2EE Applications
Objectives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 54/596
3-2 Copyright © 2004, Oracle. All rights reserved.
j
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 maintainableapplications
• Identify sample architectures and their merits and
demerits
Realizing J2EE Benefits
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 55/596
3-3 Copyright © 2004, Oracle. All rights reserved.
g
To leverage the full benefits of J2EE, you must designapplications that are:
• Portable: You should be able to redeploy the J2EEapplications to different servers, databases, andso on.
• Scalable: Web applications should be able tohandle large numbers of users.
• Maintainable: A minimum amount of codingshould be necessary for a new business rule.
• Reusable: A class that processes credit cardsshould be reused by multiple applications.
• Simple: The business need should be solved with
the least amount of complexity.
J2EE Issues
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 56/596
3-4 Copyright © 2004, Oracle. All rights reserved.
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.
J2EE Design Patterns
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 57/596
3-5 Copyright © 2004, Oracle. All rights reserved.
g
Recurring application development issues have led to
the acceptance of design patterns. The generally
accepted design patterns include (but are not limitedto) the following:
• Presentation-tier patterns
– Intercepting filter – Controller servlet
• Business-tier patterns
– Business delegate – Transfer object
Implementing Design Patterns by
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 58/596
3-6 Copyright © 2004, Oracle. All rights reserved.
Using MVC
MVC is a framework that separately identif ies the
components of an application as:
• Business functionality (Model)
• Presentation (View)
• Control logic (Controller)
View Controller
Model
The Model
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 59/596
3-7 Copyright © 2004, Oracle. All rights reserved.
• The model represents the enterprise data and
business rules, handling access and updates.
• You can simplify the model by using two
mechanisms called “ façade class” and “ command
pattern.”
– A façade encapsulates and hides the complexity,and coordinates the operations between
cooperating classes.
– A command pattern encapsulates each application
function in a separate class.
• The model is often implemented as EJBs.
The View
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 60/596
3-8 Copyright © 2004, Oracle. All rights reserved.
• 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 onlyvisual design skills
• The view is commonly implemented as JSPs.
The Controller
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 61/596
3-9 Copyright © 2004, Oracle. All rights reserved.
• 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 fulfi ll these requests – Removes navigation coding from the view
– Can be implemented in the client, Web, or EJB t ier
or in a combination of these tiers
• The control ler is usually implemented as a servlet.
MVC in Oracle Application Server 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 62/596
3-10 Copyright © 2004, Oracle. All rights reserved.
Containers for J2EE
Browser
Servlet EnterpriseJavaBeans
HTTPresponse
Methodinvocation
Return
result
Selectedview
ModelView Controller
JSP
HTTPrequest
Designing J2EE Applications
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 63/596
3-11 Copyright © 2004, Oracle. All rights reserved.
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 taskof managing transactions.
Flow Diagram: Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 64/596
3-12 Copyright © 2004, Oracle. All rights reserved.
Browse
products
Receive
order
status
Administrator
Vendor
Log in
Customer
Update
inventories
Fill ordersPlace
orders
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 65/596
3-13 Copyright © 2004, Oracle. All rights reserved.
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
Practice 3-1: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 66/596
3-14 Copyright © 2004, Oracle. All rights reserved.
This practice covers using J2EE design patterns and
the MVC architecture to identify components for a
proposed application.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 67/596
Copyright © 2004, Oracle. All rights reserved.
Creating the Web Tier: Servlets
Objectives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 68/596
4-2 Copyright © 2004, Oracle. All rights reserved.
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
Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 69/596
4-3 Copyright © 2004, Oracle. All rights reserved.
Dynamic HTML
Client Web browser Servlet
Connects to
Generates
Requests
Responds
About Java Servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 70/596
4-4 Copyright © 2004, Oracle. All rights reserved.
Client
Server
Servlet engine
Java application,
Servlet, JSP,or HTML
Request
Response
• A servlet is a Java class that implements theServlet interface.
• A servlet runs in the context of a special process
called a servlet engine.
• Servlets can be invoked simultaneously by
multiple clients.
Principal Features of Servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 71/596
4-5 Copyright © 2004, Oracle. All rights reserved.
Server Clients
Request 1
Request 2
Request 3
• Concurrent requests are possible and common.
• Servlet methods are run in threads.
• Servlet instances are shared by multiple client
requests.
Life Cycle of Servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 72/596
4-6 Copyright © 2004, Oracle. All rights reserved.
Load
• All actions are carried out inside the server.
• After initial setup, the response time is less.
Initialize
init()
Destroy
destroy()
Executeservice()
1 2 3
4
HTTP Servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 73/596
4-7 Copyright © 2004, Oracle. All rights reserved.
Request
Response
• 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 willperform
• The servlet processes the request and sends back
a status code and a response.
HTTP protocolClient Servlet
Inside an HTTP Servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 74/596
4-8 Copyright © 2004, Oracle. All rights reserved.
• 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
Browser
HttpServlet subclass
service()
doGet()
Request
Response
Servlet: Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 75/596
4-9 Copyright © 2004, Oracle. All rights reserved.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*; public class SimplestServlet extends
HttpServlet
{
public void doGet(HttpServletRequestrequest, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();out.println("Hello World");
}
}
The doGet() Method
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 76/596
4-10 Copyright © 2004, Oracle. All rights reserved.
• The most common HTTP request method typemade to a Web server is GET.
• The service() method in your servlet invokesthe 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 URLhttp://www.oracle.com/servlet?param1=value1
The doPost() Method
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 77/596
4-11 Copyright © 2004, Oracle. All rights reserved.
• 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">
The HttpServletRequest Object
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 78/596
4-12 Copyright © 2004, Oracle. All rights reserved.
• 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()
The HttpServletResponse Object
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 79/596
4-13 Copyright © 2004, Oracle. All rights reserved.
• 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 theinformation:
– setContentLength(int length)
– setContentType(String type) – getWriter()
Methods for Invoking Servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 80/596
4-14 Copyright © 2004, Oracle. All rights reserved.
• 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 (anhref link)
– Submitt ing a form to the servlet (via the action tag)
– Using URL classes in client Java applications
• Invoke servlets inside the J2EE container by
defining a chain of servlets or JSPs.
Your First Servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 81/596
4-15 Copyright © 2004, Oracle. All rights reserved.
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>");
}
}
Handling Input: The Form
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 82/596
4-16 Copyright © 2004, Oracle. All rights reserved.
<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>
You can use an HTML form and the doPost() method
to modify the HelloWorld servlet.
Handling Input: The Servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 83/596
4-17 Copyright © 2004, Oracle. All rights reserved.
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>");
}}
Initialization and Destruction
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 84/596
4-18 Copyright © 2004, Oracle. All rights reserved.
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
Error Handling
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 85/596
4-19 Copyright © 2004, Oracle. All rights reserved.
• 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 implementation-dependent ways
• IOException: Is generated if there is an input or
output error while processing the request
Debugging a Servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 86/596
4-20 Copyright © 2004, Oracle. All rights reserved.
Servlets can be debugged in the following ways:
• Setting breakpoints and using the debugger in
JDeveloper
• Viewing the source of the generated HTML
SingleThreadModel
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 87/596
4-21 Copyright © 2004, Oracle. All rights reserved.
• You can implement the SingleThreadModel
interface to prevent multithreaded access of data.
• Each concurrent request then has its own
dedicated servlet instance, which is randomly
assigned.
public class HelloWorld extends HttpServlet
implements SingleThreadModel{
public void doGet…
}
JDeveloper Environment
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 88/596
4-22 Copyright © 2004, Oracle. All rights reserved.
The Servlet Wizard in JDeveloper makes it easy for you
to write servlets. The wizard:
• Provides the doGet() and doPost() methodskeletons
• 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
Servlet Mapping
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 89/596
4-23 Copyright © 2004, Oracle. All rights reserved.
• 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/<context-
root>/servlet/< package>.<servlet>
– By using the mapped URL:
http://host:port/<context- root>/servlet/< mappedservletname>
• <context-root> is the mapping for the Web module
Servlet Mapping in JDeveloper
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 90/596
4-24 Copyright © 2004, Oracle. All rights reserved.
JDeveloper provides the standard J2EE model formapping 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>
Invoking a Servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 91/596
4-25 Copyright © 2004, Oracle. All rights reserved.
Specifying J2EE Web Module Settings
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 92/596
4-26 Copyright © 2004, Oracle. All rights reserved.
Creating a Connection to Oracle
Application Server 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 93/596
4-27 Copyright © 2004, Oracle. All rights reserved.
Deploying to OC4J
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 94/596
4-28 Copyright © 2004, Oracle. All rights reserved.
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 95/596
4-29 Copyright © 2004, Oracle. All rights reserved.
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
Practices 4-1, 4-2, and 4-3: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 96/596
4-30 Copyright © 2004, Oracle. All rights reserved.
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 Server10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 97/596
4-31 Copyright © 2004, Oracle. All rights reserved.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 98/596
Copyright © 2004, Oracle. All rights reserved.
Accessing the Database with Servlets
Objectives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 99/596
5-2 Copyright © 2004, Oracle. All rights reserved.
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
• Create a pool of connections
Review of JDBC
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 100/596
5-3 Copyright © 2004, Oracle. All rights reserved.
• JDBC is a standard interface for connecting to
relational databases from Java.
• The JDBC classes and interfaces are in thejava.sql package.
Querying in JDBC
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 101/596
5-4 Copyright © 2004, Oracle. All rights reserved.
Connect
Close
Query
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();
Process results
JDBC and Servlets
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 102/596
5-5 Copyright © 2004, Oracle. All rights reserved.
• 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 aproperties 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:
– Init ialize the database connection in the servlet’sinit() method (or retrieve from a pool).
– Close the database connection in the destroy()
method (or return to a pool).
Synchronizing Shared Resources
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 103/596
5-6 Copyright © 2004, Oracle. All rights reserved.
• 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();
}
Transaction Handling
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 104/596
5-7 Copyright © 2004, Oracle. All rights reserved.
Initialize Connection in the servlet’s init() method.
• Problems with transactions:
– The Connection object in the servlet’s 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.
Connection Pooling
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 105/596
5-8 Copyright © 2004, Oracle. All rights reserved.
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
Data Sources
• Data sources provide logical mappings of
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 106/596
5-9 Copyright © 2004, Oracle. All rights reserved.
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.• Data sources are published in the JNDI tree.
• Data sources come in different varieties.
Data Source Definition
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 107/596
5-10 Copyright © 2004, Oracle. All rights reserved.
• Global data sources are defined in theOC4J_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 <data-
sources> tag in the application.xml file.
OC4J_HOME/applications
myapp
application.xml
data-sources.xmlPoints to
data-sources.xml: Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 108/596
5-11 Copyright © 2004, Oracle. All rights reserved.
<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 >"
/>
Using Data Sources
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 109/596
5-12 Copyright © 2004, Oracle. All rights reserved.
To use a defined data source in a servlet:
1. Use the lookup method of the
javax.naming.Context class to retrieve thenamed 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) {… }
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 110/596
5-13 Copyright © 2004, Oracle. All rights reserved.
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
• Improve database performance by usingconnection pooling
Practice 5-1: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 111/596
5-14 Copyright © 2004, Oracle. All rights reserved.
This practice covers the following topics:
• Connecting to the database by using JDBC
• Retrieving database information and formatting itfor output in a servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 112/596
Copyright © 2004, Oracle. All rights reserved.
Using Advanced Techniques in Servlets
Objectives
Aft l ti thi l h ld b bl t d
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 113/596
6-2 Copyright © 2004, Oracle. All rights reserved.
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 f ilters
• Define event l isteners
Overview
R t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 114/596
6-3 Copyright © 2004, Oracle. All rights reserved.
Servlet
Error handling
Client Web
browser
Request
getCookies()
getHeader()
Response
setHeader()
addCookie()
HTTP Headers
Headers are HTTP details that are passed between
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 115/596
6-4 Copyright © 2004, Oracle. All rights reserved.
• 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.
Request Headers
Additional request headers include the following:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 116/596
6-5 Copyright © 2004, Oracle. All rights reserved.
Additional request headers include the following:
Accept Specifies MIME types that the browser
supports
Accept-
Language
Specifies the browser’s 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 therequest, for checking browser features
Sending a Response
There are three aspects to sending a response:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 117/596
6-6 Copyright © 2004, Oracle. All rights reserved.
There are three aspects to sending a response:
• Sending HTTP headers
• Sending a status code (an integer denoting thenature of response)
• Sending multimedia content
Response Headers
• The HttpServletResponse class is used to send
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 118/596
6-7 Copyright © 2004, Oracle. All rights reserved.
• The HttpServletResponse class is used to send
headers.
• You have seen an example of setting headerinformation: setContentType("text/html");.
• Other headers are set by using the setHeader()
method.• Do not confuse HTTP headers with the HEAD tag in
HTML pages.
Setting Status Codes
• If a servlet does not specify a status code, thenthe Web server sends the default status code
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 119/596
6-8 Copyright © 2004, Oracle. All rights reserved.
int pageVersion =Integer.parseInt(req.getParameter("pageVersion"));
if (pageVersion >= currentVersion){
response.setStatus(response.SC_NO_CONTENT);
}else{//Send original page
}
the Web server sends the default status code
(200).
• You can explicitly set a status code by using thesetStatus() method.
Example:
• Assume that the randomSite() method generates
Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 120/596
6-9 Copyright © 2004, Oracle. All rights reserved.
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException{
String tempSite = this.randomSite();
// implementation not shownres.setStatus(res.SC_MOVED_TEMPORARILY);
res.setHeader("Location", tempSite);
}
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.
Sending Multimedia Content
• Multimedia content usually contains binary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 121/596
6-10 Copyright © 2004, Oracle. All rights reserved.
Multimedia content usually contains binary
response data.
• Use the getOutputStream() method instead ofthe 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.
Cookies
• A cookie is a name or value pair sent by a servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 122/596
6-11 Copyright © 2004, Oracle. All rights reserved.
A cookie is a name or value pair sent by a servlet
to a browser in the header.
• Cookies are persistent (the information sent isstored on the client, to be retrieved later).
• Cookies are often used to obtain state information,
such as a username or preference.
Setting Cookies
• Use the Cookie() constructor to create a new
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 123/596
6-12 Copyright © 2004, Oracle. All rights reserved.
Cookie userCookie = new Cookie ("user", "fred");userCookie.setMaxAge(60*60); //one hour
response.addCookie(userCookie);
()
cookie.
• Use the addCookie() method in theHttpServletResponse class to add and send the
cookie to a browser.
Retrieving Cookies
Use the getCookies() method to fetch an array of
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 124/596
6-13 Copyright © 2004, Oracle. All rights reserved.
g () y
Cookie objects.
Cookie[] cookies = request.getCookies();
if (cookies != null) {
String readValue;
for (int i = 0; i < cookies.length; i++)
readValue = cookies[i].getValue();…
About State Preservation
• Usually, the servlet engine instantiates the servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 125/596
6-14 Copyright © 2004, Oracle. All rights reserved.
y, g
only once.
• Any number of requests can be handled by thesame 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.
public class StateServlet extends HttpServlet {
State Preservation: Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 126/596
6-15 Copyright © 2004, Oracle. All rights reserved.
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>");
}}
ServletContext
• The ServletContext interface defines the servlet
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 127/596
6-16 Copyright © 2004, Oracle. All rights reserved.
within the Web application.
• Methods in ServletContext allow for retrievingthe MIME type of a file, dispatching requests to
other servlets, or writing to a log file.
RequestDispatcher
• To forward the request to another servlet or JSP,
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 128/596
6-17 Copyright © 2004, Oracle. All rights reserved.
use the RequestDispatcher interface:getServletContext().getRequestDispatcher(String
url).
• RequestDispatcher contains two methods:
forward() and include().
– Use the forward() method to transfer control tothe associated URL.
• These methods take HttpServletRequest and
HttpServletResponse as arguments.
RequestDispatcher: Example
public void doPost(HttpServletRequest request,
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 129/596
6-18 Copyright © 2004, Oracle. All rights reserved.
p c o d do ost( ttp e et eq est eq est,
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) ;}
}
Servlet Filters
Filters dynamically change the content or header of a
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 130/596
6-19 Copyright © 2004, Oracle. All rights reserved.
request or response. A fi lter is used to:
• Intercept a request before a servlet is called• Modify the request, response, and header values
• Optionally, customize the response
Using Filters
The javax.servlet.Filter interface is implemented
fil d i h h d
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 131/596
6-20 Copyright © 2004, Oracle. All rights reserved.
to use a fi lter, and contains three methods:
• void init(FilterConfig)• void doFilter(ServletRequest,
ServletResponse, FilterChain)
• void destroy()
doFilter() Method
The doFilter() method:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 132/596
6-21 Copyright © 2004, Oracle. All rights reserved.
• Examines the request header
• Modifies request headers by wrapping therequest object
• Modifies the response by wrapping the response
object• Invokes the next fil ter in the filter chain
Using Filters
import javax.servlet.*; import javax.servlet.Filter;
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 133/596
6-22 Copyright © 2004, Oracle. All rights reserved.
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(){}
}
Configuring Filters
To use a servlet filter, the web.xml deployment
descriptor is modified to include the <filter> tag:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 134/596
6-23 Copyright © 2004, Oracle. All rights reserved.
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>
Application Lifecycle Events
• Lifecycle Events are a new feature of the Servlet
2 3 API
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 135/596
6-24 Copyright © 2004, Oracle. All rights reserved.
2.3 API.
• Event listeners are used to check for statechanges.
• There are two types of events: ServletContext
and HttpSession.
• Event listeners can be notified when objects are
initialized, destroyed, or when their attributes
change.
ServletContext Events
Implement one or more ServletContext listener
interfaces to respond to ServletContext events The
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 136/596
6-25 Copyright © 2004, Oracle. All rights reserved.
interfaces to respond to ServletContext events. The
following methods are invoked when aServletContext event occurs:
• contextInitialized()
• contextDestroyed()
• attributeAdded()
• attributeRemoved()
• attributeReplaced()
HttpSession Events
Implement one or more HttpSession listener
interfaces to respond to HttpSession events The
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 137/596
6-26 Copyright © 2004, Oracle. All rights reserved.
interfaces to respond to HttpSession events. The
following methods are invoked when an HttpSession
event occurs:
• sessionCreated()
• sessionDestroyed()
• attributeAdded()
• attributeRemoved()
• attributeReplaced()
Example of an Event Listener
public class ConnectionManager implements
S l tC t tList {
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 138/596
6-27 Copyright © 2004, Oracle. All rights reserved.
ServletContextListener {
public voidcontextInitialized(ServletContextEvent
event) {
Connection conn = // create connection
event.getServletContext().setAttribute("conn",
conn);
}
Error Handling
• Java prevents a servlet from unintentionally or
maliciously damaging the servlet engine
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 139/596
6-28 Copyright © 2004, Oracle. All rights reserved.
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 notany other exceptions (for example,InterruptedException).
Summary
In this lesson, you should have learned how to:
• Send headers and other content to the client
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 140/596
6-29 Copyright © 2004, Oracle. All rights reserved.
• Send headers and other content to the client
• Use fil ters to modify servlet response• Handle state preservation
• Handle errors that might arise during the
execution of your servlet
Practices 6-1 and 6-2: Overview
These practices cover the following topics:
• Creating a servlet that uses cookies
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 141/596
6-30 Copyright © 2004, Oracle. All rights reserved.
• Creating a servlet that uses cookies
• Using servlet filters to manipulate headers
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 142/596
Copyright © 2004, Oracle. All rights reserved.
Maintaining State in J2EE Applications
Objectives
After completing this lesson, you should be able to do
the following:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 143/596
7-2 Copyright © 2004, Oracle. All rights reserved.
g
• Maintain persistent activity from clients by using abrowser
• Use the HttpSession object
• Describe state preservation
First request
Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 144/596
7-3 Copyright © 2004, Oracle. All rights reserved.
First request
Chris
Second request
Chris
First request
Michelle
Servlet
Session Basics
• The HTTP protocol is stateless.
• The session mechanism guarantees that the
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 145/596
7-4 Copyright © 2004, Oracle. All rights reserved.
The session mechanism guarantees that the
object that serves the client knows which clienthas made a request.
• User requests from the same browser are
considered to be from the same client.
Session Basics
• Options for identifying the client: Cookies, URLrewriting, hidden fields, HttpSession
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 146/596
7-5 Copyright © 2004, Oracle. All rights reserved.
• 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.)
Threading
Multithreaded model Single-threaded model
Client 1
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 147/596
7-6 Copyright © 2004, Oracle. All rights reserved.
Servlet instance 1
Servlet instance 2
Client 1
Client 2
Client 1
Client 2
Both clients using
unique sessions, butsharing the same
servlet instance
Both clients using
unique sessions andunique instances
URL Rewriting
• URL rewriting:
– Every URL that is accessed by the client is rewritten
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 148/596
7-7 Copyright © 2004, Oracle. All rights reserved.
so that it has the session ID.
– Use the encodeURL() method to re-create the path
dynamically.
• URL rewriting is used when a client turns off
cookie support in the browser.
HttpSession
• The unique identity for the client is anHttpSession object.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 149/596
7-8 Copyright © 2004, Oracle. All rights reserved.
• The object is created by using the getSession()method of the HttpRequest object.
• Any servlet that responds to a client request cancreate this object.
• An object can be potentially shared across several
servlets. (Every servlet within an application canidentify with this client.)
HttpSession session = req.getSession(true);
Session Objects
• With session objects, you can:
– Put items into the object (values persist across
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 150/596
7-9 Copyright © 2004, Oracle. All rights reserved.
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
public void doGet(…)… {
response.setContentType("text/html");
PrintWriter out = response getWriter();
Session-Based Page Counter
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 151/596
7-10 Copyright © 2004, Oracle. All rights reserved.
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 withthe id of " + "<b>" + sessionid + "</b> is: " +
sessionCount);
}
Session Life Cycle
• A session can expire automatically, or you can
explicitly invalidate a session.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 152/596
7-11 Copyright © 2004, Oracle. All rights reserved.
Date dayAgo = new Date(
System.currentTimeMillis() - 24*60*60*1000);
Date hourAgo = new Date(…) // an hour agoDate created = new Date(
session.getCreationTime());
Date accessed = new Date(…)
if (created.before(dayAgo)||
accessed.before(hourAgo)) {
session.invalidate(); session = … //create new
}
• The HttpSession object gets invalidated when asession expires.
Session Tracking in OC4J
• J2EE server vendors handle session tracking in
different ways.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 153/596
7-12 Copyright © 2004, Oracle. All rights reserved.
• 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
(modif ied in the deployment descriptor)
Sessions and Events
When a servlet stores an object in a session orremoves an object from a session, the session checks
whether that object implements theHttpSessionBindingListener interface If it does
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 154/596
7-13 Copyright © 2004, Oracle. All rights reserved.
HttpSessionBindingListener interface. If it does,
then the servlet notifies the object that it has been
either:
• Bound to the session (by calling the object’s
valueBound() method, which is a good place forinitializing client-specific resources)
Or
• Unbound from a session (by calling the object’svalueUnbound() method, which is a good place
for releasing resources)
Sessions and Events
• An object is bound to a session after the object ispassed into the session.setAttribute()
method
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 155/596
7-14 Copyright © 2004, Oracle. All rights reserved.
method.
• An object is unbound from a session:
– After the object is removed by using thesession.removeAttribute() method
– When a session is invalidated
Sessions and Events
To use the event mechanism, you must perform the
following steps:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 156/596
7-15 Copyright © 2004, Oracle. All rights reserved.
1. Create a class that implements theHttpSessionBindingListener interface.
2. Instantiate the class.
3. Insert the instantiated object into theHttpSession object by using the
setAttribute() method.
public class EventObject
implements HttpSessionBindingListener {
Sessions and Events
Example:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 157/596
7-16 Copyright © 2004, Oracle. All rights reserved.
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
}
}
Creating Distributable Applications
Applications are deployed as “ distributable” byspecifying the <distributable/> tag in the web.xml
fi le These applications should be developed to run in
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 158/596
7-17 Copyright © 2004, Oracle. All rights reserved.
fi le. 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), theinformation 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.
Summary
In this lesson, you should have learned how to:
• Instantiate the HttpSession object
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 159/596
7-18 Copyright © 2004, Oracle. All rights reserved.
• Use the HttpSession object• Implement the HttpSessionBindingListener
interface
Practice 7-1: Overview
This practice covers the following topics:
• Creating an HttpSession object
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 160/596
7-19 Copyright © 2004, Oracle. All rights reserved.
• Tracking an order based on the HttpSessionobject
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 161/596
Copyright © 2004, Oracle. All rights reserved.
Creating the Web Tier: JavaServer Pages
Objectives
After completing this lesson, you should be able to do
the following:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 162/596
8-2 Copyright © 2004, Oracle. All rights reserved.
• 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
JavaServer Pages
JSP
Connects toRequest
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 163/596
8-3 Copyright © 2004, Oracle. All rights reserved.
Generates
Dynamic content
EJB
ClientDatabase
Response
Comparing Servlets and JSPs
Servlets:
• Are Java programs
with embedded
JavaServer Pages:
• Are HTML pages
with embedded Java
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 164/596
8-4 Copyright © 2004, Oracle. All rights reserved.
with embedded
HTML
• Generate dynamic
content
• Do not separate
static and dynamic
content
with embedded Java
code or they can be
pure XML
• Generate dynamic
content
• Separate static and
dynamic content
Invoking JSPs
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 165/596
8-5 Copyright © 2004, Oracle. All rights reserved.
HTML
JSP
Invoke
Servlet
JSP
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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 166/596
8-6 Copyright © 2004, Oracle. All rights reserved.
<body><h2> The current time is: </h2>
<p> <%= new java.util.Date() %> </p>
</body>
</html>
The Date Servlet
...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 167/596
8-7 Copyright © 2004, Oracle. All rights reserved.
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();}
...
Automated JSP Features
• A JSP is automatically converted into a servlet the
first time it is invoked:
– Java source fi les are generated.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 168/596
8-8 Copyright © 2004, Oracle. All rights reserved.
– 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.)
JSP Life Cycle
J2EE container
1First
time
YesOC4J
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 169/596
8-9 Copyright © 2004, Oracle. All rights reserved.
http://host/date.jspCreate servletdate.java
Compile servletdate.class
Servlet l ife cycle
2
3
No
Basic JSP Elements
A JSP contains three main elements:
• Text elements
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 170/596
8-10 Copyright © 2004, Oracle. All rights reserved.
• Directives• Scripting elements
– Declarations
– Expressions
– Scriptlets
Declarations
• Are used to define methods or variables
• Begin with the sequence <%!
E d ith th
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 171/596
8-11 Copyright © 2004, Oracle. All rights reserved.
• 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"; %>
Expressions
• Begin with the sequence <%=
• Contain Java expressions that are evaluated and
inserted into the servlet’s output
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 172/596
8-12 Copyright © 2004, Oracle. All rights reserved.
• End with the sequence %>
• Do not end with a semicolon
<%= i+1 %><%= a + b %>
<%= new java.util.Date() %>
1
2
Scriptlets
• Begin with the sequence <%
• Contain a block of Java code that is executed
every time a request is made
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 173/596
8-13 Copyright © 2004, Oracle. All rights reserved.
• End with the sequence %>
<% if (i<3)
out.print("i<3");if (i==3)
out.print("i==3");
else
out.print("i>3");%>
Implicit Objects
There are eight implicit objects, also known as
predefined variables, in JSP:
• request • application
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 174/596
8-14 Copyright © 2004, Oracle. All rights reserved.
• response
• session
• out
• config
• pageContext
• page
Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 175/596
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 <%@
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 176/596
8-16 Copyright © 2004, Oracle. All rights reserved.
• End with the sequence %>
• Are of the following types:
– page
– include
– taglib
include: Example
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 177/596
8-17 Copyright © 2004, Oracle. All rights reserved.
page Directive
You can define the following attributes by using the page directive:
• import • extends
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 178/596
8-18 Copyright © 2004, Oracle. All rights reserved.
• contentType
• isThreadSafe
• session
• buffer
• autoflush
• info
• errorPage
• isErrorPage
• language
JSP and JavaBeans
package lesson08;
import java.lang.*;
import java.util.*;
public class LuckyNumberBean {i t i t l k N
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 179/596
8-19 Copyright © 2004, Oracle. All rights reserved.
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;
}
}
Using JavaBeans with JSP
Accessing JavaBeans with the <jsp:useBean> tag:
<jsp:useBean id="myBean" scope="session"
class="lesson08 LuckyNumberBean" />
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 180/596
8-20 Copyright © 2004, Oracle. All rights reserved.
class= lesson08.LuckyNumberBean />
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 181/596
Accessing and Setting Bean Property
• Accessing bean property:
<jsp:getProperty name="myBean"
property=“luckyNum" />
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 182/596
8-22 Copyright © 2004, Oracle. All rights reserved.
• Setting bean property:
<jsp:setProperty name="myBean"
property=“luckyNum" value="10" />
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 183/596
8-23 Copyright © 2004, Oracle. All rights reserved.
• Can be processed directly by the JSP container
• Can be used with XML development tools
Traditional Syntax Versus XML Syntax
Traditional: XML:
• No root element
di ti
• <jsp:root> is the root
element• j di ti
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 184/596
8-24 Copyright © 2004, Oracle. All rights reserved.
• page directive<%@ page %>
• Declaration tag<%! %>
• Expression tag<%= expression %>
• Scriptlet<% %>
element• <jsp:directive.
page />
• <jsp:declaration>
</jsp:declaration>
• <jsp:expression>
</jsp:expression>
• <jsp:scriptlet>
</jsp:scriptlet>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 185/596
Creating JSPs Visually
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 186/596
8-26 Copyright © 2004, Oracle. All rights reserved.
JSP Tag Insight
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 187/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 188/596
8-28 Copyright © 2004, Oracle. All rights reserved.
• Describe the JSP life cycle
• Use JSP elements and implicit objects
• Develop JSPs with declarations, expressions, and
scriptlets
• Use JavaBeans with JSP
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 189/596
8-29 Copyright © 2004, Oracle. All rights reserved.
Us g Ja a ea to ca cu ate a equa d scou t o
the total amount of purchase
• Creating a JSP that displays product_id ,
product_name, and price in the form of a table
Modularizing JavaServer PagesD l t ith T
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 190/596
Copyright © 2004, Oracle. All rights reserved.
g gDevelopment with Tags
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)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 191/596
9-2 Copyright © 2004, Oracle. All rights reserved.
g g ( )
• Use the customizable Component Palette for JSP
• Develop a JSP using the JSP Standard Tag Library
(JSTL)
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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 192/596
9-3 Copyright © 2004, Oracle. All rights reserved.
• Tags are useful for defining custom actions such
as:
– Accessing a database – Defining recurring tasks
– Sending e-mail
• Collections of tags are grouped into JAR filescalled Tag Libraries.
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 )
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 193/596
9-4 Copyright © 2004, Oracle. All rights reserved.
– 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 theweb.xml file.
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();
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 194/596
9-5 Copyright © 2004, Oracle. All rights reserved.
p p g g ();
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);}
}
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:
The tag library’s version<tlibversion>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 195/596
9-6 Copyright © 2004, Oracle. All rights reserved.
Specifies the class for the individual tag<tagclass>
Set to empty, tagdependent, or JSP<bodycontent>
Documentation regarding the library<info>
Identifies the tag library location<uri>
A default name for the library<shortname>
The JSP specification version for the library<jspversion>
g y
Using a Custom Tag
<html>
<head>
<%@ taglib uri="webapp/taglib.tld"
prefix="mytags" %></head>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 196/596
9-7 Copyright © 2004, Oracle. All rights reserved.
</head>
<body>
<h2>The following output is from the
HelloWorldTag:</h2>
<p>
<mytags:hellotag/>
</p>
</body>
</html>
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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 197/596
9-8 Copyright © 2004, Oracle. All rights reserved.
<tag> <name>hellotag</name>
<tagclass>HelloWorldTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>custName</name>
<required> true</required><rtexprvalue>true</rtexprvalue>
</attribute> </tag>
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 Ri ht l i k th tld fi l i S t N i t d
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 198/596
9-9 Copyright © 2004, Oracle. All rights reserved.
2. Right-cl ick the .tld fi le in System Navigator and
select “ Add Tag” to create a tag handler.
3. Right-cl ick the .java file in System Navigator andselect “ Add Attribute” or “ Add Scripting Variable”
as necessary.
4. Add the tag library to the component palette.
Tag Libraries in JDeveloper
• Tag libraries are viewed in JDeveloper by usingthe component palette.
• Select View > Component Palette to enable the
palette in the integrated development environment
(IDE).
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 199/596
9-10 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 200/596
9-11 Copyright © 2004, Oracle. All rights reserved.
3. Name the page for display.
Registering Tag Libraries
4. Select Tools > Manage Libraries.
5. Add the JAR and TLD files to the list of JSP Tag
Libraries.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 201/596
9-12 Copyright © 2004, Oracle. All rights reserved.
Registering Tag Libraries
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 202/596
9-13 Copyright © 2004, Oracle. All rights reserved.
Using Tag Insight
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 203/596
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 expressionlanguage support
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 204/596
9-15 Copyright © 2004, Oracle. All rights reserved.
language support
• Parsing and transforming XML documents
• Formatting and parsing strings, dates, andcurrencies for internationalization
• Database access and data manipulation
Core Tag Library
The Core library of JSTL is used for typical JSPactions.
• Reduces the need for scriptlet tags in a JSP
• Contains four types of tags: – Generic (sets variables and display results of
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 205/596
9-16 Copyright © 2004, Oracle. All rights reserved.
( p y
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" %>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 206/596
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" />
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 207/596
9-18 Copyright © 2004, Oracle. All rights reserved.
• The value attribute of the <c:set> tag usesExpression Language (EL).
<c:out value= Hello World />
<c:set var="name" value="${param.username}"
scope="session" /> Welcome <c:out value="${name}"default="guest" />
Expression Language
JSTL tags can contain Expression Language (EL)
within attr ibutes. Expression Language:
• Is a simpler way of writing an expression in JSPs
• Accesses object properties and collection
elements using dot notation
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 208/596
9-19 Copyright © 2004, Oracle. All rights reserved.
elements using dot notation
• Has access to implicit objects
• Uses a dollar sign and braces to create anexpression: ${expression}
<c:set var="name" value="${param.username}"
scope="session" /> Welcome <c:out value="${name}"default="guest" />
Using Iteration Tags
Use iteration tags to iterate over blocks of code:
<table><tr>
<c:forEach var="allparams" items="${param}" >
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 209/596
9-20 Copyright © 2004, Oracle. All rights reserved.
<c:forEach var allparams items ${param} ><c:out value="${allparams.key}" /></c:forEach><tr><table>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 210/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 211/596
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 othertags similar to the core tag library, in addition to:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 212/596
9-23 Copyright © 2004, Oracle. All rights reserved.
– <x:parse> : Parses a specified XML document
– <x:transform> : Creates a formatted page from anXML 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" %>
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:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 213/596
9-24 Copyright © 2004, Oracle. All rights reserved.
p q g
<%@ taglib uri="http://java.sun.com/jstl/sql"
prefix="sql" %>
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> tagsOr
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 214/596
9-25 Copyright © 2004, Oracle. All rights reserved.
• 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" />
Querying Using SQL Tags
<sql:query datasource="jdbc/oeCoreDS"var="customers" maxRows="10">
SELECT * FROM customers
</sql:query><table>
<c:forEach var="row"
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 215/596
9-26 Copyright © 2004, Oracle. All rights reserved.
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>
Inserting, Updating, and Deleting Data
Use the <sql:update> tag to insert, update, or delete
data. For example:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 216/596
9-27 Copyright © 2004, Oracle. All rights reserved.
<sql:update var="rows">
UPDATE customers SET account_mgr_id=147 WHERE account_mgr_id=149</sql:update><c:out value="${rows}"/> Rows Updated.
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
j til L l t f t d t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 217/596
9-28 Copyright © 2004, Oracle. All rights reserved.
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" %>
Internationalization Concepts
There are three main considerations for
internationalizing an application:
• Locale (geographical or poli tical region)
• Resource bundle (set of paired messages andkeys)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 218/596
9-29 Copyright © 2004, Oracle. All rights reserved.
• Basename (identifier for a resource bundle)
Internationalizing Strings
• To look up a message in a resource bundle, usingthe current locale, specify the key attribute in the
<fmt:message> tag:
<fmt:message key="Hello" />
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 219/596
9-30 Copyright © 2004, Oracle. All rights reserved.
• Alternatively, specify the basename to use withthe <fmt:bundle> tag:
<fmt:bundle basename="login">
<fmt:message key="Hello" /></fmt:bundle>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 220/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 221/596
9-32 Copyright © 2004, Oracle. All rights reserved.
Formatting Numbers and Dates
To reverse the formatting that is executed by theformat 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 222/596
9-33 Copyright © 2004, Oracle. All rights reserved.
or a locale-specific manner
– Specify the way the date string should be formattedby using the pattern or parseLocale attributes.
Transforming XML Documents
XML uses XSLT stylesheets to transform data. You canaccomplish the same by using the <x:transform>
tag:
<c:import url="Customers.xml" var="xml"/>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 223/596
9-34 Copyright © 2004, Oracle. All rights reserved.
<c:import url="customerDisplay.xsl"
var="MyStyleSheet" /><x:transform xml="${xml}"
xslt="${MyStylesheet}" />
JSTL in JDeveloper
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 224/596
9-35 Copyright © 2004, Oracle. All rights reserved.
output of the tag, as with any
other JSP element.
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 225/596
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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 226/596
9-37 Copyright © 2004, Oracle. All rights reserved.
Communicating in J2EE
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 227/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 228/596
10-2 Copyright © 2004, Oracle. All rights reserved.
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
Overview of RMI
Remote Method Invocation (RMI) is a framework forexecuting distributed objects in Java. RMI has thefollowing characteristics:
• It uses RPC-like communication mechanisms.
• It is designed for client applications to invokeremote object methods, as easily as calling localmethods
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 229/596
10-3 Copyright © 2004, Oracle. All rights reserved.
methods.
• It comprises the following components: – Remote interface
– Implementation class
– Server application/class – Client application/class
– Stub (proxy) and skeleton classes
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.3specification requires support for the RMI-IIOP
protocol as the type of communication used
between the client and server object
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 230/596
10-4 Copyright © 2004, Oracle. All rights reserved.
between the client and server object.
• EJBs have a remote interface and implementationclasses, which conform to RMI semantics:
– They implement a remote interface.
– Methods throw the java.rmi.RemoteException. – Object parameters or return values must be
serializable.
Communication in a J2EE Environment
Marshaled data
J2EE server
Naming
Creation
Client
Interface
1
2
3
45
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 231/596
10-5 Copyright © 2004, Oracle. All rights reserved.
Local call
Network protocol(Java RMI) Server
object
Marshaled data
Interface
Stub6
7
Skeleton
How Clients Locate a DistributedComponent
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 232/596
10-6 Copyright © 2004, Oracle. All rights reserved.
service.
• Clients use the Java Naming and Directory
Interface (JNDI) API to locate a remote object by a
name.
Java Naming and DirectoryInterface (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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 233/596
10-7 Copyright © 2004, Oracle. All rights reserved.
LDAPRMI registry
Name and directory services
ClientJNDI API
JNDI SPI
COS Naming
J2EE Container and JNDI Interface
• The container implements the J2EE environmentand makes the services and resources available
through a JNDI interface.
• The JNDI service obtains names from theExtensible Markup Language (XML) files and holds
them in memory.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 234/596
10-8 Copyright © 2004, Oracle. All rights reserved.
• 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.
Naming Service
A naming service allows clients or objects to locateeach 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 235/596
10-9 Copyright © 2004, Oracle. All rights reserved.
• Using a directory service with a hierarchicalstructure 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)
JNDI Terminology
Init ial context
Contextenv
jdbc ejbSub-context
Namespace
JNDI client
ormi://host/AppCtx
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 236/596
10-10 Copyright © 2004, Oracle. All rights reserved.
OracleDS oeCoreDS Employee Cart Atomicnames
Objects
Binding
java:comp/env/jdbc/OracleDS Compound name
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 thejava.naming.Context interface
• The javax.naming.Context interface:
P id th d t bi d t bj t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 237/596
10-11 Copyright © 2004, Oracle. All rights reserved.
– 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 theinit ial context or a subcontext
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 callthe lookup() method to get the reference to the
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 238/596
10-12 Copyright © 2004, Oracle. All rights reserved.
local home interface object. Example:DepartmentLocalHome home =
(DepartmentLocalHome) ic.lookup(
"java:comp/env/ejb/Dept");
• lookup() returns an Object type that should becast to a desired type.
Getting the JNDI InitialContext
• When OC4J starts, a JNDI context is constructedfor 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 environmentproperties to obtain the InitialContext:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 239/596
10-13 Copyright © 2004, Oracle. All rights reserved.
properties to obtain the InitialContext:
– INITIAL_CONTEXT_FACTORY
– PROVIDER_URL
– SECURITY_PRINCIPAL
– SECURITY_CREDENTIAL
– dedicated.rmicontext
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 theapplication EAR file, as part of the application-
client.jar file
– An environment specified explicitly in a Hashtable
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 240/596
10-14 Copyright © 2004, Oracle. All rights reserved.
p p y
• 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 byremote clients to execute code in a remote J2EE
container
Initial Context Factories
• There are three JNDI init ial context factories: – ApplicationClientInitialContextFactory
– ApplicationInitialContextFactory
– RMIInitialContextFactory• An initial context factory is used to construct an
InitialContext object.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 241/596
10-15 Copyright © 2004, Oracle. All rights reserved.
• The initial context factory class name is the stringvalue for the INITIAL_CONTEXT_FACTORY JNDI
property.
lookup() Method
• The lookup() method obtains a reference to therequired resource.
• To reference a local resource, pass the URL withthe object name as parameter:java:comp/env/subContext/resourceName
Examples:
– java:comp/env/ejb/Dept
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 242/596
10-16 Copyright © 2004, Oracle. All rights reserved.
– jdbc/oeCoreDS• Retrieve a reference to target EJB by using:
– The actual bean name specif ied in the <ejb-name>element or the <ejb-ref-name> element of ejb-
jar.xml – The logical bean name specified in the <ejb-ref-
name> element of application-client.xml
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 243/596
Obtaining a Reference to aRemote 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);
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 244/596
10-18 Copyright © 2004, Oracle. All rights reserved.
3. Obtain a reference to a resource by usinglookup():Object obj = ic.lookup("Dept");
4. Cast the reference to the returned Object type:
DepartmentHome dh = (DepartmentHome)PortableRemoteObject.narrow(obj,DepartmentHome.class);
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 theclient
• Setting JNDI properties:
– Supply the properties through the
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 245/596
10-19 Copyright © 2004, Oracle. All rights reserved.
Supply the properties through the
jndi.properties fi le. The path of the file must bein the CLASSPATH, or JAVA_HOME/lib.
– Supply properties in the client code by using aHashtable.
Setting JNDI Environment Properties
Using the jndi.properties file:
• Factory: Initial context factory to be usedjava.naming.factory.initial =
com.evermind.server.
ApplicationClientInitialContextFactory
• Location: URL used to look up the objectsjava.naming.provider.url =
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 246/596
10-20 Copyright © 2004 Oracle All rights reserved
ormi://<hostname>:23891/<application-name>
• Security: Valid credentials of the client to this
containerjava.naming.security.principal=<username>
java.naming.security.credentials=< password >
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 247/596
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");
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 248/596
10-22 Copyright © 2004 Oracle All rights reserved
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);
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 249/596
10-23 Copyright © 2004 Oracle All rights reserved
following example:
• Port used is the HTTP server port (by default 80)
Hashtable env = new Hashtable();
env.put(Context.PROVIDER_URL,
"http:ormi://<host>:< port>/Application");
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 250/596
Configuring Environment Variables
• Environment variables are defined in the <env-
entry> 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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 251/596
10-25 Copyright © 2004 Oracle All rights reserved
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>500</env-entry-value>
</env-entry>
InitialContext ic = new InitialContext(); Client
Integer minBal = (Integer)
ic.lookup("java:comp/env/minBalance");
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.
<env-entry> J2EE DD
<env-entry-name>minBalance</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 252/596
10-26 Copyright © 2004 Oracle All rights reserved
<env-entry-value>500</env-entry-value>
</env-entry>
<env-entry-mapping OC4J DD
name="minBalance">300
</env-entry-mapping>
• Specify an EJB reference by using an <ejb-ref>
element in a J2EE client application deploymentdescriptor:<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>
Specifying an EJB Reference
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 253/596
10-27 Copyright © 2004 Oracle All rights reserved
• 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 resolvesit in its JNDI tree.
Configuring EJB References
• The <ejb-ref> element of a client J2EEdeployment 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 254/596
10-28 Copyright © 2004 Oracle All rights reserved
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
Configuring Data Source References
• Create an environment reference to each datasource that is used by a client through a JNDI
reference.
• These references can be used only by the J2EEapplication that defines these data sources.
• The JNDI name is defined in the ejb-location
attribute of a <data-source> element in the
fil
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 255/596
10-29 Copyright © 2004 Oracle All rights reserved
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 namein the OC4J-specific deployment descriptor.
Configuring Data Source References
<data-sources><data-source
class="com.evermind.sql.DriverManagerDataSource"name="OracleDS"location="jdbc/OracleCoreDS" ...ejb-location="jdbc/OracleDS" ... />
</data-sources>
1. Define in data-sources.xml.
<resource-ref>
<res-ref-name>jdbc/oeCoreDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
/
JNDI Name2. Reference in J2EE Deployment Descriptor.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 256/596
10 30 Copyright © 2004 Oracle All rights reserved
<resource-ref-mapping
name="jdbc/oeCoreDB"
location= "jdbc/OracleDS" />
<res-auth>Application</res-auth>
<resource-ref>
Logical Name
3. Map in OC4J-specific deployment descriptor.
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
C fi th JNDI d i t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 257/596
10 31 Copyright © 2004 Oracle All rights reserved
• Configure the JNDI names and environmentproperties, such as environment variables, EJB
references, and data sources
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 258/596
10 32 Copyright © 2004 Oracle All rights reserved
Creating the Business Tier:
Enterprise JavaBeans
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 259/596
Copyright © 2004 Oracle All rights reserved
Objectives
After completing this lesson, you should be able to dothe following:
• Define an Enterprise JavaBean
• Describe the Enterprise JavaBeans (EJB)architecture
• Describe the types of EJBs and when they
are used
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 260/596
11 2 Copyright © 2004 Oracle All rights reserved
• Explain EJB interfaces
• Define the steps to deploy an EJB to Oracle
Application Server 10g
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 261/596
11 3 Copyright © 2004 Oracle All rights reserved
• Execute in a container that provides services suchas support for transactions, persistence, and
access control for the beans
When to Use EJBs
When developing a J2EE application, decide whetherto use EJBs based on the following requirements:
• The applications are complex and would benefit
from the system-level services that are providedby an EJB container.
• The applications must be portable and scalable.
• The applications must be accessed by different
types of clients
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 262/596
11 4 Copyright © 2004 Oracle All rights reserved
types of clients.
Types of EJBs
EJB Type Purpose
Session Beans Performs a task for a client
Enti ty Beans Represents a business object
that exists in a database
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 263/596
11 5 Copyright © 2004 Oracle All rights reserved
Message-Driven Beans Receives asynchronous Java
Message Service (JMS)
messages
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 notmaintain client-specific state
• Stateful Session Beans (SFSBs) – Conversation with one client that may invoke many
methods
– Business processes that span multiple methodrequests thus maintaining state
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 264/596
11 6 Copyright © 2004 Oracle All rights reserved
requests, thus maintaining state
EJB container
Client 1
Client 2
Pool of SLSBs
EJB container
Client 1
Client 2
SFSBs
Entity BeansEntity beans represent a business object in thedatabase. They are:
• Sharable across multiple clients• Uniquely identifiable through a primary key
• Persistent—the 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 thecontainer.
– The bean developer specifies the persistent fields( )
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 265/596
11 7 Copyright © 2004 Oracle All rights reserved
The bean developer specifies the persistent fields.• Bean-managed persistence (BMP) beans:
– The state of the bean is maintained by the beanitself.
– The bean developer writes the logic to managepersistence by using Java Database Connectivity(JDBC).
Message-Driven Beans
• Provide a facil ity for asynchronouscommunication
• Exist within a pool, and receive and processincoming messages from a JMS queue or topic
• Are invoked by the container to handle eachincoming message from the queue or topic
• Are similar to stateless session beans
EJB t iJMS queue
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 266/596
11 8 Copyright © 2004 Oracle All rights reserved
Clients
EJB container
Pool of MDBs
JMS queue
EJB Architecture
EJB client
EJB server
Database
EJB container
Remote/local
object
Home/local home
object
Remote/local
interface
Home/localhome
interface EJBClass
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 267/596
11 9 C i ht © 2004 O l All i ht d
Enterprise ServicesNaming, Transaction, Security,
Messaging
Deploymentdescriptor
j
EJB Server
• Manages the EJB container • Provides a deployment and execution platform for
EJB components
• Provides system services to containers that inturn provide services to beans:
– Transaction services
– JNDI naming services
• Can provide vendor specific features such as
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 268/596
11 10 C i ht © 2004 O l All i ht d
• Can provide vendor-specific features such as
connection pooling
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 EJBclasses through well-defined interfaces
EJB container
home/localhome
Home/localhome
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 269/596
11 11 C i ht © 2004 O l All i ht d
ClientEJB
class
objectinterfaceContainer
generated
remote/local
object
Remote/
localinterface
Services Provided by the EJB Container
• Life-cycle management• Bean instance pooling
• Client state management
• Database connection pooling• Declarative transaction management
• Security
• Persistence
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 270/596
11 12 C i ht © 2004 O l All i ht d
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 271/596
EJB Interfaces and Classes
• Interfaces: – Remote interface/Local interface
– Home interface/Local home interface
• Classes: – Bean class
– Primary key class (entity beans)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 272/596
11 14 C i ht © 2004 O l All i ht d
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 accessibleto remote clients
• EJB object:
– Is a container-generated implementation of a
remote interface– Is a reference object that a client receives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 273/596
11 15 C i ht © 2004 O l All i ht d
– Is a reference object that a client receives
– Delegates the method calls to a bean class afterdoing some infrastructure work
• The remote interface and remote object are usedby session and entity beans.
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 beanclass
– Contains home methods
– Are accessed by remote clients
• Home object:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 274/596
11-16C i ht © 2004 O l All i ht d
– Is a container-generated implementation of thehome interface
– Uses callback methods on a bean class to performits functions
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 byreference
• Local home interface:
– Extends the javax.ejb.EJBLocalHome interface– Defines the life-cycle methods that are accessible
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 275/596
11-17C i ht © 2004 O l All i ht d
– Defines the life-cycle methods that are accessible
by local cl ients
• These interfaces are used by session and entity
beans.
• They enable relationships between entity beans.
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 d i b l
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 276/596
11-18 Copyright © 2004, Oracle. All rights reserved.
• A message-driven bean class:
– Implements javax.ejb.MessageDrivenBean
– Must implement the MessageListener interface – Contains business logic in the onMessage()
method
The EJB Deployment Process
Jarcommand/
tool
EJBJAR
Component deployer’s
responsibility
Developer’s
responsibilityHome interface
Remote interfaceBean classOther classes
Deploymentdescriptor
Deploymenttools/
commands
Deployed EJB in the
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 277/596
11-19 Copyright © 2004, Oracle. All rights reserved.
JNDI
Deployed EJB in theServer
<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>
ejb-jar.xml File
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 278/596
11-20 Copyright © 2004, Oracle. All rights reserved.
<security-role> </security-role>
<method-permission> </method-permission>
<container-transaction> </container-transaction>
</assembly-descriptor>
</ejb-jar>
orion-ejb-jar.xml File
Oracle Application Server 10g uses the orion-ejb-jar.xml file for deployment. This file:
• Specifies run-time attributes of the bean for
deployment to the container
• Enables customization of the run-time behavior of
enterprise beans
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 279/596
11-21 Copyright © 2004, Oracle. All rights reserved.
Creating an EJB in JDeveloper
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 280/596
11-22 Copyright © 2004, Oracle. All rights reserved.
Using the EJB Wizard
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 281/596
11-23 Copyright © 2004, Oracle. All rights reserved.
Using the EJB Wizard
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 282/596
11-24 Copyright © 2004, Oracle. All rights reserved.
Adding Methods to the Bean
To add methods to the bean, right-click and select GoTo Bean Class:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 283/596
11-25 Copyright © 2004, Oracle. All rights reserved.
Deploying to Oracle Application Server10g from JDeveloper
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 284/596
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 areused
• Explain EJB interfaces
• Define the steps to deploy an EJB to Oracle Application Server 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 285/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 286/596
11-28 Copyright © 2004, Oracle. All rights reserved.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 287/596
11-29 Copyright © 2004, Oracle. All rights reserved.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 288/596
11-30 Copyright © 2004, Oracle. All rights reserved.
Implementing Business Tasks with
Session EJBs
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 289/596
Copyright © 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to dothe following:
• Describe session beans
• Differentiate stateless session beans from statefulsession beans
• Develop a home interface, a remote interface, and
a bean class for session beans
• Develop a client application to invoke the
business methods
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 290/596
12-2 Copyright © 2004, Oracle. All rights reserved.
business methods
Session Beans
A session bean:• Implements business processes
• Is short-lived and has the lifetime of a client’s
session• Does not survive server, machine, or network
crashes
• Is not saved in permanent storage
• Implements the javax.ejb.SessionBean
interface
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 291/596
12-3 Copyright © 2004, Oracle. All rights reserved.
interface
javax.ejb.SessionBean Interface
The SessionBean interface contains the followingcallback methods:
• setSessionContext(SessionContext ctx)
• ejbActivate()
• ejbPassivate()
• ejbRemove()
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 292/596
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 beanmaintains the state for a client, and the instance
variable represents the state of a unique client.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 293/596
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 datamanipulation is not necessary
• Use stateful session beans when:
– Interaction between bean and client must bemaintained across method calls and transactions
– A bean works on logic based on entity beans that
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 294/596
12-6 Copyright © 2004, Oracle. All rights reserved.
A bean works on logic based on entity beans thatrepresent persistent data
Life Cycle of a Stateless Session Bean
Container invokes
class.newInstance,setSessionContext(sessCtx),
and ejbCreate().
Ready
Container invokesejbRemove() .
Does notexist
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 295/596
12-7 Copyright © 2004, Oracle. All rights reserved.
Ready
Home Interface for StatelessSession Beans
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatelessejbHome extendsEJBHome
{
Statelessejb create() throws RemoteException,
CreateException;}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 296/596
12-8 Copyright © 2004, Oracle. All rights reserved.
Remote Interface for StatelessSession Beans
import javax.ejb.EJBObject;
import java.rmi.*;
public interface Statelessejb extends
EJBObject
{
public String incrementValue() throws
RemoteException; public int getValue()throws RemoteException;
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 297/596
12-9 Copyright © 2004, Oracle. All rights reserved.
The Session Bean Class
• The class must be defined as public, must not befinal, 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() methodshould be void.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 298/596
12-10 Copyright © 2004, Oracle. All rights reserved.
– Remote or create exceptions need not be thrown.
• The class can optionally implement theSessionSynchronization interface.
The Session Bean Class:Business Methods
• The bean class may define zero or more methodsto 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 componentinterface.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 299/596
12-11 Copyright © 2004, Oracle. All rights reserved.
• The method arguments and return types must be
legal types for RMI.• Application-specific exceptions can be thrown.
Bean Class for the StatelessSession 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()
{
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 300/596
12-12 Copyright © 2004, Oracle. All rights reserved.
return value;
}
}
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/ejb-
jar_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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 301/596
12-13 Copyright © 2004, Oracle. All rights reserved.
</session>
</enterprise-beans>
</ejb-jar>
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 bean’s
home interface is published• Authenticate itself with the naming service
interface
• Obtain a reference to the bean’s home interface
from the naming service by using the bean’s URL
• Invoke the create() method on the home
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 302/596
12-14 Copyright © 2004, Oracle. All rights reserved.
interface
• Invoke business methods
Client Application for StatelessSession 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];
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 303/596
12-15 Copyright © 2004, Oracle. All rights reserved.
Statelessejb obj[] = new Statelessejb[3];
for (int i=0;i<3;i++)
{ obj[i]= statelessejbHome.create(); }...
Client Application for StatelessSession 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 withobject" + i+" " +obj[i].getValue()+"\n");
}
for (int i=0;i<3;i++)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 304/596
12-16 Copyright © 2004, Oracle. All rights reserved.
for (int i=0;i<3;i++)
{ obj[i].remove(); }
...
Life Cycle of a Stateful Session Bean
setSessionContext(sessCtx),
and ejbCreate()
Container invokesejbRemove()
Passivated
ejbPassivate()
Does notexist
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 305/596
12-17 Copyright © 2004, Oracle. All rights reserved.
ReadyPassivated
instances
ejbActivate()
Home Interface for Stateful Session Bean
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatefulejbHome extendsEJBHome
{
Statefulejb create(int x) throws
RemoteException, CreateException;}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 306/596
12-18 Copyright © 2004, Oracle. All rights reserved.
Client Application for StatefulSession 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 withobject" + i+" " +obj[i].getValue()+"\n");
}
for (int i=0;i<3;i++)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 307/596
12-19 Copyright © 2004, Oracle. All rights reserved.
( ; ; )
{ obj[i].remove(); }
...
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 308/596
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 thefirst_name, last_name, email, and
department_name of an employee whose
employee_id is provided
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 309/596
12-21 Copyright © 2004, Oracle. All rights reserved.
Managing Persistent Data in
the Business Tier
Entity EJBs
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 310/596
Copyright © 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to dothe 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 311/596
13-2 Copyright © 2004, Oracle. All rights reserved.
container-managed persistent beans
Entity Beans
• Are objects that can be stored in permanentstorage
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 312/596
13-3 Copyright © 2004, Oracle. All rights reserved.
Representing Data in Entity Beans
Table
Entity bean object
int xString s
float f
int y
double d
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 313/596
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 relationshipbetween entities
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 314/596
13-5 Copyright © 2004, Oracle. All rights reserved.
Callback Methods to Load and Store Data
• ejbLoad()loads the
data from the
persistent storage to
the bean.
• ejbStore()saves thedata from the bean
instance to the
persistent storage.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 315/596
13-6 Copyright © 2004, Oracle. All rights reserved.
Session Beans Versus Entity Beans
Session Beans:
• Are represented byverbs because they
model workflow
• Are short-lived and
have a lifetime of a
client session
• Manage their state, but
do not containcallback methods to
manage data because
Entity Beans:
• Are represented bynouns because they
model business data
• Are long-lived and do
not depend on a
client’s session
• Contain callback
methods formanaging data
(create, retrieve,
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 316/596
13-7 Copyright © 2004, Oracle. All rights reserved.
they do not represent
data in the persistent
storage
persist, and so on) in
the persistent storage
Types of Entity Beans
•Container-managed persistent (CMP) beans: Thecontainer provides the logic to search and
manipulate the persistent data.
• Bean-managed persistent (BMP) beans: The bean
provider codes the logic to search and manipulatethe persistent data in the callback methods.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 317/596
13-8 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 318/596
13-9 Copyright © 2004, Oracle. All rights reserved.
descriptor
– Are easier to program and contain lesser code
Components of an Entity Bean
• 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 andcontains methods to access or manipulate that
data
• Primary key class: Is used to uniquely identify anentity bean instance
• Deployment descriptor: Contains information that
i d b th t i
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 319/596
13-10 Copyright © 2004, Oracle. All rights reserved.
is used by the container
Creating, Removing, Finding, andSelecting Entity Beans
• ejbCreate(): Initializes the entity bean in
memory. This method may also insert thecorresponding 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 andrelease 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 320/596
13-11 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 321/596
13-12 Copyright © 2004, Oracle. All rights reserved.
– Contains business methods that are not applicableto a specif ic instance (home methods)
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 322/596
13-13 Copyright © 2004, Oracle. All rights reserved.
– Throws RemoteException if i t is part of a remotehome interface
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 entityobject
– Return enti ty bean’s component interface referenceor collection of objects of component interface type
– Must throw FinderException
– Must throw RemoteException in a remote home
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 323/596
13-14 Copyright © 2004, Oracle. All rights reserved.
– Must throw RemoteException in a remote home
interface – Have find as a prefix in their names
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
• remove() methods remove the entity object and
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 324/596
13-15 Copyright © 2004, Oracle. All rights reserved.
• remove() methods remove the entity object and
the row from the underlying database.
Home Methods of Entity Beans
• 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 325/596
13-16 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 326/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 327/596
13-18 Copyright © 2004, Oracle. All rights reserved.
Bean Class of an Entity Bean
• Initializes the bean instance through theejbCreate() and ejbPostCreate() methods
• Implements:
– Finder methods through ejbFindxxx() methods
– Home methods through ejbHomexxx() methods
– Callback methods from the EntityBean interface
– Business and private methods
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 328/596
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 andbefore any other request from a client is processed
– Has void as return type
– Init ializes any relationship fields for an entity bean
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 329/596
13-20 Copyright © 2004, Oracle. All rights reserved.
Init ializes any relationship fields for an entity bean
javax.ejb.EntityBean Interface
All entity bean classes should implement thejavax.ejb.EntityBean interface.
public interface javax.ejb.EntityBeanimplements javax.ejb.EnterpriseBean
{
public void ejbActivate();
public void ejbLoad();
public void ejbPassivate();
public void ejbRemove();
public void ejbStore();
public void setEntityContext(EntityContextctx);
public void unSetEntityContext();
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 330/596
13-21 Copyright © 2004, Oracle. All rights reserved.
public void unSetEntityContext();
}
Life Cycle of an Entity Bean
Does not
exist
newInstance()
setEntityContext()
Pooled
unsetEntityContext()
ReadyejbLoad() ejbStore()
ejbCreate()
ejbPostCreate() ejbActivate() ejbRemove()ejbPassivate()
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 331/596
13-22 Copyright © 2004, Oracle. All rights reserved.
Clients invoke
business methods
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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 332/596
13-23 Copyright © 2004, Oracle. All rights reserved.
</enterprise-beans>...
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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 333/596
13-24 Copyright © 2004, Oracle. All rights reserved.
</ejb-jar>
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 334/596
13-25 Copyright © 2004, Oracle. All rights reserved.
Practice 13-1: Overview
This practice reviews entity bean concepts using
paper-based questions.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 335/596
13-26 Copyright © 2004, Oracle. All rights reserved.
Achieving State Management in the
Business Tier
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 336/596
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-managedpersistent (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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 337/596
14-2 Copyright © 2004, Oracle. All rights reserved.
Features of BMP Entity Beans
• The Bean provider provides the code for
persistence management.
• BMP beans provide more flexibili ty in managing
persistent data.
• The bean class of a BMP entity bean containscode for data access and manipulation.
• Callback methods contain code to map the entity
bean instance to the data, load the data, and storethe data in persistent storage.
• BMP beans are less portable.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 338/596
14-3 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 339/596
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:
– Portabil ity across all EJB-compliant containers
– A layer of data independence
– Container-managed fields, which represent the
persistent f ields in the database
• Bean developers concentrate on the businesslogic and provide empty implementations of the
callback methods.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 340/596
14-5 Copyright © 2004, Oracle. All rights reserved.
Implementing Methods in CMP Beans and
BMP Beans
ejbStore()
ejbLoad()
ejbcreate()
setXXX() and
getXXX()
ejbFind()
CMPBMPMethod
abstract
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 341/596
14-6 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 342/596
14-7 Copyright © 2004, Oracle. All rights reserved.
CMP Bean: Example
• The example in this lesson creates a CMP entity
bean to represent the DEPARTMENTS table with thefollowing components:
– Remote interface: Departments
– Home interface: DepartmentsHome – Bean class: DepartmentsBean
– Deployment descriptor: ejb-jar.xml
• Client for Departments bean:DepartmentsClient
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 343/596
14-8 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 containerimplements these methods
– Must have names in the following form:getFieldname()or setFieldname()
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 344/596
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 fieldsLong 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;
...
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 345/596
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;
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 346/596
14-11 Copyright © 2004, Oracle. All rights reserved.
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 347/596
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)
{ }
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 348/596
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()
{ }
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 349/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 350/596
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</ persistence-
type>< prim-key-class>java.lang.Long</ prim-key-
class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 351/596
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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 352/596
14-17 Copyright © 2004, Oracle. All rights reserved.
j j
Mapping CMP Fields to
Database Table Columns
• Accept the defaults that are supplied by the
container.• Map explicit ly 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
• JDeveloper provides easy mapping of thepersistent fields to database tables.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 353/596
14-18 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 fi le, which can be customized• Table: Default table is created by a container with
a unique name that combines the following:
– 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 fieldsdefined in the deployment descriptor; Java data
types are translated to database data types inoracle xml
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 354/596
14-19 Copyright © 2004, Oracle. All rights reserved.
yp yporacle.xml
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)"/>
...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 355/596
14-20 Copyright © 2004, Oracle. All rights reserved.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 356/596
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;
...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 357/596
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 ANDDEPARTMENT_NAME");
System.out.println(departments.getDepartment_id() +
" " + departments.getDepartment_name());
...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 358/596
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)
{...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 359/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 360/596
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 andupdate the EMPLOYEES table
• Creating a remote interface, and a home interface
for a CMP entity bean by using Oracle JDeveloper10g
• Implementing the create() methods, callback
methods, and methods of the remote interface inthe entity bean class
• Testing the entity bean with a client application
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 361/596
14-26 Copyright © 2004, Oracle. All rights reserved.
Container-Managed Relationships (CMRs)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 362/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 363/596
15-2 Copyright © 2004, Oracle. All rights reserved.
Relationships
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 364/596
15-3 Copyright © 2004, Oracle. All rights reserved.
Implementing Relationships
• Data manipulation in the beans may involve a
more complex data model, with a relationshipbetween 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 isnavigated
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 365/596
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 366/596
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.
111 1111Smith100
phone_num nameemp_id
MCI650111 1111
servicearea_code phone_num
EMP
PHONE
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 367/596
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 containmany departments (1:M).
…Seattle1700
…citylocation_id
DEPARTMENTS
LOCATIONS
1700 Administration10
location_id department_namedepartment_id
1700Purchasing30
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 368/596
15-7 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.
SA_REP176 A1
job_id employee_id assign_pk
ASSIGNMENTS
EMPLOYEES
Jonathon176
Nameemployee_id
JOBS_HISTORY
...SA_REP
...job_id
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 369/596
15-8 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
RowsJava
application
JDBCTopLink
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 370/596
15-9 Copyright © 2004, Oracle. All rights reserved.
TopLink: Integration of J2EE Applications
with Data Sources at Run Time
DB2
SQL server
EIS
Oracle
XML
Data mapping and integration
EJBs
Servlets/JSPs
J2EE
Application Server
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 371/596
15-10 Copyright © 2004, Oracle. All rights reserved.
TopLink: Integrated with Oracle
JDeveloper 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 372/596
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 deploymentdescriptor
– Use only local interfaces to define the relationship
• Define abstract get() and set() accessor
methods in the bean class for each relationshipfield
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 373/596
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 objectretrieval
– 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 374/596
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);
...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 375/596
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);...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 376/596
15-15 Copyright © 2004, Oracle. All rights reserved.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 377/596
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);
... }
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 378/596
15-17 Copyright © 2004, Oracle. All rights reserved.
Implementing a Relationship in
the Deployment Descriptor
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 379/596
15-18 Copyright © 2004, Oracle. All rights reserved.
Implementing 1:1 Relationships
...
<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>
...
Emp to Phone
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 380/596
15-19 Copyright © 2004, Oracle. All rights reserved.
Implementing 1:1 Relationships
...
<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> ...
Phone to Emp
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 381/596
15-20 Copyright © 2004, Oracle. All rights reserved.
Implementing 1:M Relationships
<relationships>
<ejb-relation>
<ejb-relation-name>Departments-Locations</ejb-relation-name><ejb-relationship-role>
<ejb-relationship-role-name>Locations-has-departments_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>...
Departments to Locations
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 382/596
15-21 Copyright © 2004, Oracle. All rights reserved.
Implementing 1:M Relationships
...
<ejb-relationship-role>
<ejb-relationship-role-name>Departments-owned-by-locations_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>
...
Locations to Departments
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 383/596
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>...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 384/596
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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 385/596
15-24 Copyright © 2004, Oracle. All rights reserved.
Mapping Relationship Fields to Database
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 386/596
15-25 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 containercreates 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 one-
to-many and many-to-many relationships
• User-defined or automatically generated primary
key
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 387/596
15-26 Copyright © 2004, Oracle. All rights reserved.
Explicit Mapping of Relationship Fields
1. Deploy your application with only the ejb-
jar.xml elements configured.2. Copy the container-created orion-ejb-jar.xml
file to your development environment.
3. Modify the <entity-deployment> element in theorion-ejb-jar.xml fi le to use the database table
and columns that you specify.
4. Rearchive and redeploy your application.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 388/596
15-27 Copyright © 2004, Oracle. All rights reserved.
15 28 C i ht © 2004 O l All i ht d
Using JDeveloper to Create CMR Beans
Using JDeveloper, you can create a container-
managed relationship between entity beans in thefollowing 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 389/596
15-28 Copyright © 2004, Oracle. All rights reserved.
15 29 C i ht © 2004 O l All i ht d
Summary
In this lesson, you should have learned how to:
• Determine the cardinality and direction of arelationship
• Define and implement relationships between CMR
entity beans
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 390/596
15-29 Copyright © 2004, Oracle. All rights reserved.
15 30 Copyright © 2004 Oracle All rights reserved
Practice 15: Overview
This practice covers creating a one-to-many
relationship between the Employees andDepartments entity beans.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 391/596
15-30 Copyright © 2004, Oracle. All rights reserved.
Copyright © 2004 Oracle All rights reserved
Developing Message-Driven Beans
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 392/596
Copyright © 2004, Oracle. All rights reserved.
16-2 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 393/596
16 2 Copyright © 2004, Oracle. All rights reserved.
16-3 Copyright © 2004 Oracle All rights reserved
Overview of Messaging Systems
• 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 394/596
16 3 Copyright © 2004, Oracle. All rights reserved.
16-4 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 395/596
Copy g 00 , O ac e g s ese ed
16-5 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
MOMJMS clientJMS client
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 396/596
py g , g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 397/596
16-7 Copyright © 2004, Oracle. All rights reserved.
Point-to-Point Model
• Senders send messages to virtual destinations.
• There is only one receiver for a message from aqueue.
Queue sender
M* - Message
Queues
(virtual destinations)
Queue receiver
R3
R2
M1
M2
M3
Messaging server
M1
M3
Queue1
Queue2
M2
S1
S2
R1
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 398/596
16-8 Copyright © 2004, Oracle. All rights reserved.
Publish-and-Subscribe Model
• Publishers send messages to virtual destinations.
• One or more subscribers receive the messages.
Topic subscriber
S3
S2
S1
M1
M2
M1
M2P2
Topic1P1
Topics
(virtual destinations)Topic publisher
M* - Message
Messaging server
Topic2
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 399/596
16-9 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• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 400/59616-10 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 foridentif ication and routing information.
• Properties for application-defined property values,
which can be used for message fil tering purposes
• A body for the contents of the message, whosecontents can be structured as a StreamMessage,
MapMessage, TextMessage, ObjectMessage, or
ByteMessage
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 401/59616-11 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 402/59616-12 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 403/59616-13 Copyright © 2004, Oracle. All rights reserved.
Asynchronous Message Delivery
• In an asynchronous messaging model, the
consumer implements a MessageListenerinterface.
• 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 processesthe message.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 404/59616-14 Copyright © 2004, Oracle. All rights reserved.
Message-Driven Beans
MDBs:
• Are programmed for receiving and processingasynchronous messages through the JMS
Destination
• Are stateless, server-side, transaction-awarecomponents
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 405/59616-15 Copyright © 2004, Oracle. All rights reserved.
MDB Architecture
OC4J
MDB
JMS resourceprovider
Queue/Topic
Client
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 406/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 407/59616-17 Copyright © 2004, Oracle. All rights reserved.
State Diagram of an MDB
Does not exist
Method-ready pool
Container invokesClass.newInstance,
setMessageDrivenContext(context)
andejbCreate()
Container invokesejbRemove(…)
Container invokesonMessage()
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 408/59616-18 Copyright © 2004, Oracle. All rights reserved.
Developing MDBs
1. Configure Oracle Application Server 10g
Containers for J2EE (OC4J) with the JMS providerdetails.
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 locationsin orion-ejb-jar.xml
4. Create the EJB JAR file that contains the bean andthe deployment descriptors.
5. Create the .ear fi le and deploy the bean.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 409/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 410/596
16-20 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;
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 411/596
16-21 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");
}
}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 412/596
16-22 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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 413/596
16-23 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>
...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 414/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 415/596
16-25 Copyright © 2004, Oracle. All rights reserved.
orion-ejb-jar.xml: Example
<enterprise-beans>
<message-driven-deploymentname="MessageLogger"
connection-factory-location=
"jms/QueueConnectionFactory">
destination-location="jms/demoQueue"
</message-driven-deployment>
...
</enterprise-beans>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 416/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 417/596
16-27 Copyright © 2004, Oracle. All rights reserved.
Creating an MDB with JDeveloper
ejb-jar.xml
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 418/596
16-28 Copyright © 2004, Oracle. All rights reserved.
Creating an MDB with JDeveloper
Map the destination details in orion-ejb-jar.xml.
orion-ejb-jar.xml
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 419/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 420/596
16-30 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)
• Create an MDB• Compare a stateless session EJB and an MDB
• Describe JMS
• Configure a JMS resource provider in the OC4Jjms.xml file
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 421/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 422/596
Copyright © 2004, Oracle. All rights reserved.
Integrating J2EE Components
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 423/596
17-2 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 10gContainers for J2EE (OC4J)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 424/596
17-3 Copyright © 2004, Oracle. All rights reserved.
Overview
JSP
HttpServlet
Request
Web t ier EJB t ier
Controller servlet
Employees
JSP
Employees
EJB
To EIS
HttpServletResponse
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 425/596
17-4 Copyright © 2004, Oracle. All rights reserved.
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 theEJB method.
4. Define a reference to the EJB in the web.xml file.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 426/596
17-5 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" %>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 427/596
17-6 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(); }
}
%>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 428/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 429/596
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 430/596
17-9 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 aPortableRemoteObject.
• 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.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 431/596
17-10 Copyright © 2004, Oracle. All rights reserved.
ejb-local-ref Element
Right-click web.xml to create an EJB local reference.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 432/596
17-11 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:
EJB Tag Purpose
useHome Looks up the home interface for the EJB andcreates an instance of it
useBean Instantiates the EJB
createBean Nests an EJB createBean tag within theuseBean tag to create the EJB instance
iterate Iterates through a collection of EJB
instances
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 433/596
T
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 434/596
17-13 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" />
t B T
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 435/596
17-14 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:createBeaninstance="<%=EmployeesHome.create()%>" />
</EJB:useBean>
it t T
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 436/596
17-15 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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 437/596
Deploying an Application: Web Tier
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 438/596
17-17 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
) inJDeveloper.
3. Right-cl ick the .deploy fi le and select either of
the following:
– Deploy to WAR file
– Deploy to OracleAS10g (where OracleAS10g is the
name of your application server connection)
Deploying an Application: EJB Tier
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 439/596
17-18 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-cl ick the .deploy fi le and select either of
the following:
– Deploy to JAR file
– Deploy to OracleAS10g
Deploying an Application: EAR File
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 440/596
17-19 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 beincluded in this EAR file.
3. Right-cl ick the .deploy fi le and select either of
the following:
– Deploy to EAR file
– Deploy to OracleAS10g
Deploying from Oracle Enterprise Manager
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 441/596
17-20 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:
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 442/596
17-21 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
Practice 17-1 and 17-2: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 443/596
17-22 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 444/596
Copyright © 2004, Oracle. All rights reserved.
Distributing Modular Applications:
Introduction to Web Services
Objectives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 445/596
18-2 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
What Is a Web Service?
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 446/596
18-3 Copyright © 2004, Oracle. All rights reserved.
What Is a Web Service?
External
applications
HTML
XML
Web
presentation
Business
logic
Web
serviceDatabases
Application Server
HTTP client
Web Service
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 447/596
18-4 Copyright © 2004, Oracle. All rights reserved.
Web Service
A Web service is:
• A software component whose technology is basedon a set of standards for building interoperable
distributed applications
• A set of self-describing business functions
• Service oriented
• Component based
Service-Oriented Architecture
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 448/596
18-5 Copyright © 2004, Oracle. All rights reserved.
Service Oriented Architecture
Invoke
Servicerequestor
Publish Find
Serviceprovider
Service
registry
Web Services Constituents
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 449/596
18-6 Copyright © 2004, Oracle. All rights reserved.
• Internet for communication
• XML as universal data format
• SOAP for XML messaging
• WSDL for describing the service
• UDDI for publishing the Web services
Benefits of Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 450/596
18-7 Copyright © 2004, Oracle. All rights reserved.
• Distributed component model with interoperability
• XML format for representing data. The request andresponse 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)
Web Services Model
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 451/596
18-8 Copyright © 2004, Oracle. All rights reserved.
Web servicesdirectory
(UDDI)
XML interface (WSDL)
Web service
Find
Invoke Publish
1
2
3
XML interface (WSDL)
Client application
RPC-Style Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 452/596
18-9 Copyright © 2004, Oracle. All rights reserved.
y
• RPC-style Web services are loosely coupled.
• SOAP messages model the call and response
semantics.
• This style of communication can be described in
WSDL.
Document-Style Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 453/596
18-10 Copyright © 2004, Oracle. All rights reserved.
• Document-style Web services are loosely coupled.
• SOAP messages carry arbitrary XML documents.
• This style of communication can be described in
WSDL.
Oracle Support for Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 454/596
18-11 Copyright © 2004, Oracle. All rights reserved.
Oracle ApplicationServer 10g is the
infrastructure for:
• Describing Webservices
• Deploying Webservices
• Publishing Webservices
• Invoking Webservices
Oracle JDeveloper 10gprovides tools for:
• Developing, deploying,publishing, andinvoking Web services
• Modeling, testing, anddebugging Webservices
• Browsing UDDI registry
to locate Web services
• Generating stub fi les toconsume Web services
SOAP: XML Messaging for Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 455/596
18-12 Copyright © 2004, Oracle. All rights reserved.
• Introduces a self-describing data representationformat in XML
• Represents request and response as XMLmessages
• Supports both RPC-style and document-styleinvocation
• 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
Communication with SOAP
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 456/596
18-13 Copyright © 2004, Oracle. All rights reserved.
Communication by using SOAP protocol includes:
• Requests to invoke a service
• Responses from service method
• Fault from a service
SOAP client
Request
Web server Firewall
Response
SOAP Messages
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 457/596
18-14 Copyright © 2004, Oracle. All rights reserved.
A SOAP message is an
XML document that
consists of:
• A mandatoryenvelope as a top-
level element• An optional header
• A mandatory body
• An optional fault
HTTP headers
Headers
Message name, data,
and fault element
SOAP envelopeSOAP header
SOAP body
Web Services Description
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 458/596
18-15 Copyright © 2004, Oracle. All rights reserved.
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 definit ion: Describes whatmessage must be sent and what message isreturned
– Service implementation definit ion: Describes towhich address the message must be sent
• Allows both the messages and the operations onthe 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?
WSDL
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 459/596
18-16 Copyright © 2004, Oracle. All rights reserved.
<?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>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 460/596
How UDDI Is Used
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 461/596
18-18 Copyright © 2004, Oracle. All rights reserved.
UDDI Business
Registry
Business portals and
marketplaces
Business user Software developer
UDDI Registry
Business
descriptions
Service
types
Searching for a Web Service by
U i UDDI
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 462/596
18-19 Copyright © 2004, Oracle. All rights reserved.
Using UDDI
Provider infoContact InfoDirectory of names
White pages
Yellow pages
Search usingcontext such as
location, service
type. Point to
White pages for
details.
Green pages
Information aboutbusiness modelTechnical detailsof providedservice
Information onbusiness process
UDDI Specification
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 463/596
18-20 Copyright © 2004, Oracle. All rights reserved.
• UDDI Programmer’s API
• UDDI Data Structure Specification and XML
Schema
• UDDI Replication Specification and UDDI XML
Replication Schema
• UDDI Operator’s Specification
tModel
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 464/596
18-21 Copyright © 2004, Oracle. All rights reserved.
• Provides metadata information about a Web
service specification
• Contains references to the specification locations
• Is used for compliance check
tModel
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 465/596
18-22 Copyright © 2004, Oracle. All rights reserved.
<tModel
tModelKey="uuid:7716711A-1231-483F-A4B9-
36104341BA78" 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>
UDDI Support in Oracle JDeveloper 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 466/596
18-23 Copyright © 2004, Oracle. All rights reserved.
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
UDDI Browsing with Oracle JDeveloper 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 467/596
18-24 Copyright © 2004, Oracle. All rights reserved.
UDDI Publishing and Browsing with
Oracle Enterprise Manager
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 468/596
18-25 Copyright © 2004, Oracle. All rights reserved.
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
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 469/596
18-26 Copyright © 2004, Oracle. All rights reserved.
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 Document-
style Web service
Practice 18-1: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 470/596
18-27 Copyright © 2004, Oracle. All rights reserved.
This practice covers revision questions on Web
services technology and standards such as SOAP,
WSDL, and UDDI.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 471/596
Copyright © 2004, Oracle. All rights reserved.
Distributing Modular Applications:
Developing Web Services
Objectives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 472/596
19-2 Copyright © 2004, Oracle. All rights reserved.
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 aPL/SQL stored procedure as a Web service
Oracle Application Server 10g
Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 473/596
19-3 Copyright © 2004, Oracle. All rights reserved.
Web Services
Oracle Application Server10g Web services can be
implemented as any of thefollowing:
• Stateless and statefulJava classes
• Stateless PL/SQLpackages
• Stateless session
Enterprise JavaBeans(EJBs)
• Java Message Service(JMS) destinations
Developing a Web Service with a Stateless
Java Class
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 474/596
19-4 Copyright © 2004, Oracle. All rights reserved.
1. Define an interface.
2. Define a stateless Java class.
3. Generate an .ear file.
4. Deploy the generated .ear file to Oracle
Application Server 10g.
Defining an Interface
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 475/596
19-5 Copyright © 2004, Oracle. All rights reserved.
Defining an Interface
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 476/596
19-6 Copyright © 2004, Oracle. All rights reserved.
Defining a Stateless Java Class
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 477/596
19-7 Copyright © 2004, Oracle. All rights reserved.
Defining a Stateless Java Class
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 478/596
19-8 Copyright © 2004, Oracle. All rights reserved.
Creating the Web Service
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 479/596
19-9 Copyright © 2004, Oracle. All rights reserved.
Creating the Client Application
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 480/596
19-10 Copyright © 2004, Oracle. All rights reserved.
Creating the Client Application
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 481/596
19-11 Copyright © 2004, Oracle. All rights reserved.
Deploying the Web Service
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 482/596
19-12 Copyright © 2004, Oracle. All rights reserved.
Testing the Web Service
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 483/596
19-13 Copyright © 2004, Oracle. All rights reserved.
Web Service Home Page
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 484/596
19-14 Copyright © 2004, Oracle. All rights reserved.
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
Testing the Deployed Web Service with
Home Page
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 485/596
19-15 Copyright © 2004, Oracle. All rights reserved.
Testing the sayHello Operation
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 486/596
19-16 Copyright © 2004, Oracle. All rights reserved.
Testing the sayHello Operation
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 487/596
19-17 Copyright © 2004, Oracle. All rights reserved.
Serializing and Encoding Parameters
and Results
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 488/596
19-18 Copyright © 2004, Oracle. All rights reserved.
• Oracle Application Server 10g Web services
support a prepackaged implementation for
handling encoding, decoding, serialization, anddeserialization.
• Oracle Application Server 10g supports the
following encoding mechanisms: – Standard SOAP v.1.1 encoding
– Literal XML encoding
Developing a Stored Procedure
Web Service
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 489/596
19-19 Copyright © 2004, Oracle. All rights reserved.
1. Set up data sources in OC4J by configuring thedata-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 Server10g or stand-alone OC4J to expose it as a Web
service.
Generating Wrapper Classes
Using JPublisher
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 490/596
19-20 Copyright © 2004, Oracle. All rights reserved.
Database Java classesJPublisher
Exposing a Function as a Web Service by
Using Oracle JDeveloper 10g
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 491/596
19-21 Copyright © 2004, Oracle. All rights reserved.
Publishing the Package as a Web Service
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 492/596
19-22 Copyright © 2004, Oracle. All rights reserved.
JMS Web Services
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 493/596
19-23 Copyright © 2004, Oracle. All rights reserved.
• 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 JMSdestinations.
• JMS messages can be processed on the server
side by:
– Message-Driven Bean (MDB)
– JMS client
Summary
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 494/596
19-24 Copyright © 2004, Oracle. All rights reserved.
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
Practice 19-1: Overview
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 495/596
19-25 Copyright © 2004, Oracle. All rights reserved.
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 ApplicationServer 10g and testing it with the Web services
home page
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 496/596
Copyright © 2004, Oracle. All rights reserved.
Implementing Security in J2EE
Applications
Objectives
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 497/596
20-2 Copyright © 2004, Oracle. All rights reserved.
After completing this lesson, you should be able to do
the following:
• Define Java Authentication and AuthorizationService (JAAS)
• Define security issues regarding Web applications
and Enterprise JavaBeans (EJB)• List the security attr ibutes of the Java Naming and
Directory Interface (JNDI) Context interface
Goals of J2EE Security Architecture
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 498/596
20-3 Copyright © 2004, Oracle. All rights reserved.
• Lessen the burden of the application developer in
securing applications
• Ensure fine-grained access control to the EJBresources
• Enable portable and secured Web applications
and EJBs
Overview of J2EE Security Architecture
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 499/596
20-4 Copyright © 2004, Oracle. All rights reserved.
Use Java Authentication and Authorization Service
(JAAS) APIs to:
• Authenticate a client to access the system – Define security identit ies (principal/users), groups,
and roles to identify clients to the container
– Associate principals to the client to enable accessto 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
Java Authentication and Authorization
Service (JAAS)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 500/596
20-5 Copyright © 2004, Oracle. All rights reserved.
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.
Java Authentication and Authorization
Service (JAAS)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 501/596
20-6 Copyright © 2004, Oracle. All rights reserved.
JAAS supports the following authorization,
authentication, and user community (realm) features:
• Principals• Subjects
• Login module authentication
• Roles• Realms
• Policies
• Permissions
Authorization of a Client
• The authorization is specified in the J2EE-specific
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 502/596
20-7 Copyright © 2004, Oracle. All rights reserved.
p p
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• Every client obtains a security principal.
• A client can invoke a URL or a method only if the
client’s role has the associated invocation rights.
• The container provider enforces the security
policies and provides the tools for managing
security.
JAAS Provider Types in OC4J
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 503/596
20-8 Copyright © 2004, Oracle. All rights reserved.
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.
Configuring Security
D fi d i j d t l (
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 504/596
20-9 Copyright © 2004, Oracle. All rights reserved.
• Define users and groups in jazn-data.xml (or
principals.xml).
• Define security view or logical roles in J2EEdeployment descriptor (web.xml or ejb-
jar.xml).
• Map logical roles to users and groups in OC4J-specific 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).
Defining the Users, Groups, and Roles
• The identities (users and groups) are known to the
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 505/596
20-10 Copyright © 2004, Oracle. All rights reserved.
• The identities (users and groups) are known to thecontainer 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> ...
Managing Users and Groups
with the JAZN Admintool
Th JAZN Ad i l l d
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 506/596
20-11 Copyright © 2004, Oracle. All rights reserved.
The JAZN Admintool can manage users, roles, andgroups and can assign roles to users in XML or LDAP-
based data.• It modifies jazn-data.xml or the LDAPrepository.
• It prompts for admin username and password.
Examples:
• Adding a user:
• Adding a role (or a group):
• Granting a role to a user (assign user to a group):
java –jar jazn.jar –adduser jazn.com ora1 oracle
java –jar jazn.jar –addrole jazn.com managers
java –jar jazn.jar –grantrole manager jazn.com ora1
Defining the Logical Roles
Th l i l it l d fi d i th J2EE
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 507/596
20-12 Copyright © 2004, Oracle. All rights reserved.
The logical security roles defined in the J2EE
deployment descriptors are:
• Specified in the web.xml fi le 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.
Defining and Using Logical Roles in Web Applications (web.xml)
• Define logical role in the <security-role>l t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 508/596
20-13 Copyright © 2004, Oracle. All rights reserved.
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-resource-
name><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>
Defining and Using Logical Roles in EJBs(ejb-jar.xml)
Define logical role in < it l > element
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 509/596
20-14 Copyright © 2004, Oracle. All rights reserved.
• 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> ...
Mapping Logical Roles to
Users and Groups
Mapping is done in the OC4J deployment descriptors
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 510/596
20-15 Copyright © 2004, Oracle. All rights reserved.
Mapping is done in the OC4J deployment descriptors.
• A logical role to a group:
• A logical role to a user:
• A logical role to a group or a specific user:
<security-role-mapping name = "hr_managers"><group name="managers"/>
</security-role-mapping>
<security-role-mapping name = "hr_managers"><user name="ora1"/>
</security-role-mapping>
<security-role-mapping name = "hr_managers"><group name="managers"/><user name="ora1"/>
</security-role-mapping>
Programmatic Access to a Caller’s
Security Context
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 511/596
20-16 Copyright © 2004, Oracle. All rights reserved.
• Not all security policies can be expressed
declaratively.
• Use a programmatic interface to access thesecurity context of the calling cl ient 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);
Client Authentication
• For Web applications:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 512/596
20-17 Copyright © 2004, Oracle. All rights reserved.
• For Web applications:
– Use Web application server security mechanisms,
where credentials are passed through to the J2EEenvironment
– 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 orsettings in a Hashtable.
– Local clients, such as servlets, JSPs, or other EJBs,pass their credentials by using the Context object.
EJB Client Authentication with thejndi.properties file
• In the jndi properties file:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 513/596
20-18 Copyright © 2004, Oracle. All rights reserved.
• In the jndi.properties file:
• Client accessing the EJB with the above JNDI
properties:
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
Context ic = new InitialContext();EmployeeHome = (EmployeeHome) ic.lookup(
"java:comp/env/Employee");
EJB Client Authentication with aHashtable
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 514/596
20-19 Copyright © 2004, Oracle. All rights reserved.
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");
Setting Access Control with JDeveloper
• You can set security roles to access a Web
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 515/596
20-20 Copyright © 2004, Oracle. All rights reserved.
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.
• For Web applications, set the access permissions
as constraints defining URL patterns for a Web
resource.
• For EJBs, set the access permissions for eitherindividual methods or all the methods of the bean.
Creating Web Application Security Roles
1. Right-click web.xml, select Properties.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 516/596
20-21 Copyright © 2004, Oracle. All rights reserved.
1. Right click web.xml, select Properties.
2. In the Security Roles section, click Add.
Web Application Login Authentication
Typically done using Oracle HTTP Server using either
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 517/596
20-22 Copyright © 2004, Oracle. All rights reserved.
Typically done using Oracle HTTP Server using either
Basic, Digest, Login Form, Single-Sign On, and so on.
Web Application Authorization
• Define a Web resource (URLs and HTTP methods).
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 518/596
20-23 Copyright © 2004, Oracle. All rights reserved.
Define a Web resource (URLs and HTTP methods).
• Grant security roles access to the Web resource.
Creating EJB Security Roles
1. Select the Security Roles section.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 519/596
20-24 Copyright © 2004, Oracle. All rights reserved.
2. Click Add to create and enter a new logical role
name and description in the Create Security Roledialog window.
Setting Method Permissions
In the Method Permissions section, select the roles
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 520/596
20-25 Copyright © 2004, Oracle. All rights reserved.
,
and the methods that are accessible for those roles.
Method Access in EJB
Deployment Descriptors
• The example shows the hr_managers role granted
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 521/596
20-26 Copyright © 2004, Oracle. All rights reserved.
access to the incrementSalary() method.
• Explicit settings have precedence over defaultmethod access in the OC4J deployment descriptor.
Creating a Mapping for the Logical Roles
In JDeveloper, edit the orion-ejb-jar.xml file.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 522/596
20-27 Copyright © 2004, Oracle. All rights reserved.
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).
Mapping JAZN Identities to a Logical Role
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 523/596
20-28 Copyright © 2004, Oracle. All rights reserved.
Mapping JAZN Identities to a Logical Role
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 524/596
20-29 Copyright © 2004, Oracle. All rights reserved.
Mapping Results in orion-ejb-jar.xml
The OC4J XML Deployment Descriptor holds the
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 525/596
20-30 Copyright © 2004, Oracle. All rights reserved.
details for mapping the logical role to the allowed
identities (groups or users).For example:
Accessing the EJB with New Permissions
• Any client with a role other than those specified in
h d l d i i h i
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 526/596
20-31 Copyright © 2004, Oracle. All rights reserved.
the deployment descriptor receives the exceptioncom.evermind.server.rmi.OrionRemoteException .
• Clients without read/write access to the namespacereceive the exceptionjavax.naming.NoPermission.
Summary
In this lesson, you should have learned how to:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 527/596
20-32 Copyright © 2004, Oracle. All rights reserved.
• 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 thelogical and concrete roles for client authorization
• Access security information of the caller by usingmethods in the javax.ejb.EJBContext interface
• Authenticate EJB client applications by using thejndi.properties fi le and InitialContext
Practice 20-1: Overview
This practice covers the following topics:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 528/596
20-33 Copyright © 2004, Oracle. All rights reserved.
• Using the Web Application Deployment Descriptor
to create logical security roles for a Webapplication
• 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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 529/596
Copyright © 2004, Oracle. All rights reserved.
Oracle Application Server 10g TransactionSupport
Objectives
After completing this lesson, you should be able to do
the following:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 530/596
21-2 Copyright © 2004, Oracle. All rights reserved.
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
What Is a Transaction?
A transaction:
I i l l i l it f k t f t k
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 531/596
21-3 Copyright © 2004, Oracle. All rights reserved.
• 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)
Enterprise JavaBeans (EJB) Support
for Transactions
• The EJB architecture supports declarative and
programmatic transactions
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 532/596
21-4 Copyright © 2004, Oracle. All rights reserved.
programmatic transactions.
• The bean provider is not exposed to thecomplexity of distributed transactions.
• The EJB container provides a transaction
infrastructure.
• EJBs do not support a nested transaction model.
EJB Transaction Model
• Demarcating a transaction determines:
– Who begins and ends a transaction
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 533/596
21-5 Copyright © 2004, Oracle. All rights reserved.
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 specif ied declaratively (implicit) through the XML
deployment descriptor
Demarcating Transactions
• Container-managed transactional demarcation: – The <transaction-type> element set to container
in the deployment descriptor
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 534/596
21-6 Copyright © 2004, Oracle. All rights reserved.
– No transactional management code in the bean
– Transaction management depends on value of the<trans-attribute> element
– Available to entity, session, and message-drivenbeans (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 entitybeans
Container-Managed Transactions
<session><ejb-name>hrApp</ejb-name>
<home>demos.hrAppHome</home> ...
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 535/596
21-7 Copyright © 2004, Oracle. All rights reserved.
<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> ...
CMT: Transaction Attributes
• The following are the EJB-specified values of
transaction attributes:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 536/596
21-8 Copyright © 2004, Oracle. All rights reserved.
transaction attributes:
– NotSupported – Required
– Supports
– RequiresNew
– Mandatory
– Never
• The transactional behavior of a bean can be
changed with these attributes during deploymenttime.
CMT: Transaction Attributes
You specify the transaction attributes as follows:
• Specify for all the methods of a stateful session
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 537/596
21-9 Copyright © 2004, Oracle. All rights reserved.
• Specify for all the methods of a stateful session
bean or an entity bean’s component interface andall direct and indirect superinterfaces of the
component interface.
• Do not specify for:
– The methods of the javax.ejb.EJBObject
interface and the bean’s home interface in an
stateful session bean
– The getEJBHome, getHandle, getPrimaryKey,isIdentical, getEJBMetaData, and
getHomeHandle methods in an entity bean
Transaction Attribute: NotSupported
A client has:
• No transaction: The bean does not start one
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 538/596
21-10 Copyright © 2004, Oracle. All rights reserved.
No transaction: The bean does not start one.
• A transaction: The bean suspends it. Thetransaction resumes when the client gains control.
Client
(bean or servlet) Bean
No transactional context
Threads of execution
Client
(bean or servlet)Bean
No transactional context
Suspended
Resumed
No transactional context
Transactional context
Transaction Attribute: Required
A client has:
• No transaction: The bean starts a new one
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 539/596
21-11 Copyright © 2004, Oracle. All rights reserved.
Threads of execution
No transaction: The bean starts a new one.
• A transaction: The bean uses it.
Client transactional context
No transactional context
Bean
New transactional context
Client
(bean or servlet)
Client
(bean or servlet)
Transactional context
Bean
Threads of execution
Transaction Attribute: Supports
A client has:
• No transaction: The bean does not start new one.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 540/596
21-12 Copyright © 2004, Oracle. All rights reserved.
Threads of execution
No transaction: The bean does not start new one.
• A transaction: The bean uses it.
No transactional contextNo transactional context
Client
(bean or servlet)
Client
(bean or servlet)
Transactional context
Bean
Client transactional context
Bean
Threads of execution
Transaction Attribute: RequiresNew
A client has:
• No transaction: The bean starts a new one.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 541/596
21-13 Copyright © 2004, Oracle. All rights reserved.
No transaction: The bean starts a new one.
• A transaction: It is suspended, the bean starts anew one and commits it, and then the old one
resumes.
Bean transactional contextNo transactional context
Client(bean or servlet) Bean
Client
(bean or servlet)
Client Transactional context
Bean
Bean transactional context
Suspended
Resumed
Threads of execution
A client has:
• No transaction: The bean requires one. It throws the
Transaction Attribute: Mandatory
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 542/596
21-14 Copyright © 2004, Oracle. All rights reserved.
Threads of execution
qjavax.transaction.TransactionRequiredException
exception.
• A transaction: The bean uses it.
No transactional context
Client
(bean or servlet)
Client
(bean or servlet)
Transactional context Client transactional context
Bean
Bean
EXCEPTION THROWN
Threads of
execution
Transaction Attribute: Never
A client has:
• No transaction: The container calls the method in
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 543/596
21-15 Copyright © 2004, Oracle. All rights reserved.
an unspecified transaction context.• A transaction: The container throws the
java.rmi.RemoteException exception.
java.rmi.RemoteExceptionTransactional context
Client
(bean or servlet)Threads of
execution
Bean
CMT: The setRollbackOnly() Method
• The setRollbackOnly() method can control the
transaction state in the bean for a CMT.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 544/596
21-16 Copyright © 2004, Oracle. All rights reserved.
• The setRollbackOnly() method marks thecurrent transaction for rollback.
• If a transaction is marked for rollback, then the
container rolls back the transaction before
returning to the caller.
JDeveloper: Setting Transaction Attributes
1. Open the EJB Module Editor for a selected EJB.
2. Select the Container Transactions section.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 545/596
21-17 Copyright © 2004, Oracle. All rights reserved.
3. Use the buttons on the top-right corner to add,edit, or remove transaction attributes.
JDeveloper: Setting Transaction Attributes
1. Select the Transaction Attribute type from the list.
2. Select methods from the list and associate them
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 546/596
21-18 Copyright © 2004, Oracle. All rights reserved.
with the necessary transaction attributes.
Java Transaction API (JTA)
• JTA is used for managing transactions in J2EE.
• JTA transactions involve:
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 547/596
21-19 Copyright © 2004, Oracle. All rights reserved.
– Enlisting resources: Single-phase commit or two-phase commit
– Demarcating transactions: BMT or CMT
• The JTA package provides an application interface(UserTransaction).
JTA: The UserTransaction Interface
• Allows applications to explicitly manage
transaction boundaries
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 548/596
21-20 Copyright © 2004, Oracle. All rights reserved.
• Encapsulates most of the functionality of atransaction 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); }
Bean-Managed Transactions Demarcation
• Is indicated by the value Bean for the
<transaction-type> element in the deployment
descriptor
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 549/596
21-21 Copyright © 2004, Oracle. All rights reserved.
descriptor
• Uses the UserTransaction interface of JTA to
demarcate and manage the transactions
programmatically
By using a UserTransaction object, the bean:
• Initializes a transaction context on the client
• Invokes the begin(), commit(), or rollback()
methods on the current transaction context tomanage the transactions
BMT Demarcation: Process
1. Retrieve the UserTransaction object from the
bean code by using a JNDI name.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 550/596
21-22 Copyright © 2004, Oracle. All rights reserved.
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.
Using UserTransaction Support in EJBs
Code example using BMT:
SessionContext ctx;
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 551/596
21-23 Copyright © 2004, Oracle. All rights reserved.
public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
}
public beanMethodA() {UserTransaction utx = ctx.getUserTransaction();
utx.begin();
do work ……
utx.commit();
}
Client-Demarcated TransactionsUsing UserTransaction
For Web applications (or EJB client) demarcation:
• Get an InitialContext object
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 552/596
21-24 Copyright © 2004, Oracle. All rights reserved.
• Look up java:comp/UserTransaction, and castto 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();
BMT Demarcation: Restrictions
• Session and message-driven EJBs can have bean-managed transactions if their <transaction-
type> element is set to Bean
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 553/596
21-25 Copyright © 2004, Oracle. All rights reserved.
type> 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 transactionbefore a business method ends.
• A stateless session bean must commit the
transaction before the business method returns.
Local and Global Transactions
• A local transaction:
– Is started and coordinated internally by the
resource manager
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 554/596
21-26 Copyright © 2004, Oracle. All rights reserved.
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
Single-Phase Commit
• Configure a data source:
– Use the default emulated data source configuration.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 555/596
21-27 Copyright © 2004, Oracle. All rights reserved.
– Modify the url attr ibute with the URL of yourdatabase.
• 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.
Data Source Revisited
• A data source is an instantiation of an object thatimplements the javax.sql.DataSource
interface.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 556/596
21-28 Copyright © 2004, Oracle. All rights reserved.
interface.
• You can use a data source to retrieve a connection
to a database server.
• A data source offers a portable, vendor-
independent method for creating JDBCconnections.
• J2EE applications use JNDI to look up
DataSource objects.• Data sources are defined in data-sources.xml.
• Data sources can be emulated or nonemulated.
Default data-sources.xml
<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 557/596
21-29 Copyright © 2004, Oracle. All rights reserved.
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleXADS"
ejb-location="jdbc/OracleDS"
connection-
driver="oracle.jdbc.driver.OracleDriver"
username="scott"
password="tiger"
url="jdbc:oracle:thin:@localhost:5521:oracle"inactivity-timeout="30"
/>
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
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 558/596
21-30 Copyright © 2004, Oracle. All rights reserved.
– 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
Retrieve Connection to Data Source
<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="hrCourseDS"
location="jdbc/CoreDS"
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 559/596
21-31 Copyright © 2004, Oracle. All rights reserved.
xa-location="jdbc/xa/hrCoreXADS"ejb-location="jdbc/hrCoreDS" ...
/>
<resource-ref>
<res-ref-name>jdbc/hrCoreDS</res-ref-name><res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Context ctx = new InitialContext();DataSource ds = (DataSource)
ctx.lookup("jdbc/hrCoreDS");
Connection conn = ds.getConnection();
ejb-jar.xml
data-sources.xml
Bean Code
Retrieve Connection to Data Source
<data-source ...
ejb-location="jdbc/hrCoreDS"...
/>
data-sources.xml
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 560/596
21-32 Copyright © 2004, Oracle. All rights reserved.
<resource-ref-mappingname="jdbc/HumanResourcesDS"
location="jdbc/hrCoreDS"/>
<resource-ref>
<res-ref-name>jdbc/HumanResourceDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/HumanResourceDS");
orion-ejb-jar.xml
ejb-jar.xml
Bean Code
Global Transaction Resource
Request Flow
• When an EJB requests a JDBC connection or
some other transactional resource, it gets
associated with the global transaction.
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 561/596
21-33 Copyright © 2004, Oracle. All rights reserved.
• 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
Resource Request Flow
Application(Bean)
Client1 3
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 562/596
21-34 Copyright © 2004, Oracle. All rights reserved.
Transactionmanager
(Oracle10g DB)
Resourceadapter
OC4J
2
4
5
6
7
8 9
Enlisting Database Resources
• The process of including SQL updates in a
transaction is called “ enlisting.”
• JTA automatically enlists databases opened with a
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 563/596
21-35 Copyright © 2004, Oracle. All rights reserved.
y pDataSource object in a global UserTransaction
object.
• Since JDK 1.2, a DataSource published into a
JNDI namespace is the recommended way tomake connections.
• If your global transaction involves more than one
database, then you must configure a two-phasecommit engine.
Summary
In this lesson, you should have learned how to:
• Describe bean-managed and container-managed
transactions
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 564/596
21-36 Copyright © 2004, Oracle. All rights reserved.
• Explain how OC4J supports one-phase and two-
phase transaction protocol logic
Practice 21-1: Overview
This practice covers the following topics:
• Deploying a Web application and entity bean with
CMT
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 565/596
21-37 Copyright © 2004, Oracle. All rights reserved.
• 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 theentity bean methods
A di B
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 566/596
Copyright © 2004, Oracle. All rights reserved.
Appendix B
Schema Descriptions
BMP E tit EJB
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 567/596
Copyright © 2004, Oracle. All rights reserved.
BMP Entity EJBsJ2EE Connector Architecture
BMP Bean: Example
• The example in this lesson creates a BMP entitybean with the following components:
– Remote interface: JobsBMP
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 568/596
D-2 Copyright © 2004, Oracle. All rights reserved.
– Home interface: JobsBMPHome
– Bean class: JobsBMPBean
– Primary key class: JobsBMPPK
– Exception class: JobSalException
– Deployment descriptor: ejb-jar.xml
• Client for the JobsBMP bean: JobsBMPClient
Remote Interface: JobsBMP
...
public interface JobsBMP extends EJBObject
{
void incrMinSal(double amt) throws
JobSalException, RemoteException;
id i M S l(d bl t) th
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 569/596
D-3 Copyright © 2004, Oracle. All rights reserved.
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;
}
Home Interface: JobsBMPHome
... public interface JobsBMPHome extends EJBHome
{
JobsBMP create() throws RemoteException,
CreateException;
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 570/596
D-4 Copyright © 2004, Oracle. All rights reserved.
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;
}
Primary Key Class: JobsBMPPK
import java.io.Serializable; public class JobsBMPPK implements Serializable
{ public String jobId;
public JobsBMPPK(String id)
{ this jobId = id; }
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 571/596
D-5 Copyright © 2004, Oracle. All rights reserved.
{ this.jobId = id; } public boolean equals(Object job)
{...}
public int hashCode()
{
return super.hashCode();
}
public String toString()
{ return jobId; }
}
User-Defined Exception:JobSalException
public class JobSalException extends Exception
{
public JobSalException()
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 572/596
D-6 Copyright © 2004, Oracle. All rights reserved.
public JobSalException(){ super(); }
public JobSalException(Exception e)
{ super(e.toString()); }
public JobSalException(String s){ super(s); }
}
Bean Class: JobsBMPBean
...
public class JobsBMPBean implements EntityBean {
public String id;
public String jobTitle;
public double maxSal;
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 573/596
D-7 Copyright © 2004, Oracle. All rights reserved.
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 instancecreated");}
...
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;
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 574/596
D-8 Copyright © 2004, Oracle. All rights reserved.
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);
}...
create() and ejbCreate()
Home
objectEntity Bean
instance
create()
EJB Object
ejbCreate()
primary key
EJB Container
1 2
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 575/596
D-9 Copyright © 2004, Oracle. All rights reserved.
Client
EJB
object
Table in database
345
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(
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 576/596
D-10 Copyright © 2004, Oracle. All rights reserved.
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 jobID " + primKey); }
ps.close();
}
catch (Exception e) { ... }
finally { closeConnection(); }return primKey;
}
Bean Class: JobsBMPBean
public void ejbActivate() { }
public void ejbPassivate() { }
public void setEntityContext(EntityContext ctx)
{ this.context = ctx; }
public void unsetEntityContext()
{ this.context = null; }
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 577/596
D-11 Copyright © 2004, Oracle. All rights reserved.
{ ; } 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(); }
}
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 " +
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 578/596
D-12 Copyright © 2004, Oracle. All rights reserved.
p p p (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");
}
...}
Bean Class: JobsBMPBean
public void ejbStore() {
JobsBMPPK key= (JobsBMPPK)context.getPrimaryKey();
String id = key.jobId;
try {conn = getConnection();
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 579/596
D-13 Copyright © 2004, Oracle. All rights reserved.
g (); 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();
}
...
}
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);}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 580/596
D-14 Copyright © 2004, Oracle. All rights reserved.
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; }
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;
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 581/596
D-15 Copyright © 2004, Oracle. All rights reserved.
{ 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();}
Bean Class: JobsBMPBean
private void closeConnection ()
{
try { if (rset != null) rset.close();}
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 582/596
D-16 Copyright © 2004, Oracle. All rights reserved.
catch (Exception e) {...}
try { if (ps != null) ps.close();}
catch (Exception e) {...}
try { if (conn != null) conn.close(); }catch (Exception e) {...}
}
Bean Class: JobsBMPBean
public double ejbHomeGetAvgMaxSal()
throws JobSalException
{
try {
conn = getConnection(); ps = conn.prepareStatement
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 583/596
D-17 Copyright © 2004, Oracle. All rights reserved.
p p p
("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");
}
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 > ? ");
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 584/596
D-18 Copyright © 2004, Oracle. All rights reserved.
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;
}
}
Deployment Descriptor
...<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>JobsBMP</ejb-name>
<home> demos.JobsBMPHome</home>
<remote>demos.JobsBMP</remote>
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 585/596
D-19 Copyright © 2004, Oracle. All rights reserved.
<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> ...
...
</enterprise-beans>
<assembly-descriptor>
<container-transaction>< th d>
Deployment Descriptor
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 586/596
D-20 Copyright © 2004, Oracle. All rights reserved.
<method>
<ejb-name>JobsBMP</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
<?xml version="1.0" standalone='yes'?>
...
<data-sources><data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"location="jdbc/OracleCoreDS"
Creating Data Source data-sources.xml
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 587/596
D-21 Copyright © 2004, Oracle. All rights reserved.
ocat o jdbc/O ac eCo e S
xa-location="jdbc/xa/OracleXADS"
ejb-location="jdbc/hrDS"connection-driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="hr"
password="hr"
inactivity-timeout="30"/>
</data-sources>
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)
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 588/596
D-22 Copyright © 2004, Oracle. All rights reserved.
{
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);
...
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( ));
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 589/596
D-23 Copyright © 2004, Oracle. All rights reserved.
jobsBMP.getJobTitle( ));
Collectioncol=jobsBMPHome.findByMaxSalLimit(15000);
Iterator it = col.iterator();while (it.hasNext())
{JobsBMP jobSals = (JobsBMP)it.next();System.out.println(jobSals.getMaxSal());
} }catch(Throwable ex) {...} }
...
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)
M i f t ti i
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 590/596
D-24 Copyright © 2004, Oracle. All rights reserved.
– Mainframe transaction processing
– Databases and nonrelational systems, and so on
• JCA simplifies the integration of diverse EISs. Adherence to the JCA specification makes an EIS
implementation portable across compliant J2EE
servers.
OC4J J2EE Connector Architecture
Basic J2EE Connector Architecture:
OC4J
Application
Contract
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 591/596
D-25 Copyright © 2004, Oracle. All rights reserved.
J2EE Application
Component
Resource
Adapter
Enterprise
Information
System
System
Contracts
(Quality of
Service)
What Is a Resource Adapter?
It is a driver used by a client application to connect toa specific EIS.
• OC4J provides support for two J2EE 1.3 types:
– A stand-alone resource adapter, which is found in aResource Adapter Archive (RAR) fi le for use by all
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 592/596
D-26 Copyright © 2004, Oracle. All rights reserved.
deployed applications
– An embedded resource adapter, which is bundled in
an EAR file for a specif ic enterprise application• Examples of resource adapters:
– JDBC or SQL for Java (SQLJ) drivers for database
connections
– ERP adapter to connector a specific ERP
Resource Adapter Deployment Descriptors
OC4J provides the following deployment descriptors
for resource adapters:
• ra.xml: A standard J2EE deployment descriptor
for developing an adapter
4j l C t i d l t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 593/596
D-27 Copyright © 2004, Oracle. All rights reserved.
• 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 theORACLEAS_HOME/j2ee/home/config directory.
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
D l i f th f l l i t
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 594/596
D-28 Copyright © 2004, Oracle. All rights reserved.
• Deploy in one of the following two ways:
– Using the Admin command-line tool (admin.jar)
– Manually through directory manipulation, byexpanding the .rar file contents into a user-
specified directory name <connector-name> below
the ORACLEAS_HOME/j2ee/home/<connector
directory> (which defaults toORACLEAS_HOME/j2ee/home/connectors)
Deploying Embedded Resource Adapters
• Embedded resource adapters are packaged and
deployed inside an Enterprise Application Archive
(EAR) file.
• Each application (from an EAR fi le) has one oc4j-connectors xml file
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 595/596
D-29 Copyright © 2004, Oracle. All rights reserved.
connectors.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.
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 operationswith an EIS
8/15/2019 Oracle10g Build J2EE Applications - Electronic Presentation.pdf
http://slidepdf.com/reader/full/oracle10g-build-j2ee-applications-electronic-presentationpdf 596/596
D-30 Copyright © 2004, Oracle. All rights reserved.
with an EIS
• Main interfaces and classes are:
– ConnectionFactory – Connection
– Interaction
– RecordFactory
– Record
(Use Sun’s Java J2EE Tutorial for more information.)