Вы находитесь на странице: 1из 406

Oracle Fusion Middleware 11g:

Build Java EE Applications


Volume I Student Guide
D53942GC10
Edition 1.0
January 2009
D57568
Copyright 2009, Oracle. All rights reserved.
Disclaimer
This document contains proprietary information and is protected by copyright and
other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered in
any way. Except where your use constitutes "fair use" under copyright law, you may
not use, share, download, upload, copy, print, display, perform, reproduce, publish,
license, post, transmit, or distribute this document in whole or in part without the
express authorization of Oracle.
The information contained in this document is subject to change without notice. If you
find any problems in the document, please report them in writing to: Oracle University,
500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
Restricted Rights Notice
If this documentation is delivered to the United States Government or anyone using
the documentation on behalf of the United States Government, the following notice is
applicable:
U.S. GOVERNMENT RIGHTS
The U.S. Governments rights to use, modify, reproduce, release, perform, display, or
disclose these training materials are restricted by the terms of the applicable Oracle
license agreement and/or the applicable U.S. Government contract.
Trademark Notice
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other
names may be trademarks of their respective owners.
Authors
Bijoy Choudhury
Gary Williams
Technical Contributors
and Reviewers
Ken Cooper
Joe Greenwald
Taj-ul Islam
Pete Laseau
Adam Leftik
Mike Lehmann
Jacobo Marcos
Glenn Maslen
Duncan Mills
Lynn Munsinger
Nagavalli Pataballa
Holger Rasmussen
Anand Sidgiddi
Glenn Stokol
Vasily Strelnikov
Bonnie Vaughan
Editors
Aju Kumar
Amitha Narayan
Graphic Designer
Priya Saxena
Publishers
Sujatha Nagendra
Joseph Fernandez
Contents




1 Introduction
Objectives 1-2
Course Objectives 1-3
Course Agenda 1-4
Fundamentals of Java EE Technology 1-9
Designing Java EE Applications 1-10
Developing a Web Application Using Servlets 1-11
Developing a Web Application Using JavaServer Pages 1-12
Accessing Resources with JNDI and Dependency Injection 1-13
Developing the Business Logic with Session Beans 1-14
Developing the Persistence Layer with JPA Entities 1-15
Manipulating JPA Entities with the EntityManager API 1-16
Developing the Business Logic with Web Services 1-17
Developing the Web Interface Using JavaServer Faces 1-18
Planning Navigation and Page Flow 1-19
Handling Application Events 1-20
Asynchronous Communication with Message-Driven Beans 1-21
Managing Transactions with Session and Message-Driven Beans 1-22
Securing Java EE Applications with JAAS 1-23
Packaging and Deploying Java EE Applications 1-24
Troubleshooting Java EE Applications 1-25
Summary 1-26

2 Fundamentals of Java EE Technology
Objectives 2-2
Java Platform, Enterprise Edition 2-3
Java EE Platform 2-4
Distributed Multitiered Applications 2-5
Benefits of the Java EE Platform 2-6
Java EE Platform and APIs 2-8
Quiz 2-11
Java EE Components 2-12
Business-Tier Components 2-13
Enterprise JavaBeans (EJB) 2-14
Enterprise JavaBeans Application Architecture 2-16

iii
Types of Enterprise JavaBeans 3.0 2-17
Enterprise JavaBeans 3.0 Component Architecture 2-18
Java Persistence API (JPA) 2-19
Quiz 2-21
Web Services 2-22
Java EE Web Services Architecture 2-23
Client-Tier Components 2-25
Java EE Web-Tier Components 2-26
Java EE Web Application Architecture 2-28
What Is a Servlet? 2-29
What Is a JavaServer Page? 2-30
What Is JavaServer Faces? 2-31
Web-Tier Components: Summary 2-32
Java EE Applications 2-33
Packaging Java EE Applications 2-34
Packaging Java EE Application Components 2-35
Security in Java EE Applications 2-36
Using Deployment Descriptors for Declarative Security 2-37
Quiz 2-38
Java EE Server 2-39
Oracle WebLogic Server 10.3 2-41
WebLogic Server Domain 2-42
WebLogic Server Servers 2-44
Administration Server 2-45
Managed Server 2-46
WebLogic Server Machines 2-47
JDeveloper and Java EE 2-48
Oracle JDeveloper 11g Environment 2-49
Oracle JDeveloper 11g Visual Design Tools 2-50
Summary 2-51
Practice: Overview 2-52

3 Designing Java EE Applications
Objectives 3-2
Realizing the Benefits of Java EE 3-3
Java EE Issues 3-4
Design Patterns 3-5
Java EE Design Patterns 3-6
Implementing a Session Facade Pattern 3-7
Defining the MVC Architecture 3-8
The Model 3-9

iv
The View 3-10
The Controller 3-11
Designing a Java EE Application 3-12
Quiz 3-13
Struts: Overview 3-14
Struts Components 3-15
Struts Architecture 3-16
Struts Page Flow Design 3-17
JSF and Struts 3-19
Implementing the User Interface with JSF and Core Java EE Patterns 3-20
Selecting a Persistence Strategy 3-21
Quiz 3-22
What Is a Data Source? 3-23
What Is a Connection Pool? 3-24
Benefits of Data Sources Plus Connection Pools 3-25
JDBC Data Source Architecture 3-26
Data Source Architecture: Connecting 3-27
Creating a Data Source in WebLogic Server 3-28
Summary 3-30
Practice: Overview 3-31

4 Developing a Web Application Using Servlets
Objectives 4-2
Servlets: Overview 4-3
About Java Servlets 4-4
Principal Features of Servlets 4-5
Life Cycle of Servlets 4-6
HTTP Servlets 4-7
Inside an HTTP Servlet 4-8
doGet() Method 4-9
doPost() Method 4-10
HttpServletRequest Object 4-11
HttpServletResponse Object 4-12
HttpSession 4-13
Session Objects 4-14
Methods for Invoking Servlets 4-15
Quiz 4-16
Handling Input: The Form 4-17
Handling Input: The Servlet 4-18
Initialization and Destruction 4-19

v
Error Handling 4-20
Debugging a Servlet 4-21
JDeveloper Environment 4-22
Servlet Mapping 4-23
Servlet Mapping in JDeveloper 4-24
Invoking a Servlet 4-25
Specifying Java EE Web Module Settings 4-26
Summary 4-27
Practice: Overview 4-28

5 Developing a Web Application Using JavaServer Pages
Objectives 5-2
JavaServer Pages 5-3
Comparing Servlets and JSPs 5-4
Invoking JSPs 5-5
Date.jsp 5-6
Date Servlet 5-7
Automated JSP Features 5-8
JSP Life Cycle 5-9
Basic JSP Elements 5-10
Declarations 5-11
Expressions 5-13
Scriptlets 5-14
Implicit Objects 5-15
Example 5-17
Quiz 5-19
Directives 5-20
include: Example 5-21
page Directive 5-22
JSP and JavaBeans 5-24
Using JavaBeans with JSP 5-25
scope Attribute of <jsp:useBean> Tag 5-27
Accessing and Setting Bean Properties 5-28
JSP XML Document 5-30
Traditional Syntax Versus XML Syntax 5-31
JSP Segments 5-33
Quiz 5-34
What Is a Tag Library? 5-35
Tag Interfaces 5-36
Tag Handlers 5-37

vi
Tag Library Descriptor 5-38
Implementing Simple Tags 5-39
JSP Expression Language 5-40
Expression Language Implicit Objects 5-41
JDeveloper and JSPs 5-42
Summary 5-43
Practice: Overview 5-44

6 Accessing Resources with JNDI and Dependency Injection
Objectives 6-2
Java Naming and Directory Interface 6-3
JNDI Structure 6-4
Naming Service 6-5
JNDI Tree 6-6
Contexts and Subcontexts 6-8
Referencing Java EE Resources with JNDI 6-9
Providing JNDI Properties 6-10
Referencing a Local Session EJB with JNDI 6-11
Referencing a Remote Session EJB with JNDI 6-12
JNDI State Replication 6-13
Quiz 6-14
What Are Annotations? 6-15
Dependency Injection 6-16
Types of Dependency Injection 6-18
Defining the @Resource Annotation 6-19
Using Java EE Resources with Dependency Injection 6-20
Working with Dependency Injection 6-21
Referencing EJBs with Dependency Injection 6-22
Summary 6-23
Practice: Overview 6-24

7 Developing the Business Logic with Session Beans
Objectives 7-2
What Is a Session Bean? 7-3
Stateless Versus Stateful Session Beans 7-4
Dependency Injection in EJB 7-5
Life Cycle of a Stateless Session Bean 7-6
Elements of a Stateless Session Bean 7-7
Defining the Stateless Session Bean 7-8
Analyzing the Remote and Local Interfaces 7-9
Creating a Test Client for the SLSB 7-11

vii
Life Cycle of a Stateful Session Bean 7-12
Passivation and Activation Concepts 7-14
Creating a Stateful Session Bean 7-15
Defining the Stateful Session Bean 7-16
Analyzing the Remote and Local Interfaces 7-17
Creating a Test Client for the SFSB 7-18
Calling a Stateless Bean from a Stateful Bean by Implementing DI 7-19
Interceptor Methods and Classes 7-20
Interceptor Method 7-21
Interceptor Classes 7-22
Summary 7-23
Practice: Overview 7-24

8 Developing the Persistence Layer with JPA Entities
Objectives 8-2
What Are JPA Entities? 8-3
Domain Modeling with Entities 8-5
Managing Persistence of Entities 8-6
Declaring an Entity 8-7
Mapping Entities 8-8
Quiz 8-9
Mapping Inheritance 8-10
Single-Table Strategy 8-12
Joined-Tables Strategy 8-14
Specifying Entity Identity 8-16
Generating Primary Key Values 8-17
Mapping Relationships Between Entities 8-19
Implementing One-to-One Relationships 8-21
Implementing Many-to-One Relationships 8-23
Implementing One-to-Many Relationships 8-25
Implementing Many-to-Many Relationships 8-26
Quiz 8-27
Managing Entities 8-28
Summary 8-29
Practice: Overview 8-30

9 Manipulating JPA Entities with the EntityManager API
Objectives 9-2
What Is EntityManager? 9-3
Managing an Entity Life Cycle with EntityManager 9-5

viii
Accessing an EntityManager Instance in an Application 9-7
Creating a Container-Managed EntityManager Instance 9-8
Creating an Application-Managed EntityManager Instance 9-9
Specifying Database Operations with the EntityManager API 9-10
Commonly Used Methods in the EntityManager Interface 9-11
Quiz 9-13
Inserting New Data 9-14
Deleting Data 9-15
Updating and Synchronizing the Entity with the Database 9-16
Updating Data 9-17
Finding an Entity by Primary Key 9-18
Quiz 9-19
What Is JPA Query API? 9-20
Retrieving Entities by Using the Query API 9-21
Writing a Basic JPQL Statement 9-22
Creating Named Queries 9-23
Writing Dynamic Queries 9-24
Summary 9-25
Practice: Overview 9-26

10 Developing the Business Logic with Web Services
Objectives 10-2
Web Service 10-3
Web Service Standards 10-4
SOAP: XML Messaging for Web Services 10-5
Web Services Description Language (WSDL) 10-6
UDDI Registry 10-7
Web Service Architecture 10-9
Quiz 10-11
Web Service Metadata for Java Platform (JSR-181) 10-12
Examining the JSR-181 Processor Model 10-13
Describing JSR-181 Annotations 10-14
Sample Annotated Java Web Service File 10-15
What Is JAX-WS? 10-16
Quiz 10-17
Web Service Development Approach 10-18
Bottom-Up Approach 10-19
Top-Down Approach 10-20
Developing a Web Service by Using the Top-Down Approach 10-21
Defining an XSD Schema 10-22

ix
Creating the WSDL Document 10-23
Modifying the WSDL Document 10-25
Creating the Web Service by Using Oracle JDeveloper 11g 10-26
Implementing the Web Service Logic 10-27
Summary 10-28
Practice: Overview 10-29

11 Developing the Web Interface Using JavaServer Faces
Objectives 11-2
JSF: Overview 11-3
JSF: Benefits 11-4
Key Terms 11-5
JSF Architecture 11-6
JSF Components 11-8
JSF UI Components 11-9
JSF Component Architecture 11-10
Quiz 11-11
Tag Handlers and Component Trees 11-12
Tag Libraries 11-13
Configuration Files 11-14
JSF Renderers 11-15
Managed Beans 11-16
Expression Language 11-17
Life Cycle of a JSF Page 11-18
JSF Life Cycle: Initial Request 11-19
JSF Life Cycle: Postback 11-20
Quiz 11-22
Using JSF Tag Libraries 11-23
JSF Applications 11-24
JSF and JDeveloper 11g 11-25
JSF Navigation Diagram 11-26
Adding to JSF with ADF Faces 11-27
Using ADF Faces Layout Components 11-28
Creating Resizable Panes 11-29
Creating Collapsible Panes with the Panel Splitter Component 11-30
Creating Collapsible Panes with the Panel Accordion 11-31
Panel Accordion Overflow 11-32
Setting Panel Accordion Properties 11-33
Creating Titled Sections and Subsections 11-35
Grouping Related Components 11-36
Arranging Items Around a Central Area 11-37

x
Summary 11-39
Practice: Overview 11-40

12 Planning Navigation and Page Flow
Objectives 12-2
Traditional Navigation 12-3
What Is JSF Navigation? 12-4
JSF Navigation: Example 12-5
JSF Navigation Rules 12-6
faces-config Console 12-8
faces-config.xml 12-9
JSF Navigation Modeler 12-10
JSF Navigation Diagram 12-11
Navigation Elements 12-12
Global Rules 12-14
Pattern-Based Rules 12-15
JSF: Example 12-16
JSF Navigation: Example 12-18
Using the JSF Configuration Editor 12-21
Managed Beans 12-22
Creating Managed Beans 12-24
Managed Bean: Example 12-25
Setting Managed Bean Scope 12-26
Relationships Between Managed Beans 12-27
Managed Properties 12-28
Managed Properties: Examples 12-29
Using the Managed Bean on the JSF Page 12-31
Summary 12-32
Practice: Overview 12-33

13 Handling Application Events
Objectives 13-2
JSF Event Model 13-3
Types of Events 13-4
Action Events 13-5
Creating Action Events 13-6
Value Change Events 13-7
Creating Value Change Events 13-8
Event Listener Classes 13-9
Handling Action Events 13-10
Handling Value Change Events 13-11

xi
Event and Listener Execution Order 13-12
Validation in the JSF Life Cycle 13-13
Creating Custom Exception Handlers 13-15
Registering an Exception Handler 13-16
Changing Life Cycle Exception Reporting 13-17
JavaServer Faces Validators 13-18
Creating Backing Bean Validation in JDeveloper 13-19
Backing Bean Validator: Code Example 13-20
Input Validation 13-21
Summary 13-22
Practice: Overview 13-23

14 Asynchronous Communication with Message-Driven Beans
Objectives 14-2
Messaging Systems 14-3
Message-Oriented Middleware 14-4
Java Message Service 14-5
JMS Application Architecture 14-6
Point-to-Point Queue 14-7
Publish-Subscribe Topics 14-8
Quiz 14-9
WebLogic Server JMS Features 14-10
JMS Architecture: Connecting 14-11
JMS Architecture: Sending Messages 14-12
Transacted Messaging 14-13
WebLogic Server JMS Server 14-14
Creating a JMS Server 14-15
Connection Factory 14-16
JMS Destination 14-17
Creating a Queue Destination 14-18
Message-Driven Beans 14-20
Life Cycle of a Message-Driven Bean 14-21
Creating a Message-Driven Bean 14-22
Creating a JMS/MDB Client 14-24
Summary 14-26
Practice: Overview 14-27

15 Managing Transactions with Session and Message-Driven Beans
Objectives 15-2
What Is a Transaction? 15-3
Example of a Transaction 15-4

xii
Types of Transactions 15-5
Transaction Management 15-7
Two-Phase Commit Protocol 15-8
Successful Two-Phase Commit 15-9
Unsuccessful Two-Phase Commit 15-10
Quiz 15-11
Java Transaction API (JTA) 15-12
EJB Transaction Model 15-13
Managing Transactions with EJBs 15-14
Types of Transaction Management 15-16
Container-Managed Transactions 15-17
Transaction Attribute: REQUIRED 15-18
Transaction Attribute: SUPPORTS 15-19
Transaction Attribute: MANDATORY 15-20
Transaction Attribute: NEVER 15-21
Transaction Attribute: REQUIRES_NEW 15-22
Transaction Attribute: NOT_SUPPORTED 15-23
Quiz 15-24
CMT: setRollbackOnly() 15-25
Container-Managed Transaction: Example 15-26
Java Transaction API (JTA) 15-27
JTA: UserTransaction Interface 15-29
Bean-Managed Transactions 15-30
Bean-Managed Transaction: Example 15-31
BMT Demarcation: Restrictions 15-32
Enlisting Database Resources 15-33
Summary 15-34
Practice: Overview 15-35

16 Securing Java EE Applications with JAAS
Objectives 16-2
Goals of Java EE Security Architecture 16-3
Overview of Java EE Security Architecture 16-4
Java Authentication and Authorization Service (JAAS) 16-5
Authorization of a Client 16-8
Quiz 16-9
Security Process Architecture 16-10
Security Services 16-11
Security Realms 16-12
Users and Groups 16-13

xiii
Configuring New Users in WebLogic Server 16-14
Adding Users to Groups 16-16
Logical Roles 16-17
Quiz 16-19
Configuring Security 16-20
Determining Protected Resources 16-21
Defining the Logical Roles 16-22
Defining and Using Logical Roles in Web Applications (web.xml) 16-23
Defining and Using Logical Roles in EJBs (ejb-jar.xml) 16-24
Mapping Logical Roles to Users and Groups 16-25
Setup Authentication 16-26
Authentication Examples 16-27
Setting Access Control with JDeveloper 16-28
Creating Web Application Security Roles 16-29
Web Application Login Authentication 16-30
Web Application Authorization 16-31
EJB Security Roles 16-32
Security Annotation: Example 16-33
Summary 16-34
Practice: Overview 16-35

17 Packaging and Deploying Java EE Applications
Objectives 17-2
Deploying Java EE Applications 17-3
Packaging Business-Tier Components 17-5
Packaging Web Applications 17-6
Web Application Structure 17-7
Configuring Web Applications 17-9
What Is web.xml? 17-10
What Is weblogic.xml? 17-11
Web Application Archive 17-12
Creating Web Application Archives 17-13
Quiz 17-14
EJB Application Directory Structure 17-15
Java EE Enterprise Application (EAR) 17-17
Creating EJB Archives 17-18
Creating Enterprise Archives 17-19
Deploying Entities 17-20
Persistence.xml File 17-21
Configuring Oracle WebLogic ServerSpecific Features 17-22

xiv
Deploying with the Oracle WebLogic Server Console 17-23
Deploying with Oracle JDeveloper 17-24
What Is Ant? 17-25
Ant Build Files 17-26
A Sample build.xml File 17-27
Creating a JAR File by Using Ant Task 17-28
Creating a WAR File by Using Ant Task 17-29
Creating an EAR File by Using Ant Task 17-30
Deploying an Application by Using Ant Task 17-31
Packaging Best Practices for Production Environments 17-32
Summary 17-33

18 Troubleshooting
Objectives 18-2
Troubleshooting Basics 18-3
Diagnosing the Problem 18-4
Requesting Help 18-5
Creating Test Cases 18-6
Java Logging 18-7
Configuring Java Logging 18-8
Sending Logger Output to a File 18-9
Turning on Diagnostics in JDeveloper 18-10
Sample Java Clients 18-11
Sample Client for Web Service 18-12
Tools and Utilities 18-13
Identifying Search Paths with FileMon 18-14
Testing Java Code with JUnit 18-15
Analyzing HTTP Requests 18-16
Debugging with JDeveloper 18-17
Summary 18-18

Appendix A: Practices and Solutions

B Working with ADF Faces Components
Objectives B-2
Using ADF Faces Layout Components B-3
Adding Spaces and Lines B-4
Stretching Components B-5
Enabling Automatic Component Stretching B-6
Stretching a Table Column B-7
Creating Resizable Panes B-8

xv
Printing Layout Panel Content B-9
Creating Collapsible Panes with the Panel Splitter Component B-10
Creating Collapsible Panes with the Panel Accordion B-11
Panel Accordion Overflow B-13
Setting Panel Accordion Properties B-14
Arranging Items in Columns or Grids B-15
Creating Stacked Tabs B-17
Hiding and Displaying Groups of Content B-18
Arranging Items Horizontally or Vertically, with Scrollbars B-20
Displaying Table Menus, Toolbars, and Status Bars B-22
Creating Titled Sections and Subsections B-24
Grouping Semantically Related Components B-25
Displaying a Bulleted List B-26
Displaying Items in a Content Container Offset by Color B-27
Arranging Items Around a Central Area B-28
Using ADF Faces Skins B-30
Using Dynamic Page Layout B-31
Using Expression Language to Conditionally Display Components B-32
Characteristics of Partial Page Rendering (PPR) B-33
Enabling PPR Declaratively B-34
Native PPR Example B-36
Declarative PPR Example B-37
Enabling PPR Programmatically B-39
Conforming to PPR Guidelines B-40
Summary B-41

Index

xvi
Copyright 2009, Oracle. All rights reserved.
Introduction
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Identify the course objectives
Discuss the course agenda
Discuss the contents covered in the course
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 3
Copyright 2009, Oracle. All rights reserved.
Course Objectives
After completing this course, you should be able to:
Describe the Java EE 5 standards and their APIs
Design Java EE applications by using the Model-View-
Controller (MVC) architecture and Session Facade pattern
Build the business tier by using the Enterprise JavaBeans
3.0 (EJB) components, Java Persistence API (JPA)
entities, and Web services
Build the Web tier by using the JavaServer Faces (JSF)
framework
Implement asynchronous messaging by using Message-
Driven Beans (MDB)
Secure the Java EE application with Java Authentication
and Authorization Service (JAAS)
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 4
Copyright 2009, Oracle. All rights reserved.
Course Agenda
Topics for the first day
Lesson 1: Introduction
Lesson 2: Fundamentals of Java EE Technology
Lesson 3: Designing Java EE Applications
Lesson 4: Developing a Web Application Using Servlets
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 5
Copyright 2009, Oracle. All rights reserved.
Course Agenda
Topics for the second day
Lesson 5: Developing a Web Application Using JavaServer
Pages (JSP)
Lesson 6: Accessing Resources with JNDI and
Dependency Injection
Lesson 7: Developing the Business Logic with Session
Beans
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 6
Copyright 2009, Oracle. All rights reserved.
Course Agenda
Topics for the third day
Lesson 8: Developing the Persistence Layer with JPA
Entities
Lesson 9: Manipulating JPA Entities with the
EntityManager API
Lesson 10: Developing the Business Logic with Web
Services
Lesson 11: Developing the Web Interface Using
JavaServer Faces
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 7
Copyright 2009, Oracle. All rights reserved.
Course Agenda
Topics for the fourth day
Lesson 12: Planning Navigation and Page Flow
Lesson 13: Handling Application Events
Lesson 14: Asynchronous Communication with Message-
Driven Beans
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 8
Copyright 2009, Oracle. All rights reserved.
Course Agenda
Topics for the fifth day
Lesson 15: Managing Transactions with Session and
Message-Driven Beans
Lesson 16: Securing Java EE Applications with JAAS
Lesson 17: Packaging and Deploying Java EE Applications
Lesson 18: Troubleshooting Java EE Applications
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 9
Copyright 2009, Oracle. All rights reserved.
Fundamentals of Java EE Technology
Describe the Java Platform, Enterprise Edition (Java EE)
platform.
Define the components of a Java EE application.
Identify the deployment options for a Java EE application.
List the security options available in Java EE applications.
Fundamentals of Java EE Technology
Java EE is the standard development platform for Web-based Java applications and it provides
the foundation for the course. In this lesson, you learn what Java EE is and how it helps to build
portable, robust, and scalable Java EE applications. After they are built, Java EE applications are
deployed to a Java EE server, such as Oracle WebLogic Server.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 10
Copyright 2009, Oracle. All rights reserved.
Designing Java EE Applications
Identify the Java EE design patterns and their purpose.
Describe the Model-View-Controller (MVC) architecture.
Define the purpose and role of Struts.
Define the purpose and role of JSF.
Describe some important concepts and terminology used
in Oracle WebLogic Server.
Designing Java EE Applications
This lesson deals with the design of Java EE applications. After working for several years with
the object-oriented (OO) programming concepts, developers found that the best applications
follow similar patterns. The Java EE architectural design pattern for the interactive enterprise
application is known as Model-View-Controller (MVC). The MVC pattern is ideally suited for
the kind of application that combines distributed application logic with a complex user interface.
This lesson introduces the MVC design pattern, and describes how it can help you design Java
EE applications that are easier to reuse and maintain. You will also learn about the fundamental
concepts and terminology used in Oracle WebLogic Server, which is being used as the Java EE
applications deployment and execution platform in this course.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 11
Copyright 2009, Oracle. All rights reserved.
Developing a Web Application Using Servlets
Define the role of servlets in a Java EE application.
Describe the servlet life cycle.
Describe the request and response architecture.
Implement the HTTP servlet methods.
List the Java EE servlet mapping techniques.
Handle errors in a servlet.
Create and run a servlet in JDeveloper.
Developing a Web-Application Using Servlets
Servlets are the foundation of all the other Web technologies. They provide the core API used to
run JSP. A servlet is a platform-independent, server-side Java component used to extend the
capabilities of a Web server. Using servlets, you dynamically customize content, function, and
the look-and-feel of your Web pages. This lesson examines the servlet technology architecture,
and shows you how to create a servlet in JDeveloper. You also see how to deploy a servlet in the
WebLogic Java EE server.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 12
Copyright 2009, Oracle. All rights reserved.
Developing a Web Application Using JavaServer
Pages
Describe the relationship between JSP and servlets.
List the implicit objects on JSP pages.
Describe the semantics of JSP tags.
Create a JSP segment.
Explain the use of JSP tag files.
Describe custom tags and expression language.
Run and debug a JSP-based application.
Developing a Web-Application Using JavaServer Pages
The JSP specification is closely related to the servlet specification. It enables you to create Web
applications in a more productive manner. This lesson provides a detailed treatment of JSPs and
their roles in the Model-View-Controller (MVC) framework. JDeveloper provides a complete
environment for the creation, editing, and debugging of JSP pages. You learn how to use these
features in JDeveloper to simplify the development of JSP pages.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 13
Copyright 2009, Oracle. All rights reserved.
Accessing Resources with JNDI
and Dependency Injection
Describe the Java Naming and Directory Interface (JNDI)
Locate or look up resources and EJBs by using:
JNDI APIs
Dependency injection
Accessing Resources with JNDI and Dependency Injection
The Java Naming and Directory Interface (JNDI) is a Java API for directory service that allows
Java clients to discover and look up data and objects by using a name. This lesson describes the
JNDI and its implementation in Oracle WebLogic Server. You learn how to reference resources
(such as a data source or an EJB) in Java EE applications by using JNDI. This lesson also
provides an introduction to injecting resources by using dependency injection (DI). DI enables
one component to call another component or resources through interfaces. The components are
glued together by using configuration, instead of code.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 14
Copyright 2009, Oracle. All rights reserved.
Developing the Business Logic with Session
Beans
Describe session beans.
Create stateless and stateful session beans by using
annotations.
Describe the passivation and activation of stateful session
beans.
Use interceptor methods and classes.
Developing the Business Logic with Session Beans
A session bean implements one or more business processes. For example, it can retrieve and
update inventory data in a database. This lesson explains the types of session beans and their life
cycles. You use Oracle JDeveloper 11g to develop a session bean as a facade for the persistence
layer of an application.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 15
Copyright 2009, Oracle. All rights reserved.
Developing the Persistence Layer with JPA
Entities
Create a JPA entity.
Select a primary key field.
Perform O-R mapping by using annotations.
Map inheritance between entities.
Map relationships between entities.
Developing the Persistence Layer with JPA Entities
The new Java Persistence API (JPA), which simplifies the entity persistence model and adds
capabilities that were not available in EJB 2.1 technology, is a major enhancement in EJB
technology. The Java Persistence API in EJB 3.0 offers developers an entity programming
model that is both easier to use, and yet richer. In this lesson, you examine the role of the JPA
entity in providing the persistence layer for the model. An entity is a regular JavaBeans
component (also known as a POJO, or Plain Old Java Object) with properties that map to
columns in the database table. In this lesson, you learn how to use the JPA entity (or simply
entity) to map to database tables. You use JDeveloper to build and test an entity.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 16
Copyright 2009, Oracle. All rights reserved.
Manipulating JPA Entities with the
EntityManager API
Declare an EntityManager reference.
Look up an EntityManager reference by using
dependency injection.
Use the EntityManager API to:
Find an entity by its primary key
Insert a new entity
Modify an existing entity
Delete an entity
Execute dynamic queries with the Query API.
Write simple JPQL queries.
Manipulating JPA Entities with the EntityManager API
This lesson deals with a set of APIs and interfaces that you use to insert, update, delete, and
modify entities. EntityManager is an API that manages the life cycle of the entity instances.
You also learn about the JPA Query API that enables you to use either Java Persistence Query
Language (JPQL) or SQL to create and execute queries on the entity instances.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 17
Copyright 2009, Oracle. All rights reserved.
Developing the Business Logic with Web
Services
Describe Web service technologies.
Identify the role of SOAP, WSDL, and UDDI in Web
services.
Decide on the Web service development approach.
Develop Web services by using the top-down approach
with JDeveloper.
Developing the Business Logic with Web Services
A Web service is a technology (based on a set of standards) that provides a solution for
application-to-application communication and enterprise application integration. This lesson
provides an overview of Web services, and covers some of the de facto standards such as Simple
Object Access Protocol (SOAP), Web Services Description Language (WSDL), and Universal
Description, Discovery, and Integration (UDDI). You also learn about the different approaches
of the Web services development, and use Oracle JDeveloper 11g as the development tool.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 18
Copyright 2009, Oracle. All rights reserved.
Developing the Web Interface Using JavaServer
Faces
Describe the purpose of JSF.
Use JSF components.
Explain the use of managed beans.
Describe the life cycle of a JSF application.
Explain the role of the JSF tag libraries.
Describe how JDeveloper supports JSF.
Create a JSF-based JSP in JDeveloper.
Developing the Web Interface Using JavaServer Faces
In this lesson, you learn about JSF, which is JSP that contains special user interface (UI)
components. Like JSPs, JSF supports the MVC framework and is, therefore, a valuable
technology for building the view component of Java EE applications. You learn that JDeveloper
provides a feature-rich development environment for building JSF pages quickly and easily.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 19
Copyright 2009, Oracle. All rights reserved.
Planning Navigation and Page Flow
Use a JSF Navigation diagram to plan the pages of an
application and the navigation between them.
Describe JSF Navigation.
Describe the types of JSF Navigation cases.
Create a backing bean for a JSF page.
Planning Navigation and Page Flow
In this lesson, you learn how to use JSF to control navigational and data flow within an
application. The JSF Navigation diagram provides a way to visually design navigation and flow,
handle interactions with business services, and determine which page to display. Additionally,
JSF components are mapped to managed beans, which control user actions on the components
themselves.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 20
Copyright 2009, Oracle. All rights reserved.
Handling Application Events
Define the types of JSF events.
Create event listeners for a JSF application.
Describe how the JSF life cycle handles validation.
List the types of validation provided by JSF.
Handling Application Events
In any application, it is important to initiate actions based on specific events. JSF allows events
to be specified for user interface (UI) components. A JSF application can listen for events such
as user input, and then use built-in validator and data converter classes to manipulate data. In
this lesson, you learn how to use built-in validator and converter classes, as well as how to create
custom classes for handling UI events.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 21
Copyright 2009, Oracle. All rights reserved.
Asynchronous Communication with
Message-Driven Beans
Identify the features of a messaging system.
Describe the Java Message Service (JMS) architecture.
Configure a Java Message Service.
Create a Message-Driven Bean (MDB).
Create a JMS/MDB client.
Asynchronous Communication with Message-Driven Beans
All applications contain components that need to communicate between each other. Application
messaging can either be direct (synchronous) or indirect (asynchronous). Message-Driven Beans
process indirect messages between processes. Other uses of messaging include system
integration and distributed system communication. In this lesson, you learn about the Java
Message Service and message beans, and how they facilitate communication between the
components in an application.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 22
Copyright 2009, Oracle. All rights reserved.
Managing Transactions with Session and
Message-Driven Beans
Choose the appropriate type of transaction management.
Set the transaction attribute for container-managed
transactions.
Create transaction demarcations.
Managing Transactions with Session and Message-Driven Beans
This lesson covers the application transaction management by using Enterprise JavaBeans. You
will learn the fundamental concepts of implementing a transaction, different types of
transactions, transaction management by using transaction manager and resource manager, the
EJB transaction model, and the implementation of Container-Managed Transaction and Bean-
Managed Transaction.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 23
Copyright 2009, Oracle. All rights reserved.
Securing Java EE Applications with JAAS
Explain the Java EE application security design.
Describe the Java Authentication and Authorization
Service (JAAS).
Implement JAAS security for Web applications and
Enterprise JavaBeans (EJB).
Securing Java EE Applications with JAAS
Java Authentication and Authorization Service (JAAS) is a framework that provides a Java API
package to enable applications to authenticate and enforce security. This lesson deals with
securing Java EE application by implementing JAAS.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 24
Copyright 2009, Oracle. All rights reserved.
Packaging and Deploying Java EE Applications
Deploy Java EE applications to the WebLogic server
environment.
Deploy applications by using:
Console
Command-line
JDeveloper
Packaging and Deploying Java EE Applications
Java EE enables enterprises to separate the role of an application developer and an application
deployer. However, in many cases, developers are responsible for deploying the applications
they create to a Java EE server. This lesson provides detailed steps for deploying applications to
Oracle WebLogic Server 10.3. You learn about the different Java EE deployment descriptors
(such as web.xml and ejb-jar.xml), and also WebLogic specific deployment descriptors
(such as weblogic-web.xml).
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 25
Copyright 2009, Oracle. All rights reserved.
Troubleshooting Java EE Applications
Use JDeveloper and tools for logging and diagnostics.
Test a business service in isolation from views or
controllers.
Make use of FileMon, JUnit, and HTTP Analyzer.
Troubleshooting Java EE Applications
As much as you like to think of your first-cut application as flawless, there are times when you
need to fix problems. In this lesson, you learn how to identify problems in Java EE applications
and to create simple test harnesses to reproduce the error. You learn about the various tools that
are available to help you troubleshoot.
Oracle Fusion Middleware 11g: Build Java EE Applications 1 - 26
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned to:
Identify the course objectives
Discuss the course agenda
Discuss the contents covered in the course
Copyright 2009, Oracle. All rights reserved.
Fundamentals of Java EE Technology
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Describe the Java Platform, Enterprise Edition (Java EE)
platform
Define the components of a Java EE application
Identify the deployment options for a Java EE application
List the security options available in Java EE applications
Objectives
Java EE is the standard development platform for Web-based Java applications and it provides
the underlying structure for the course. In this lesson, you learn what Java EE is and how it helps
in building portable, robust, scalable Java EE applications. After they are built, Java EE
applications are deployed to a Java EE server, such as Oracle WebLogic Server.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 3
Copyright 2009, Oracle. All rights reserved.
Java Platform, Enterprise Edition
Java Platform, Enterprise Edition (Java EE) is a standard for
developing and implementing enterprisewide applications:
It provides support for multitier applications.
It is designed to help improve the process of developing,
deploying, and implementing enterprisewide applications.
Java Platform, Enterprise Edition
Java Platform, Enterprise Edition is the industry standard for developing portable, robust,
scalable, and secure Java applications. It was first proposed by Sun Microsystems and has been
included in the Java Community Process to make it a part of the open systems movement.
Building on the solid foundation of Java Platform, Standard Edition (Java SE), Java EE provides
Web services, component model, management, and communications APIs that make it the
industry standard for implementing enterprise class Service-Oriented Architecture (SOA) and
Web 2.0 applications.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 4
Copyright 2009, Oracle. All rights reserved.
Java EE Platform
Multitiered, distributed application model
Supports component-based Java EE applications
Distributes the application logic to the appropriate tier on
the multitiered architecture
Java EE Platform
Java EE defines a platform for developing, deploying, and executing applications in a
multitiered, distributed application model. That is, the application logic of a Java EE application
can be divided into components based on their functions and distributed to the appropriate tier
on the multitiered architecture.
Client-tier components, such as a Web browser, run on the client machine.
Presentation logic is built with Web-tier components, such as JavaServer Faces (JSF) and
Java servlets that run on the Java EE server.
Server-side business logic is distributed as business-tier components that run on the Java
EE server. Enterprise JavaBeans (EJB) and Application Development Framework Business
Components (ADF BC) are examples of business-tier components.
Data is stored in the Enterprise Information System (EIS) tier that runs on the database
server, such as Oracle Database 11g.
The Java EE application components are developed in the Java programming language. When
the Java EE platform is used, the Java EE components are assembled into a Java EE application,
verified according to the Java EE specification, and deployed to the Java EE server. The
deployed applications are run and managed by the Java EE server.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 5
Copyright 2009, Oracle. All rights reserved.
Distributed Multitiered Applications
Application Clients Web Clients
Client tier
JSP/JSF Pages
Enterprise Beans Web Services
Web tier
Business tier
EIS tier
Entities Persistence tier
Servlets
Distributed Multitiered Applications
Although a Java EE application can consist of three or four tiers, Java EE applications are
generally considered to be three-tiered applications because they are distributed over three
locations: client machines, the Java EE server machine, and the database or legacy machines at
the back end. Three-tiered applications that run in this way extend the standard two-tiered client
and server model, by placing a multithreaded application server between the client application
and back-end storage.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 6
Copyright 2009, Oracle. All rights reserved.
Benefits of the Java EE Platform
Write once, run anywhere provides simplified component
development.
Multiple server products and vendors support the Java EE
standard, thus giving more deployment choices.
Integration with legacy systems through standard APIs is
possible.
It provides multiple development and design scenarios.
It allows multiple clients to share server business logic.
Benefits of the Java EE Platform
Java EE takes advantage of many features of Java Platform, Standard Edition (Java SE), such as
the write once, run anywhere portability. This portability is ensured because there are multiple
vendors who support the Java EE specification, making it easy to integrate distributed
applications.
Java EE allows for clean separation of business and presentation logic, making applications
easier to maintain. There are several design choices for Java EE development, including varied
client access. This is discussed later in the course.
The vendors who provide the Java EE platform are called Java EE Product Providers. A
vendor or person who creates Web components, enterprise beans, or application clients for use
in Java EE applications is called an Application Component Provider. A Tool Provider is a
vendor who creates development, assembly, and packaging tools that are used by the component
providers. These names are assigned along with various other Java EE roles that are discussed in
the following slide.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 7
Copyright 2009, Oracle. All rights reserved.
Benefits of the Java EE Platform
Java EE separates development tasks into specific skill areas:
Web component developers create JSF components.
Enterprise bean developers and business experts create
business logic and rules.
Application assembler and application deployer teams
handle assembly and deployment.
Benefits of the Java EE Platform (continued)
The Java EE platform allows for developer specialization by component type and functionality.
For example, an EJB developer can create business logic, focusing on the business rules of the
enterprise. These EJBs are used by Web component developers, who focus on the presentation
of data and the user interface. These components are assembled by an Application Assembler,
who is responsible for the deployment and administration of the application.
An Application Deployer is the company or person who configures and deploys the Java EE
application. An Application Administrator is a person who administers the computing and
networking infrastructure where the Java EE applications run.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 8
Copyright 2009, Oracle. All rights reserved.
Java EE Platform and APIs
Web client
Browser
Applet
container
Applet
Application
client
container
Application
client
Java SE
Web container EJB container
JSP Servlet EJB
Java SE
JAX-RPC
SAAJ
JAXR
JACC
Web Services
JMX
JCA
JTA
JAF
JMS
Java Mail
Database
HTTP/
HTTPS
RMI/IIOP
JDBC driver
JDBC driver
JAX-WS JPA JAXB
Java EE Platform and APIs
The Java EE server provides services to handle transaction and state management,
multithreading, resource pooling, and other complex low-level details. The services are provided
through implementation of packages defined by Java EE. They are called Java optional
packages (previously known as standard extensions relative to Java Platform, Standard
Edition [Java SE]). The Java EE 5 required API packages are the following:
Enterprise JavaBeans (EJB) 3.0: Provides support for Enterprise JavaBeans
Servlet 2.4: Defines the packaging and deployment of Web applications, whether
stand-alone or as part of a Java EE application
JavaServer Pages (JSP) 2.1: Depends and builds on the Servlet 2.4 specification to
support declarative, tag-based Web development
Java Message Service (JMS) 1.1: Provides support for both JMS point-to-point and
publish/subscribe messaging services
Java Transaction API (JTA) 1.0: Defines the interfaces used by applications and
Enterprise JavaBeans to start, and commit or abort transactions. It provides interaction
with a Transaction Manager for local and distributed transactions.
JavaMail 1.4: Allows access to email messages in message stores and the creation and
sending of email messages using message transport. JavaMail uses JAF to identify MIME
types.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 9
Java EE Platform and APIs (continued)
JavaBeans Activation Framework (JAF) 1.1: Provides support for MIME data types into
the Java platform. For example, if a browser obtains a JPEG image, this framework
enables the browser to identify that stream of data as a JPEG image.
Java API for XML Processing (JAXP) 1.2: Provides industry-standard SAX 2 and DOM
2 APIs, and a pluggable API enabling the use of different SAX and DOM parsers and
XSLT transform engines in the framework
Java EE Connector Architecture (JCA) 1.5: Provides a Java technology solution to the
problem of connectivity between the many application servers and todays enterprise
information systems (EIS). JCA is particularly important for integrating legacy and
non-Java EE systems and data repositories with Java EE applications.
Web Services for Java EE: Defines the capabilities that a Java EE application server
must support for deployment of Web service endpoints
Java API for XML-based RPC (JAX-RPC) 1.1: Defines client APIs for accessing Web
services and techniques for implementing Web service endpoints
SOAP with Attachments API for Java (SAAJ) 1.3: Allows manipulation of SOAP
messages. SAAJ is used by JAX-RPC to represent XML fragments and to access a SOAP
message in a JAX-RPC message handler.
Java API for XML Registries (JAXR) 1.0: Defines an API for client access to
XML-based registries, such as ebXML and UDDI registries
Java EE Management 1.0: Provides an API for management tools to query a Java EE
compatible server about its status, the applications deployed, and other Java EE server
features
Java Management Extensions (JMX) 1.2: Provides tools for building distributed,
Web-based, dynamic solutions for managing and monitoring devices, applications, and
service-driven networks
Java EE Deployment API 1.1: Enables deployment of Java EE components and
applications, and the development of platform-independent deployment tools
Java Authorization Service Provide Contract for Containers (JACC) 1.0: Defines a
contract between a Java EE server and an authorization policy provider
Java Architecture for XML Binding (JAXB) 2.0: Provides a convenient way to process
XML content using Java objects by binding its XML schema to Java representation
Java API for XML Web Services (JAX-WS) 2.0: Provides support for Web services that
use the JAXB API for binding XML data to Java objects
Java Persistence API (JPA): Is a Java standardsbased solution for persistence.
Persistence uses an object-relational mapping approach to bridge the gap between an
object-oriented model and a relational database.
Java EE containers also provide applications with the Java Platform, Standard Edition 1.5 APIs,
which include the following Java-compatible APIs (optional packages) as required for the Java
EE 5 specification:
Java Interface Definition Language (IDL): Allows applications to access any CORBA
object, written in any language, using the Internet Inter-ORB Protocol (IIOP) standard
Java Database Connectivity (JDBC) 3.0: Enables you to access any tabular data source
such as database, spreadsheets, or flat files
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 10
Java EE Platform and APIs (continued)
Remote Method Invocation- Internet InterORB Protocol (RMI-IIOP): Enables
creation of distributed Javabased applications, allowing methods of remote Java objects
to be invoked from other JVMs optionally on different hosts
Java Naming and Directory Interface (JNDI): Provides naming and directory
functionality to Java applications
Java Authentication and Authorization Service (JAAS): Enables services to
authenticate and enforce access controls upon users. It implements a Pluggable
Authentication Module (PAM) framework and supports user-based authorization.
Additional requirements include support for logging, networking, and preferences APIs.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 11
Copyright 2009, Oracle. All rights reserved.
Quiz
The Java EE platform provides a single development and
design scenario to develop applications.
1. True
2. False
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 12
Copyright 2009, Oracle. All rights reserved.
Java EE Components
Java EE applications are made up of components. A
component:
Is an application-level software unit
Can be easily updated as business needs change
Is reusable
There are several types of components:
Client-side components
Web components
Business-tier components
Java EE Components
A Java EE component is a self-contained functional software unit that is assembled into a Java
EE application with its related classes and files and that communicates with other components.
There are several types of Java EE components. The Java EE specification defines the following
Java EE components:
Application clients and applets are components that run on the client.
Java Servlet, JSF, and JSP technology components are Web components that run on the
server.
Enterprise JavaBeans components (enterprise beans) are business components that run on
the server.
Java EE components are written in the Java programming language and are compiled in the
same way as any program in the language. The difference between Java EE components and
standard Java classes is that Java EE components are assembled into a Java EE application,
verified to be well formed and in compliance with the Java EE specification, and are deployed to
production, where they are run and managed by the Java EE server.
This course focuses on the most widely used components, those of the Web and the business tier.
These components are reusablethat is, they are available to other components and
applications. For example, the business rules that are included in a software component called
Process Order can be used by multiple applications that allow customers to order the products
or services of a company.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 13
Copyright 2009, Oracle. All rights reserved.
Business-Tier Components
Business-tier components:
Are implemented by remote components, such as Web
services and EJBs
Handle business logic
Receive data from client programs
Encapsulate business data and rules
Process the data and communicate with the database and
the client program
Can be invoked by the Web-tier components
Business-Tier Components
EJBs and Web services are the components that run in the business tier. These distributed
components contain business logic that meets the needs of a particular business domain, such as
banking, order entry, or human resources management. The business-tier components can
receive data from client programs, process the data, and send the processed data to the database
server for storage. The business-tier components can also retrieve data from the database,
process it, and send it back to the client program.
The Web-tier components may invoke the business-tier components where the business logic is
handled. For example, a servlet may invoke an enterprise bean to insert new customer details
and return any processed data back to the client.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 14
Copyright 2009, Oracle. All rights reserved.
Enterprise JavaBeans (EJB)
Enterprise JavaBeans:
Is the server-side component written in Java
Contains the business logic of an enterprise application
Is hosted in EJB containers
Is platform independent
Provides remote services for clients
Uses JDBC/JPA to connect to a database
Enterprise JavaBeans (EJB)
Enterprise JavaBeans (EJB) is an architecture for developing transactional applications as
distributed components in Java. EJB is a powerful development methodology for distributed
application development. When applications are developed with enterprise beans, neither the
bean developer nor the client application programmer need to be concerned with details such as
transaction support, security, remote object access, and many other complicated and error-prone
issues. These are provided transparently for the developer by the EJB container.
EJBs offer portability. A bean that is developed on one EJB container runs on other EJB
containers that meet the EJB specification. Oracle WebLogic Server implements the EJB
specification by providing a server and a container that hosts Enterprise JavaBeans.
EJB specifies Remote Method Invocation (RMI) as the transport protocol. RMI is used as a
communication protocol between EJBs executing in different JVMs. They make calls to their
respective remote interfaces. In case of EJBs executing in a single Java Virtual Machine (JVM),
they make calls by using their local interfaces. EJBs access the EIS-tier database through JDBC.
EJBs are accessed using Javas RMI framework, which can be implemented with different
network protocols.
Additionally, a stateless session EJB can be exposed as a Web service. Web services are the
standard for building interoperable distributed applications that are platform and programming-
language independent.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 15
Enterprise JavaBeans (EJB) (continued)
The Java EE 5 platform delivers EJB 3.0, which is an enhanced version of EJB technology. The
new features of EJB 3.0 include Plain Old Java Object (POJO) programming, annotations
instead of verbose XML, heavy use of sensible defaults, and the Java Persistence API (JPA).
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 16
Copyright 2009, Oracle. All rights reserved.
Enterprise JavaBeans Application Architecture
Java EE server
Exposed as
Web service
Based on
RMI
Database
JDBC
Driver
Based on
HTTP/SOAP
EJB client
Web client
Enterprise
JavaBean
EJB
container
Web
container
WSDL
Enterprise JavaBeans Application Architecture
EJB is an architecture for developing transactional applications as distributed components in
Java. EJBs are server-side reusable Java components that:
Are hosted in EJB containers
Can be exposed as Web services (WSDL)
Can use JDBC to connect to a database
Are accessed using Javas Remote Method Invocation (RMI) framework, which can be
implemented with different network protocols such as RMI/Internet Inter-ORB Protocol
(IIOP) protocol
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 17
Copyright 2009, Oracle. All rights reserved.
Types of Enterprise JavaBeans 3.0
Entity
Used to model the persistence part of an application
Session Bean
Invoked by a client to perform a specific business operation
Message-driven bean
Triggered by messages sent to a messaging server, which
enables sending asynchronous messages between system
components
Types of Enterprise JavaBeans 3.0
Each bean type serves a specific purpose and can use a subset of EJB services. The real purpose
of bean types is to safeguard against overloading them with services that cross wires. Bean
classification also helps you understand and organize an application in a sensible way. For
example, bean types help you develop applications based on a layered architecture.
Entities: They are used to model the persistence part of an application. They are managed
by a persistence provider. A persistence provider is pluggable within the container and is
abstracted behind the Java Persistence API.
Session beans: They are invoked by a client to perform a specific business operation, such
as checking the credit history of a customer. As the name session implies, the bean
instance is available for the duration of a Unit of Work, and does not survive a server
crash or shutdown. A Session Bean can model any application logic functionality.
Message-driven beans: They also process business logic. However, message-driven beans
are different in an important way. Clients do not invoke message-driven bean methods
directly. Instead message-driven beans are triggered by messages sent to a messaging
server, which enables sending asynchronous messages between system components. Some
typical examples of messaging servers include IBM WebSphere MQ, SonicMQ, Oracle
Advanced Queuing, Tibco, and so on. Message-driven beans are typically used for robust
system integration or asynchronous processing.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 18
Copyright 2009, Oracle. All rights reserved.
Enterprise JavaBeans 3.0 Component
Architecture
Client
Session bean
Message-driven bean
Database
JPA Persistence Provider
Entity
Managed by the
EntityManager or
persistence provider
EJB container
Managed by the EJB
container
Managed by the EJB
container
JMS queue/topic
Enterprise JavaBeans 3.0 Component Architecture
The diagram shows the following three generic types of Enterprise JavaBeans:
Session beans: Execute business logic in the server and can be one of two types:
- A stateless bean that does not maintain state information across method calls
- A stateful bean that maintains state information across method calls
Entities: Provide business rules for data retrieved from and persisted to a data store, such
as a database. The entities are managed by a persistence provider through the
EntityManager API. The persistence provider is pluggable within the EJB 3.0
container and is abstracted behind the JPA.
Note: The Java Persistence API is completely separable from the EJB container. It means
that JPA can be implemented both inside a Java EE 5 application server, and outside an
EJB container in a Java Platform, Standard Edition 5 application.
Message-driven beans: Process messages obtained from a JMS resource called a
destination. A JMS destination can be:
- A queue, when using a point-to-point communication model
- A topic, when using a publish/subscribe communication model
Note: The diagram shows the topic/queue resource inside the Java EE container. However,
the message-transport layer could involve external sources, such as Oracle Advanced
Queuing (AQ) in an Oracle database or other message services.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 19
Copyright 2009, Oracle. All rights reserved.
Java Persistence API (JPA)
The Java Persistence API (JPA) deals with:
The way relational data is mapped to Java objects
(persistent entities)
The way these objects are stored in a relational database
so that they can be accessed at a later time
The continued existence of an entitys state even after the
application that uses it, expires
Java Persistence API (JPA)
The new Java Persistence API, which simplifies the entity persistence model and adds
capabilities that were not in EJB 2.1 technology, is a major enhancement in EJB technology.
JPA offers developers an entity programming model that is both easier to use, and yet richer.
For students who are familiar with EJB 2.x, here is a list of the simplifications and additions
provided by JPA:
Requires fewer classes and interfaces
Virtually eliminates lengthy deployment descriptors through annotations
Addresses most typical specifications through annotation defaults
Provides cleaner, easier, standardized object-relational mapping
Eliminates the need for lookup code
Adds support for inheritance, polymorphism, and polymorphic queries
Adds support for named (static) and dynamic queries
Provides a Java Persistence Query Language (JPQL)an enhanced EJB QL
Makes it easier to test entities outside the EJB container
Can be used outside the container
Can be used with pluggable, third-party persistence providers
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 20
Copyright 2009, Oracle. All rights reserved.
Java Persistence API (JPA)
JPA defines a standard for:
The ORM configuration metadata
The EntityManager API
The JPQL
Database JPA
Java EE
application
Application makes a database
call to save the data stored in
Java objects to a database
table.
JPA persists the Java
objects to the database
by implementing ORM.
Java Persistence API (JPA) (continued)
The Java Persistence API greatly simplifies Java persistence and provides an object-relational
mapping (ORM) approach that enables you to declaratively define how to map Java objects to
relational database tables in a standard, portable way.
The JPA also defines:
Standards for creating the ORM configuration metadata for mapping entities to relational
tables
The EntityManager API for performing create, read, update, and delete (CRUD) and
persistence operations for entities
Note: Entities are persistence objects that model persistent data stored in a relational
database.
The JPQL for searching and retrieving persisted application data
Note: JPA can be implemented both inside and outside the Java EE environment.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 21
Copyright 2009, Oracle. All rights reserved.
Quiz
Enterprise Java Beans can be categorized into:
1. Stateless Session Bean
2. Entity
3. Stateful Java Bean
4. Message-Driven Bean
Answers: 1, 2, 3
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 22
Copyright 2009, Oracle. All rights reserved.
Web Services
Web services use open XML-based standards and
transport protocols to exchange data with calling clients.
The Java EE platform provides the XML APIs and tools
needed to design, develop, test, and deploy Web services
and clients that fully interoperate with other Web services
and clients running on Java-based or non-Java-based
platforms.
Web Services
To write Web services and clients with the Java EE XML APIs, you pass parameter data to the
method calls and process the data returned; or for document-oriented Web services, you send
documents containing the service data back and forth. No low-level programming is needed
because the XML API implementations do the work of translating the application data to and
from an XML-based data stream that is sent over the standardized XML-based transport
protocols.
The translation of data to a standardized XML-based data stream is what makes Web services
and clients written with the Java EE XML APIs fully interoperable. This does not necessarily
mean that the data being transported includes XML tags because the transported data can itself
be plain text, XML data, or any kind of binary data such as audio, video, maps, program files,
computer-aided design (CAD) documents, and so on.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 23
Copyright 2009, Oracle. All rights reserved.
Java EE Web Services Architecture
Web services
directory
(UDDI)
Find a credit card
validation service.
Publish
1
2
3
Client application
(Online shopping)
XML interface (WSDL)
XML interface (WSDL)
Web service
(Validate credit card)
Invoke the validate
operation of the
credit card.
Java EE Web Services Architecture
The Web services architecture allows for loose integration of applications through the exchange
of SOAP messages. Information about Web services is published using the Web Service
Description Language (WSDL) in Web-service directories via Universal Description, Discovery
and Integration (UDDI).
The illustration in the slide shows the following:
1. A Validate credit card Web service is generated and published to the UDDI registry.
2. An Online shopping application (a Web service client) browses the UDDI registry to locate
the Validate credit card Web service. Here, the Online shopping application obtains the
WSDL definition that describes the Web service.
3. The Online shopping application can invoke any operation exposed by the Validate credit
card Web service. Operations in a Web service refer to methods that are exposed as Web
services.
Java classes, stateless session EJBs, Java Message Service (JMS) queue/topics, and PL/SQL
procedures can be exposed as Web services. The WSDL contains information about the Web
service, such as the name of the Web service operation, how many parameters it takes and their
types, and the Web service location. The Web services are registered with the UDDI registry for
lookup by client applications. The client can invoke the Web service with an instance of a proxy
class similar to invoking a method on the local machine.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 24
Java EE Web Services Architecture (continued)
Note: The Web Services Directory (UDDI) is an optional component in the Web services
architecture. A client application can directly access a Web service without browsing the Web
services directory if the Uniform Resource Identifier (URI) of the Web service is known to the
client application.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 25
Copyright 2009, Oracle. All rights reserved.
Client-Tier Components
A Web browser:
Is used for a Web-based Java EE application
Presents static or dynamic Web pages from
Web-tier components
An application client:
Is used for a non-browser-based Java EE application
Executes on the client machine
Can contain a graphical or command-line interface
Accesses middle-tier services
Requires installation on the client machine
Client-Tier Components
Web Browser Client
For a Web-based Java EE application, the users Web browser is the client component. The Web
browser downloads static or dynamic Web pages from the Web tier to a client machine.
Dynamic Web pages are generated by servlets, JSP, or JSF technologies from the Web tier. JSPs
or JSFs do not require Java plug-ins or security policy files to be downloaded to the client
machine.
A downloaded Web page can contain an embedded applet that executes in the JVM in the Web
browser. An applet may require a Java plug-in and a security file to successfully execute in the
users Web browser.
Web-based clients do not perform operations such as executing complex business rules,
connecting to the database, and querying the database. These operations are generally performed
by business-tier components.
Application Client
An application client executes on a client machine for a non-browser-based Java EE application.
It can contain a graphical user interface (GUI) created from Swing or Abstract Window Toolkit
(AWT) APIs, or a command-line interface. Application clients can directly access business-tier
components. They can also access a servlet that is running in the Web tier through an HTTP
connection.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 26
Copyright 2009, Oracle. All rights reserved.
Java EE Web-Tier Components
A Web tier may consist of:
Java servlets
JSPs
JSFs
Servlets and JSPs:
Work on a request-response model
Generate HTML dynamically
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
Java EE Web-Tier Components
Java EE Web-tier components can be either servlets or JSPs that can statically and dynamically
generate HTML, Wireless Markup Language (WML), or Extensible Markup Language (XML)
pages. Java servlets provide a simple, yet powerful API for generating Web pages by
dynamically processing the client requests and constructing responses. JSPs simplify the process
of dynamically generating the content by allowing Java as the scripting language inside HTML
pages. JSPs are translated and compiled into Java servlets, which are then run in a Web server
like any other servlet.
Web components can access the business-tier components that access the database by using
JDBC. Web components can handle requests from the client, such as form submission.
Following are some advantages of using Web components:
The HTML interface that is generated by a Web component is lightweight when compared
to applets that require heavyweight downloads to the clients at run time.
The HTML interface does not require prior installation on the client machines, whereas the
conventional clients require redeployment of the applications on the client machines.
The HTTP protocol, over which the clients request for Web pages is served, can pass
through most firewalls.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 27
Java EE Web-Tier Components (continued)
A combination of Web components and EJBs, thus provides:
Presentation logic for generating Web pages through Web components
Transactional business logic through EJBs
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 28
Copyright 2009, Oracle. All rights reserved.
Java EE Web Application Architecture
Client tier
Browser
applet
application
Web tier
JSF
JSP
Servlet
Business tier
EJBs / Web services /
POJOs
Java EE application server
HTTP
Java EE Web Application Architecture
There are three primary Java EE Web-tier technologies:
Servlets: A servlet is a server-side Java component that runs in an application servers
Web container. It responds to HTTP requests and is used to handle presentation logic such
as form validation or data formatting.
JSP: JSPs are an extension to servlets that allow Java code to be embedded in an HTML
page. JSPs are then compiled into servlets for run-time execution. JSPs can be extended
through the use of custom JSP tags to create reusable JSP tag libraries.
JSF: JSF is a Web application framework for simplified development of user interfaces
through the use of standard GUI components and are currently implemented as sets of JSP
custom tag libraries. JSF defines APIs, which can be easily extended to include more
robust, rich-client style components. Oracle ADF Faces is one such extension to JSF that
provides many enhanced user interface components for JSF application development,
including multiple renderers per client type, advanced tables, and color and date pickers,
along with a host of general components such as menus, command buttons, shuttle
choosers, and progress meters.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 29
Copyright 2009, Oracle. All rights reserved.
Client info (host name,
form data)
Success or failure
Process results
(access database).
Format results and produce
HTML.
Send the page back to client.
Browser Servlet
What Is a Servlet?
Request
Response
What Is a Servlet?
A servlet is a Java program that runs on a Java EE server and produces dynamic pages typically
in response to client requests. The pages are then sent back to the clients Web browser. The
output format for servlets usually is HTML, but any other output format, including XML, can be
used.
Before returning HTML pages, a servlet can perform any operation that a Java application can
perform. For example, in a business environment, servlets access the business objects, so that
you can send custom HTML pages and forms with embedded data to your end users.
Because servlets contain Java code, they are best suited for programs that perform more
processing than presentation. Presentation is best left to JSPs, which are discussed in the
following slide.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 30
Copyright 2009, Oracle. All rights reserved.
What Is a JavaServer Page?
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 easy modification of
the user interface
Focuses on presentation
What Is a JavaServer Page?
JSPs are servlets that are written differently. The JSP technology separates the user interface
from dynamic content generation, so that designers can easily change the overall page layout
without altering the dynamic content. The JSP technology supports a reusable component-based
design, making it easy and fast to build Web-based applications.
A key feature of the JSP technology is simplified page generation, HTML-like tags, and
scriptlets written in the Java programming language that encapsulate the logic that generates the
content for the page. By separating the presentation design from the application logic that
generates the data, the JSP-enabled pages make it easier for organizations to reuse and share
application logic through custom tags and JavaBeans-based components. This also separates the
job responsibilities of the Web designer and the Java programmer. For example, custom tags and
beans can be developed by the Java programmer and implemented by the Web designer.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 31
Copyright 2009, Oracle. All rights reserved.
What Is JavaServer Faces?
A JSF:
Is a server-side component framework for Web
applications
Implements the Model-View-Controller (MVC) framework
Provides separation of navigational and data flow
Is built for rapid application development (RAD) style
development
What Is JavaServer Faces?
JSF is a component-based framework for developing Web-based applications. JSF provides a
framework for using robust UI components in a consistent manner. JSF provides a RAD
environment for building Web applications. JSF is developer toolcentric so that developers can
use visual editors to create applications.
JSF also combines the functionality of a JSP with a built-in Controller. These parts make JSF a
true MVC framework.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 32
Copyright 2009, Oracle. All rights reserved.
Web-Tier Components: Summary
Web-tier components generate dynamic content.
Servlets:
Extend Web server functionality
Are best used for controlling the applications flow
JSPs:
Combine HTML (or other markup) and Java
Are best used for presentation logic
JSFs:
Are component based
Implement MVC
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 33
Copyright 2009, Oracle. All rights reserved.
Java EE Applications
Java EE applications consist of Java EE 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.
Java EE Applications
Java EE applications are server-side applications that contain standard components, such as
servlets, JSPs, JSFs, and EJBs. Applications are deployed in the form of modules that package
all necessary code for deployment to a Java EE server. Modules are archive files in a standard
format, specified by the Java EE architecture.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 34
Copyright 2009, Oracle. All rights reserved.
Packaging Java EE Applications
Assembly
Root
META-INF
Web
module
EJB
module
Application
Client module
Resource
Adapter module
application.xml EAR file structure
web.xml ejb-jar.xml
Packaging Java EE Applications
A Java EE application is delivered in an Enterprise Archive (EAR) file, a standard Java Archive
(JAR) file with an .ear extension. Using EAR files and modules makes it possible to assemble
different Java EE applications using some of the same components. No extra coding is needed; it
is only a matter of assembling (or packaging) various Java EE modules into Java EE EAR files.
An EAR file contains Java EE modules and deployment descriptors (such as web.xml and
ejb-jar.xml). A deployment descriptor is an XML document with an .xml extension that
describes the deployment settings of an application, a module, or a component. Because
deployment descriptor information is declarative, it can be changed without the need to modify
the source code. At run time, the Java EE server reads the deployment descriptor and acts upon
the application, module, or component, accordingly.
There are two types of deployment descriptors: Java EE and run time. A Java EE deployment
descriptor is defined by a Java EE specification and can be used to configure deployment
settings on any Java EE-compliant implementation. A run-time deployment descriptor is used to
configure Java EE implementation-specific parameters.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 35
Copyright 2009, Oracle. All rights reserved.
Packaging Java EE
Application Components
4. ejb.jar
Class files for enterprise beans and an
EJB deployment descriptor
1. webtier.war
Java servlets, JSP files, HTML, GIF files, and
a Web application deployment descriptor
2. JavaEEappClient.jar
Java EE application client (Java class), and
an application client deployment descriptor
3. Resource adapter (.rar)
Java interfaces, classes, native libraries,
and other documentation and the resource
adapter deployment descriptor
Java EE application.ear
Packaging Java EE Application Components
The diagram in the slide shows the components of a Java EE application.
A Web Archive (WAR) file that contains the archive of Web componentsJava servlets,
JSP files, HTML, GIF files, and a deployment descriptor that contains references of the
EJBs being accessed, in ejb-ref tags
A JAR file that contains the archive of a Java EE application client in the form of a Java
class, and a deployment descriptor that contains references to the EJBs from which the
business methods are being accessed. The Java EE application client is a Java application
that runs in an environment that allows it to access Java EE services.
An optional resource adapter archive (RAR), which is a driver that either an application
server or an application client uses to connect to a specific EIS. Examples of resource
adapters are JDBC drivers to connect to a relational database, or an ERP resource adapter
to connect to an ERP system.
A Java Archive (JAR) file that contains the archive of EJB componentsEJB class files,
EJB deployment descriptor that contains information about transaction attributes, security
roles, and so on
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 36
Copyright 2009, Oracle. All rights reserved.
Security in Java EE Applications
Security for Java EE application components is provided
by their containers.
A container provides two types of security:
Declarative security through deployment descriptors
Programmatic security embedded in the application
Annotations are used to specify information about security
within a class file.
Security in Java EE Applications
Java EE and Web services applications are made up of components that can be deployed into
different containers. Security for the components is provided by their containers. A container
provides two types of security: declarative and programmatic.
Declarative security expresses an application components security requirements using
deployment descriptors. Deployment descriptors are external to an application and include
information that specifies how security roles and access requirements are mapped into
environment-specific security roles, users, and policies.
Programmatic security is embedded in an application and is used to make security
decisions. Programmatic security is useful when declarative security alone is not sufficient
to express the security model of an application.
Annotations (also called metadata) enable a declarative style of programming and, therefore,
encompass both the declarative and programmatic security concepts. Users can specify
information about security within a class file. When the application is deployed, this information
can either be used by, or be overridden by the application deployment descriptor.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 37
Copyright 2009, Oracle. All rights reserved.
Using Deployment Descriptors for
Declarative Security
A deployment descriptor:
Is an XML document with an .xml extension
Is used by application developers to communicate how
security is to be set up for the deployed application
Enables an applications security structure, including roles,
access control and authentication requirements to be
expressed in a form external to the application
Is read at run time by the Java EE server which then acts
upon the application, module, or component, accordingly
Using Deployment Descriptors for Declarative Security
Declarative security expresses an application components security requirements by using
deployment descriptors. A deployment descriptor is an XML document with an .xml extension
that describes the deployment settings of an application, a module, or a component. Because the
deployment descriptor information is declarative, it can be changed without the need to modify
the source code. At run time, the Java EE server reads the deployment descriptor and acts upon
the application, module, or component, accordingly.
Different types of components use different formats, or schema, for their deployment
descriptors.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 38
Copyright 2009, Oracle. All rights reserved.
Quiz
Identify the components of Java EE Web Tier.
1. Stateless Session Bean
2. Servlet
3. MDB
4. JSP
5. JPA
Answers: 2, 4
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 39
Copyright 2009, Oracle. All rights reserved.
Java EE Server
The Java EE server provides:
Containers for each component type of a Java EE
application
System-level services to components:
Naming and directory services (JNDI)
Security services for Web components and EJBs (JAAS)
Transaction architecture (JTA)
Remote client connectivity:
Enterprise beans (RMI/IIOP)
Servlet/JSP (HTTP, HTTPS, FTP)
Java EE Server
The Java EE server is the run-time portion of a Java EE product. A Java EE server provides EJB
and Web containers. The Web-tier and business-tier components can themselves be clients for
the other Java EE application components.
An advantage of the Java EE platform is that all the container providers must abide by the same
Java EE standards. This is much easier for developers because the application assembly is the
same in any Java EE-compliant environment.
The Java EE server provides system-level services to the Java EE application components:
Java EE naming services provide the Java EE application components with access to the
Java Naming and Directory Interface (JNDI) lookup service. Using the JNDI lookup
service, the components can locate user-defined objects, environment entries, enterprise
beans, JDBC DataSource objects, and messaging connections.
The security services enable you to configure Web-tier and business-tier components so
that only authenticated and authorized users can access the system resources.
The transaction architecture enables you to specify relationships among methods that make
up a single transaction so that all methods in one transaction are treated as a single unit.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 40
Java EE Server (continued)
The remote connectivity service manages the low-level communications between clients
and Java EE components. This provides location transparency to the clients. The client
accesses the components as though both of them (the client and the
Web-tier or business-tier components) were on the same JVM.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 41
Copyright 2009, Oracle. All rights reserved.
Oracle WebLogic Server 10.3
Is a Java EE server implementation
Key features:
Implements Java EE 1.5 Specification
Runs on standard JVM
Provides high performance and scalability
Is productive for developers to use
Is simple to manage and deploy
Provides clustering for high availability and failover
Oracle WebLogic Server 10.3
Oracle WebLogic Server (WLS) provides a complete Java EE server implementation. It is
written in Java and executes on the standard JVM. WLS 10.3 is compatible with Sun SDK 1.6
and BEA JRockit 1.6 JDK versions.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 42
Copyright 2009, Oracle. All rights reserved.
WebLogic Server Domain
A domain:
Is an administrative unit or boundary.
Allows for a single point of administration for a collection of
servers
MyDomain
Machine 2 Machine 1
Server 1
Server 2
Server 3
WebLogic Server Domain
A domain is simply an administrative unit. Essentially, the scope of a domain is the scope from
which an administration server can see all of its managed servers.
Servers do not have to be assigned to a machine. If a server is not assigned to a machine, it is
assumed to be on a different machine than the other servers.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 43
Copyright 2009, Oracle. All rights reserved.
WebLogic Server Domain
WebLogic Server Domains can be used to separate:
Development, test, and production applications
Administration and operational responsibilities
Organizational or business divisions
Domain1 (Development)
Domain2 (Production)
Application 1 Application 2 Application 1 Application 2
WebLogic Server Domain (continued)
A BEA WebLogic Server domain is an administrative feature. There are no WLS programming
interfaces that refer to domains. All domain-related information is in the configuration files;
only an administrator is aware of domains.
Benefits of Multiple Domains
An enterprise can have different kinds of applications, be geographically dispersed, and be
organized into different areas of responsibility. There might be many separate domains. Each
domain is a separately administered unit. Perhaps it is organized for geographical considerations
(all the machines in a given location) or organized on departmental lines within an enterprise
(accounting, manufacturing, shipping, and so on).
Eventually, an enterprise may want the different applications in those domains to be able to
interoperate. It is often impossible to expand a single domain to encompass the enterprise.
However, the size of an expanded domain in terms of the number of machines and services
could be impractical. Because a single domain must be administered as a whole, the
configuration would rapidly become huge and require more effort in administering than in
developing and implementing applications.
Therefore, to keep a domain relatively compact for administration, there must be a way to
separate applications into multiple domains and still allow applications in one domain to access
services in other domains. This capability for interdomain communication is made possible by
the WLS Domain feature.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 44
Copyright 2009, Oracle. All rights reserved.
WebLogic Server Servers
A server is a WebLogic Server instance executing within a
JVM.
A server:
Can be associated with at most
one WLS machine
Has a dedicated amount of RAM
Is multithreaded
Server 1
Server 2
WebLogic Server Servers
A WebLogic Server server is simply a JVM that is executing the weblogic.Server class.
The weblogic.Server class is the class that contains the main() method of the WebLogic
Server system. It is the primary controller for the system. Because a server executes within a
single virtual machine, it has a dedicated amount of RAM that is predetermined at system boot
time. A server can be associated with only a single machine, but a machine can be associated
with multiple servers.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 45
Copyright 2009, Oracle. All rights reserved.
Administration Server
An Administration Server is:
The central point of control for a domain
The keeper of the XML configuration repository
The central source for logging information
Administration
Server
Critical Domain
Notifications
(Logs)
Configuration
repository
(config.xml)
Runs the
Admin Console
LOGS
Administration Server
A WebLogic Server running the administration service is called an Administration Server. The
Administration Server provides the central point of control for configuring and monitoring an
entire domain. The Administration Server must be running in order to perform any management
operation on that domain. In a configuration with multiple WebLogic Servers, only one server is
the Administration Server; the other servers are called Managed Servers. Each Managed Server
obtains its configuration at startup from the Administration Server.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 46
Copyright 2009, Oracle. All rights reserved.
Managed Server
A Managed Server:
Is an instance of WebLogic Server
Loads its configuration remotely from an Administration
Server
MyDomain
Administration
Server
Managed Server
Managed Server
Managed Server
Managed Server
A Managed Server is a single server that boots on a remote, or perhaps the same, physical
machine and loads its configuration from a specified Administration Server. Managed servers
get all of their configuration information from the remote Administration Server and need only
know the domain and server they represent in a domain.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 47
Copyright 2009, Oracle. All rights reserved.
WebLogic Server Machines
A machine:
Represents the physical piece of hardware that a server
resides on
Can be a UNIX (Solaris, HP-UX, AIX, Linux) or non-UNIX
type (NT, OS-390, Mainframe)
One or more server instances can reside on a single
machine.
Machine 2 Machine 1
Server 1
Server 2
Server 3
WebLogic Server Machines
A machine is a piece of hardware that can have multiple CPUs and IP addresses. Typically, a
machine is managed by a single operating system that supports all the networking
communications with the hardware. WebLogic Server makes a distinction between UNIX
machines and non-UNIX machines.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 48
Copyright 2009, Oracle. All rights reserved.
JDeveloper and Java EE
JDeveloper provides:
Integrated development, deployment, and testing support
for Web-tier and business-tier components
A Java EE 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 WebLogic Server JDeveloper
JDeveloper and Java EE
JDeveloper is an integrated development environment (IDE) that is used to build, test, and debug
Java EE applications. In Oracle JDeveloper 11g, workspaces and projects are used to organize
the files that you need for your application. To effectively work with the files in JDeveloper, you
can use projects to work with individual files, and workspaces to manage one or more projects.
You must have a workspace before you can create projects. It is a common practice to create
workspaces around functions of applications, such as human resources management, and to
separate technologies into projects, such as having separate projects for the model, view, and
controller. By using UML Modeler, you can model business processes, build, test, and debug
Java EE components, and easily deploy the business processes to any Java EE servers.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 49
Copyright 2009, Oracle. All rights reserved.
Oracle JDeveloper 11g Environment
Wizards for
JSPs,
servlets, and
EJBs
Error
checking
for HTML
and JSPs
Code Insight
EAR, WAR
deployment
to Java EE
server
Customizable Code Editor
Oracle JDeveloper 11g Environment
JDeveloper provides you with several helpful development features. Wizards for creating
servlets, JSPs, and EJBs make it easy to start building a Web application. The Code Editor is
customizable and Code Insight makes it easy to develop code without having to remember each
package and class name. Debugging is provided in both local and remote modes, and errors in
HTML and JSPs are identified within the IDE. Additionally, JDeveloper automates the
packaging of Java EE applications into WAR or EAR files for deployment to a Java EE server.
Oracle WebLogic Server is provided within the tool to test and debug Java EE applications.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 50
Copyright 2009, Oracle. All rights reserved.
Oracle JDeveloper 11g
Visual Design Tools
Drag JSP and HTML
Elements.
Modify the
values
in Property
Inspector.
Design in visual
or code views,
see revisions.
Oracle JDeveloper 11g Visual Design Tools
Oracle JDeveloper 11g enables you to choose between editing in code or visual views for JSF
and HTML documents, or to view the revisions that have been made. You can drag JSF and
HTML elements from the Component Palette to the visual or code views, and elements can be
modified directly in the Code Editor, Visual Editor, or in the Property Inspector. The Code
Editor, Visual Editor, Property Inspector, and another visual tool, the Structure window, are all
synchronized so that a change in one propagates immediately to all other representations of the
data.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 51
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned that:
Java EE is a set of Java technologies that supports
end-to-end application development
Components are the foundation of the Java EE
architecture
Business components (EJBs) are server-side components
that contain business logic
Web components (servlets, JSPs, and JSFs) generate
dynamic content
Summary
Java EE is a complete application architecture for enterprise-class applications that provides
multitier application support. Java EE emphasizes a portable, component-based approach to the
creation, deployment, and management of complex applications.
Java EE distributes application logic into:
Business-tier components, such as EJB and Web services that define
server-side business logic
Client-tier components, such as a Web browser or an application client
Web-tier components, such as JSFs, JSPs, and Java servlets, that are used to build the
presentation logic
Enterprise Information System tier running on the database server to store the data
Java EE components are assembled into a Java EE application, verified according to the Java EE
specification, and deployed to the Java EE server. The deployed applications are run and
managed by the Java EE server.
The Java EE server, the run-time portion of Java EE, provides containers for each type of Java
EE application. These containers provide system-level services to components. You deploy
applications to a Java EE server, such as Oracle WebLogic Server.
Oracle Fusion Middleware 11g: Build Java EE Applications 2 - 52
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices cover the following topics:
Creating JDeveloper connections for the FOD database
schema
Examining some of the seeded data in the FOD schema
tables
Copyright 2009, Oracle. All rights reserved.
Designing Java EE Applications
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Identify Java EE design patterns and their purpose
Describe the Model-View-Controller (MVC) architecture
Define the purpose and role of Struts
Define the purpose and role of JavaServer Faces (JSF)
Describe data source and connection pools in WebLogic
Server
Objectives
This lesson deals with the design of Java EE applications. After working for several years with
the object-oriented (OO) programming concepts, developers found that the best applications
follow similar patterns. The Java EE architectural design pattern for the interactive enterprise
application is known as MVC. The MVC pattern is ideally suited for the kind of application that
combines distributed application logic with a complex user interface. The lesson introduces the
MVC design pattern, and describes how it can help you design Java EE applications that are
easier to reuse and maintain.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 3
Copyright 2009, Oracle. All rights reserved.
Realizing the Benefits of Java EE
To leverage the full benefits of Java EE, you must design
applications that are:
Portable: You should be able to redeploy the Java EE
applications to different servers, databases, and so on.
Scalable: Web applications should be able to handle large
numbers of users.
Maintainable: A minimum amount of coding should be
necessary for a new business rule.
Reusable: For example, a class that processes credit
cards should be reused by multiple applications.
Simple: The business need should be solved with the least
amount of complexity.
Realizing the Benefits of Java EE
Java EE helps achieve portability, which is particularly important for applications that must be
clustered. Additionally, well-designed Java EE applications are scalable when the number of
users and their actions are difficult to predict, as in Internet applications. Java EE applications
must be able to accommodate new business needs in an organization because the application
could be used within an organization for many years. Applications that enable code reuse for
minimizing duplication benefit from object-oriented design. Finally, applications that avoid
unnecessary complexity are engineered to meet the needs of the business, without becoming
overcomplicated by using the latest buzzword technology.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 4
Copyright 2009, Oracle. All rights reserved.
Java EE Issues
It is important to follow certain guidelines for the design and
development of any new technology:
Implement generally accepted design patterns and
architectures.
Focus on real business needs rather than simply adopting
new technology.
Employ the simplest technology to solve a business
problem.
Java EE Issues
Developers are often directed toward Java EE as a complete, effective solution, where scalability
and portability are handled automatically, without the need for good design patterns. Thus, many
Java EE applications are built to use the latest functionality, without solving the needs of the
enterprise.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 5
Copyright 2009, Oracle. All rights reserved.
Design Patterns
Design patterns:
Are a repeatable process of design addressing a specific
issue or problem in the development of a system
Are predictable in their function and are consistent in their
pros and cons
Are concepts that allows for a common method to quickly
and effectively communicate complex ideology to others
Allow for the accelerated education of the concept for
those new to it
Design Patterns
Design patterns are recurring solutions to software design problems, which you find again and
again in real-world application development. Patterns are about design and interaction of
objects, as well as providing a communication platform concerning elegant, reusable solutions to
commonly encountered programming challenges.
Design patterns are helpful because they:
Solve real-world problems
Capture domain expertise
Document design decisions and rationale
Reuse wisdom and experience of master practitioners
Convey expert insight to novices
Form a shared vocabulary for problem-solving discussion
Describe more than just the solution
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 6
Copyright 2009, Oracle. All rights reserved.
Java EE Design Patterns
The generally accepted design patterns include (but are not
limited to) the following:
Presentation-tier patterns:
Intercepting filter
Controller servlet (as used in MVC)
Business-tier patterns:
Service Locator
Data Transfer Object
Session Facade
Java EE Design Patterns
Design patterns describe solutions for common design issues. This slide introduces some of the
more popular design patterns.
Presentation-tier patterns
- Intercepting filter: Facilitates preprocessing and postprocessing of a request, by
applying additional services that are needed to process a request. A servlet filter is an
example of an implementation of this pattern.
- Controller servlet: Provides a centralized controller for handling a request. This is
more comprehensive than the intercepting filter approach because all requests are
maintained in the same controller.
Business-tier patterns
- Service Locator: Facilitates to transparently locate business components and
services in a uniform manner. It centralizes and reuses the implementation of lookup
mechanisms for Java EE application clients. It also encapsulates vendor
dependencies for registry implementations, and hide the dependency and complexity
from the clients.
- Data Transfer Object (DTO): Facilitates data exchange between tiers by reducing
the network load
- Session Facade: Encapsulates business-tier components and exposes a coarse-
grained service to the clients
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 7
Copyright 2009, Oracle. All rights reserved.
Implementing a Session Facade Pattern
A Session Facade pattern:
Provides clients with a single application interface
Contains centralized, complex interactions between lower-
level business components
Decouples components to yield a flexible design
Facade
Session bean
Entity
Client
Entity
Implementing a Session Facade Pattern
A Session Facade pattern is useful for applications with complex business process and
interactions. As depicted in the diagram, a Session Facade pattern is implemented as a session
Enterprise JavaBean. The benefits of implementing a facade are the following:
Provision of a single application interface for clients, whether Web or application clients
Definition of a higher-level business component that contains centralized business logic.
The business logic in a Session Facade pattern can encapsulate more complex interactions
between lower-level components. For example, a single method (business operation) in a
Session Facade pattern can manage retrieval of an order and all its items from two or more
entities involved in a relationship.
Decoupling of lower-level components from each other. This enables the design to be more
flexible, making it easier to maintain the application over its lifetime as it changes and
grows in complexity. The facade hides the location of components and the implementation
details from the clients.
Improved network performance through the elimination of multiple fine-grained method
calls between a client and individual components managed by the facade
Spanning transactions across more than one call to the entities
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 8
Copyright 2009, Oracle. All rights reserved.
Defining the MVC Architecture
Generic MVC architectural design pattern
Get state.
View Controller
User requests
Model
Set (change) state.
Notify change.
Select next view.
Defining the MVC Architecture
The graphic depicts the generic MVC design pattern recommended for interactive applications.
The benefit of an MVC architecture is separation of presentation, control, data persistence, and
behavior. Parts of an MVC design pattern are:
A model, which encapsulates application state or data exposing functionality and notifies
the view when the state changes
A view, which presents the user interface rendering the data and accepting user input. The
view directs requests to the controller.
A controller, which defines application behavior and flow between one view and the next.
The controller maps user requests to model functionality and data operations.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 9
Copyright 2009, Oracle. All rights reserved.
The Model
The model represents the enterprise data and business
rules that handle access and updates.
You can simplify the model by using two mechanisms
called facade class and command pattern.
A facade encapsulates, hides the complexity of, and
coordinates the operations between cooperating classes.
A command pattern encapsulates each application function
in a separate class.
The model is often implemented using Java beans and
EJBs.
The Model
The model of an application contains the business data and the operations that govern access and
modification of the data. Thus, it is often implemented using Java beans and EJBs. The model
notifies a view when it changes and provides the ability for the view to query the model about its
state. The controller accesses the application functionality that is encapsulated in the model. A
session bean is often used to create the facade. For example, a Session Facade bean provides the
required interfaces (while hiding the complexities of the interfacing classes from the client), and
manages the relationships between the objects. A command pattern bean provides the business
logic of the interfaces that a Session Facade bean implements.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 10
Copyright 2009, Oracle. All rights reserved.
The View
The view focuses on presentation and is responsible for
maintaining consistency between data presentation and
model changes. It enables:
Presentation to be changed without altering
programming logic
Development by Web page authors having only visual
design skills
The view is commonly implemented using JSPs.
The View
The view of an application renders the contents of a model and specifies how data should be
displayed. The view forwards the user input to a controller. For example, a view component
might display rows from a database. The actual querying of the data should be left to the model,
but formatting the data for the client is left to the view. For this reason, view components are
usually JSPs. An application may be designed to accept query parameters from user input. In this
example, the parameters would be passed to the model from the controller (discussed in the
following slide), and the resultant data would be displayed in the view.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 11
Copyright 2009, Oracle. All rights reserved.
The Controller
The controller provides interaction with the client, serving
as a glue between the model and the view.
The controller:
Interprets user requests and controls business objects to
fulfill these requests
Removes navigation coding from the view
Can be implemented in the client, Web, or EJB tier, or in a
combination of these tiers
The controller is usually implemented as a servlet.
Struts and JSF are two widely used implementations.
The Controller
A controller defines application behavior. It dispatches user requests and selects views for
presentation. The controller determines what happens when the user interacts with the
component. For example, what occurs when the user clicks a button. The controller accepts the
users query parameters and passes them to the model. A servlet is best suited for this MVC
component because it contains coding logic for accepting user input and passing it to a model,
with little or no presentation coding, such as HTML. In this way, the controller makes the
application more maintainable as a whole. The database column names or the preferred
formatting style can change, without affecting the navigation and functionality of the
application. A developer simply changes either the model or the view, respectively.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 12
Copyright 2009, Oracle. All rights reserved.
Designing a Java EE Application
Web-tier design: Use an MVC design pattern.
Business Logic tier design: Use a Session Facade pattern.
Client
Servlet
(Controller)
JavaBean (Model)
Web tier
JSP (View)
Session Facade
bean
Entities
Designing a Java EE Application
A Java EE application is a server-side implementation that contains standard components such
as servlets, JSPs, and EJBs.
Web-tier design: Web-tier designs typically use an MVC design pattern, such as JavaServer
Faces and Oracle ADF Faces. Using an MVC design pattern enables you to separate the
presentation logic from the business or data logic. The controller facilitates application flow
control from one page to the next. The basic components used in an MVC design model are:
A JSP or servlet for the view
A servlet for the controller
JavaBeans for the model. The JavaBeans may execute the business logic or may use EJB
components to perform the business logic operations.
Business Logic tier design: Depending on the complexity of the business logic, entities may or
may not be exposed to the Web-tier or clients. Complex applications commonly use a session
bean as a facade, for the following reasons:
For control of security at the business-method level
To mediate access to entity beans and persistence layers
To better manage transaction boundaries
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 13
Copyright 2009, Oracle. All rights reserved.
Quiz
If you implement the MVC design pattern, the controller:
1. Adds navigation and implements the view
2. Can be implemented in the client, Web, or EJB tier, or in a
combination of these tiers
3. Handles the input event from the user interface
4. Processes and responds to events, typically user actions,
and may invoke changes on the model
Answers: 2, 3, 4
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 14
Copyright 2009, Oracle. All rights reserved.
Struts: Overview
Struts is a framework for implementing the MVC design
pattern in Java EE applications.
Struts:
Is an open-source project from the Apache Software
Foundation
Is implemented by an XML-driven controller servlet
Uses standard Java EE Web technologiesservlets, JSPs,
and tag libraries
Struts: Overview
Struts is an open-source project from the Apache Software Foundation. It is used for developing
Java EE Web applications using the MVC design pattern. Struts uses and extends the Java
Servlet API to adopt an MVC architecture.
Struts provides its own controller component that integrates with other data access technologies
(such as Java beans and EJBs) to provide the model. It also integrates with JavaServer Pages,
JavaServer Faces and other presentation systems to provide the view.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 15
Copyright 2009, Oracle. All rights reserved.
Struts Components
Action Servlet: Receives user inputs and state changes
and issues view selections
Action: Interacts with the model to execute a state change
or query
Form Beans: Passes data (from forms) into JavaBeans for
reuse and validation
Action Forward: Stores the path to a page where the user
is sent
Action Mapping: Tells the servlet how each request URI is
mapped to an Action
Struts-config.xml: Contains the definitions of the
Struts components used in an application
Struts Components
Action Servlet: This component is focused on receiving requests from the client (typically, a
user running a Web browser), deciding what business logic function is to be performed, and then
delegating responsibility for producing the next phase of the user interface to an appropriate
view component.
Action: This serves as an interface between client-side user action and the business logic.
Almost everything that happens in a Struts-based application happens in an Action.
Form Beans (Action Forms): Form Beans are used to pass data to and receive data from the
model and the view.
Action Forward: This component defines where the requesting page should be forwarded to, if
required.
Action Mapping: Tells the servlet how each request Uniform Resource Identifier (URI) is
mapped to an Action. It includes the class of the Action, the name of the Form Beans that the
Action uses, and the path to pass control to when this mapping is invoked.
Struts-config.xml: This file contains the definitions of the Struts components used in an
application.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 16
Copyright 2009, Oracle. All rights reserved.
Struts Architecture
View
Model
Action
Servlet
Controller
JSP
struts-config.xml
web.xml
Web
Client
Database
Java
Script
JSP
Tags
Web container
HTTP
Request
HTTP
Response
2
4
3
Action
Java Beans/
EJBs
1
Struts Architecture
The graphic depicts a high-level view of the Struts architecture.
1. A Web client sends an HTTP request to the server.
2. The Struts Action Servlet receives the HTTP request. It inspects the URL and based on the
Struts configuration file (struts-config.xml), delegates the handling of the request
to an Action class.
3. The Action class communicates with the model layer and invokes the business logic.
4. Based on the information from the model layer, the Action class advises the Action
Servlet to show the next JSP page to the client.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 17
Copyright 2009, Oracle. All rights reserved.
Struts Page Flow Design
Use the Struts Page Flow diagram to create the top-level page
flow design of a Struts application:
Struts Page Flow Design
JDeveloper includes a Visual Editor for the struts-config.xml file. Using the Visual
Editor, you can create pages, add page forwards, add actions, and so on. In this diagram, there
are three pages and one action. The login.jsp page has a link to the login action. The
login action is a class that validates the login information and returns either success or
badlogin. The controller then forwards the request to either the login page or the
welcome page. The welcome page has a link to the emps page.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 18
Struts Page Flow Design (continued)
The following is the struts-config.xml file for this application:
<struts-config>
<form-beans>
<form-bean name="DataForm"
type="oracle.adf.controller.v2.struts.
forms.BindingContainerActionForm"/>
</form-beans>
<action-mappings>
<action path="/emps"
className="oracle.adf.controller.v2.struts.
actions.DataActionMapping"
type="oracle.adf.controller.v2.struts.
actions.DataForwardAction"
name="DataForm" parameter="/emps.jsp"/>
<action path="/login" type="sr.view.login">
<forward name="badlogin" path="/login.jsp"/>
<forward name="success" path="/welcome.jsp"/>
</action>
</action-mappings>
<message-resources parameter="sr.view.ApplicationResources"/>
</struts-config>
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 19
Copyright 2009, Oracle. All rights reserved.
JSF and Struts
JSF provides the same benefits as the Struts architecture,
including:
Controller servlet (MVC implementation)
Declarative and visual design in JDeveloper
XML configuration file (faces-config.xml)
JSF and Struts
JSF uses the same basic framework for controlling applications (MVC). However, JSF pages and
the controller are designed to work together.
With Struts, there is generally one action per page, whereas JSF can have multiple events within
a single page.
JSF uses built-in managed beans that facilitate single-point coding for any component on the
page. These managed beans provide a way to store page-specific or session-specific information.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 20
Copyright 2009, Oracle. All rights reserved.
Business Delegate
Controller
Implementing the User Interface with JSF and
Core Java EE Patterns
View: JSF Page
Model: Managed
(Backing) Bean
faces-config.xml
FacesServlet
EJB
Uses
Request
Response
1
2
3
Implementing the User Interface with JSF and Core Java EE Patterns
The graphic represents a typical Java enterprise application architecture implemented with a JSF
user interface. The application components shown include:
1. The view (JSF pages) making up the presentation layer that interacts with its model. UI
component values are stored in the backing bean or determined by its functionality.
2. The model (JSF backing beans, also called managed beans) that decouples the user
interface from the business logic. The model interacts with a Session Facade Enterprise
JavaBean that implements the business logic layer.
3. The controller (faces-config.xml and FacesServlet) manages the application flow
logic between JSF pages application flow and their life cycle based on user interaction and
application action events.
Note: The first three are parts of the MVC Java EE design pattern framework consisting of the
view (JSF Page), model (backing JavaBean), and controller (faces-config.xml and
FacesServlet).
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 21
Copyright 2009, Oracle. All rights reserved.
Selecting a Persistence Strategy
Persistence techniques for Java EE applications:
Session bean
ORM
1
2
3
Entity
JDBC
JPA Entity
JPA 4
Selecting a Persistence Strategy
There are many persistence strategies that a developer may use to manage database data and
transactional logic. The diagram depicts the EJB types with possible persistence choices:
1. A session bean directly executes JDBC logic to perform the database operations. JDBC is
used wherever required, without dependency on bean life-cycle methods.
2. A session bean can use Java Database Connectivity (JDBC), a Plain Old Java Object
(POJO) with an object-relational mapping (ORM) mechanism, or a direct mapping to the
database using the ORM technology.
3. A session bean executes a Java Persistence API (JPA) entity to map Java objects to
relational database tables.
4. An entity (or JPA entity) is a Java object that is persisted into the database by
implementing JPA.
You can use Oracle TopLink or Hibernate (among others) as ORM tools.
Using JPA, you can designate any POJO class as a JPA entitya Java object whose nontransient
fields should be persisted to a relational database using the services of an entity manager
obtained from a JPA persistence provider (either within a Java EE EJB container or outside of an
EJB container in a Java SE application).
Note: A servlet or JSP page may also perform persistence logic by using either JDBC directly or
POJOs and O-R mapping techniques such as Oracle TopLink or Hibernate. A servlet can also
directly invoke JPA entities.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 22
Copyright 2009, Oracle. All rights reserved.
Quiz
Struts is a framework for implementing the Session Facade
design pattern in Java EE applications:
1. True
2. False
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 23
Copyright 2009, Oracle. All rights reserved.
What Is a Data Source?
A data source:
Is a Java EE concept that allows for abstracting a JDBC
connection
Provides connections from connection pools
Hides the physical location of the data
jdbc/OracleDS
Order Entry data
Product database
Application
What Is a Data Source?
A data source is a Java EE concept that allows for abstracting a JDBC connection. With a data
source, a developer or an administrator can specify an object that represents a database.
In the Java EE environment, a data source name is associated with a set of properties that specify
the details of how to communicate with a physical resource managing the data. In the graphic,
the logical name jdbc/OracleDS is initially associated with an Oracle Database 11g
database. If the physical data is relocated to another database (for example, the product
database), the data source properties can be altered to identify the new location. In this way, the
application does not need to be altered; it still references the data by using the same logical data
source name.
In all cases, the data source properties identify the resources needed to facilitate communication
with the target data source, such as JDBC drivers (drivers that are needed to enable access to the
data).
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 24
Copyright 2009, Oracle. All rights reserved.
What Is a Connection Pool?
A connection pool is a group of ready-to-use database
connections associated with a data source.
Connection pools:
Define database connections
Provide pools of readily available connections
Can be dynamically resized to accommodate increasing
load
What Is a Connection Pool?
WebLogic Server opens JDBC connections to the database during the WebLogic startup process
and adds the connections to the pool. This is faster than creating a new connection on demand.
The size of the pool is dynamic and can be fine-tuned. Connection pools could be started with
the server if it is declared on the server system level or at the time of the application startup if it
is described within an application archive.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 25
Copyright 2009, Oracle. All rights reserved.
Benefits of Data Sources Plus
Connection Pools
Following are some advantages of this approach:
Time and overhead are saved by using an existing
database connection.
Connection information is managed in one location in the
administration console.
The number of connections to a database can be
controlled.
The DBMS can be changed without the application
developer having to modify underlying code.
A connection pool allows an application to borrow a DBMS
connection.
Benefits of Data Sources Plus Connection Pools
Making a DBMS connection is very slow. When WebLogic Server starts, connections from the
connection pools are opened and are available to all clients. When a client closes a connection
from a connection pool, the connection is returned to the pool and becomes available for other
clients; the connection itself is not closed. There is little cost to opening and closing pool
connections. The alternative is for application code to make its own JDBC connections as
needed. A DBMS runs faster with dedicated connections than if it has to handle incoming
connection attempts at run time.
Connection information, such as the JDBC driver class name, the database location (URL), and
the username and password, can be managed in one location by using the WebLogic Console.
Application developers can obtain a connection without having to worry about these details.
Limiting the number of DBMS connections is important if you have a licensing limitation for
DBMS connections or a resource concern.
Clients use a connection pool by borrowing a connection, using it, and then return it to the
pool by closing it. The connection pool can grow or shrink dynamically to accommodate
demand. The administration console is used to set a connection pools initial capacity, maximum
capacity, and its capacity increment.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 26
Copyright 2009, Oracle. All rights reserved.
JDBC Data Source Architecture
WebLogic Server
JNDI Tree
JDBC Conn. Pool
: Connection
: Connection
: Connection
JDBC Conn. Pool
DataSource
External Clients
DataSource
Internal Clients
(Servlets, JSP)
: Connection

JDBC Data Source Architecture


You create the connection pools and deploy them to servers and clusters. Then you create the
data sources, which are bound to the JNDI tree, and deploy the data sources to the same servers
and clusters. When you create a data source object, you specify a connection pool as one of the
data source attributes. This associates that data source with one specific connection pool.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 27
Copyright 2009, Oracle. All rights reserved.
Data Source Architecture: Connecting
A client retrieves a data source through a JNDI lookup and
uses it to obtain a database connection.
Connection
Data Source
WebLogic Server
JNDI Tree
Client
Connection Pool
Database
Lookup Data Source
Return Data Source
getConnection()
Return Connection
Database Access
1
2
3
4
5
JDBC Driver
Data Source Architecture: Connecting
The slide shows an example of how a data source is used by the client. The sequence of events
are as follows:
A client retrieves a data source object by performing a lookup in the WebLogic Server
JNDI tree.
A data source object contains a reference to a connection pool.
After a data source object is obtained, the client can then obtain a database connection.
The connection then interacts with the database.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 28
Copyright 2009, Oracle. All rights reserved.
Creating a Data Source
in WebLogic Server
1 2
3
3
4
5
Creating a Data Source in WebLogic Server
To create a data source in WebLogic Server by using the WebLogic Server console, perform the
following steps:
1. In the Domain Structure tree, expand Services > JDBC, and then select Data Sources.
2. On the Summary of Data Sources page, click New.
3. On the JDBC Data Source Properties page, enter or select the following information:
i) Name: Enter a name for this JDBC data source. This name is used in the
configuration file and throughout the administration console whenever referring to
this data source.
ii) JNDI Name: Enter the JNDI path to where this JDBC data source is bound.
Applications look up the data source on the JNDI tree by this name when reserving a
connection.
iii) Database Type: Select the DBMS that you want to connect to. If your DBMS is not
listed, select Other.
iv) Database Driver: Select the JDBC driver you want to use to connect to the database.
The list includes common JDBC drivers for the selected DBMS. Click Next to
continue.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 29
Creating a Data Source in WebLogic Server (continued)
4. On the Connection Properties page, enter values for the following properties:
i) Database Name: Enter the name of the database that you want to connect to. Exact
database name requirements vary by JDBC driver and by DBMS.
ii) Host Name: Enter the domain name server (DNS) name or IP address of the server
that hosts the database.
iii) Port: Enter the port on which the database server listens for connections requests.
iv) Database User Name: Enter the database user account name that you want to use for
each connection.
v) Password/Confirm Password: Enter the password for the database user account.
Click Next to continue.
5. On the Test Database Connection page, review the connection parameters and click Test
Configuration. WebLogic attempts to create a connection from the Administration Server
to the database. Results from the connection test are displayed at the top of the page. If the
test is unsuccessful, you should correct any configuration errors and retry the test. If the
JDBC driver you selected is not installed in the Administration Server, click Next to skip
this step. Click Next to continue.
6. On the Select Targets page, select the servers or clusters on which you want to deploy the
data source.
7. Click Finish to save the JDBC data source configuration and deploy the data source to the
targets that you selected.
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 30
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Identify Java EE design patterns and their purpose
Describe the Model-View-Controller (MVC) architecture
Define the purpose and role of Struts
Define the purpose and role of JavaServer Faces (JSF)
Describe data source and connection pools in WebLogic
Server
Oracle Fusion Middleware 11g: Build Java EE Applications 3 - 31
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers analyzing the MVC design pattern of Java
EE application development:
Exploring the business objects in the model
Exploring the view components of the application
Copyright 2009, Oracle. All rights reserved.
Developing a Web Application Using Servlets
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Define the role of servlets in a Java EE application
Describe the servlet life cycle
Describe the request and response architecture
Implement HTTP servlet methods
List Java EE servlet mapping techniques
Handle errors in a servlet
Create and run a servlet in JDeveloper
Objectives
Servlets are the foundation of all other Web technologies. They provide the core API used to run
JavaServer Pages (JSP). A servlet is a platform-independent, server-side Java component used to
extend the capabilities of a Web server. Using servlets, you can dynamically customize content,
function, and the look-and-feel of your Web pages. This lesson examines the servlet technology
architecture, and shows you how to create a servlet in JDeveloper. You also see how to deploy a
servlet in an application server.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 3
Copyright 2009, Oracle. All rights reserved.
Dynamic HTML
Client Web browser
Servlet
Generates
Servlets: Overview
Requests
Responds
Business object
(EJB/Web service)
Connects to
Servlets: Overview
The basic concepts of servlets are straightforward. A Web browser invokes a URL, which calls
the servlet. The servlet then generates dynamic HTML, Extensible Markup Language (XML), or
other content. The dynamic text may have been generated by connecting to the database. The
following questions arise:
How can multiple clients be satisfied efficiently?
How can the programmers task be simplified, with the program remaining powerful
enough to handle all situations?
This lesson discusses the answers to these questions.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 4
Copyright 2009, Oracle. All rights reserved.
Client
Server
Servlet container
Java application,
Servlet, JSP,
or HTML
About Java Servlets
A servlet is a Java class that implements the servlet
interface.
A servlet runs in the context of a special process called a
servlet container.
Servlets can be invoked simultaneously by multiple clients.
Request
Response
About Java Servlets
A servlet is a Java class that implements the servlet interface. These classes are found in the
javax.servlet package. When you use the Servlet API, it takes care of some of the
common tasks that are involved in responding to a request from a client. For instance, the API
supports preinstantiating objects in a Java Virtual Machine (JVM), if multiple clients must
simultaneously access a particular functionality that you provide as a Java class. This feature is
referred to as the servlet life cycle.
Just as applets run in the context of a Web browser, a servlet runs in the context of a servlet
container. The Web browser and the servlet container contain a JVM that is usually functional
all the time. Unlike an applet, a servlet does not use any user interface features of the Java
language, such as the classes in the java.swing package.
As shown in the slide, a multitude of clients can invoke a servlet and can use different protocols.
For example, it is possible to write a servlet that implements the FTP server protocol.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 5
Copyright 2009, Oracle. All rights reserved.
Server
Clients
Request 1
Request 2
Request 3
Principal Features of Servlets
Concurrent requests are possible and common.
Servlet methods are run in threads.
Servlet instances are shared by multiple client requests.
Principal Features of Servlets
Multiple requests for the same servlet are run in multiple threads. This means that you should
develop the servlet to be thread safe.
Similarly, when there are no more requests for a servlet, the instance is not extinguished.
Instead, in anticipation of future requests, the memory and other resources are reused when
necessary.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 6
Copyright 2009, Oracle. All rights reserved.
Load
Life Cycle of Servlets
All actions are carried out inside the server.
After the initial setup, the response time is less.
Initialize
init()
Destroy
destroy()
Execute
service()
1 2 3
4
Life Cycle of Servlets
The life cycle of a servlet has the following characteristics:
Many servlet engines execute within a single JVM. Additionally, with WebLogic Server,
you can use multiple JVMs.
Servlets persist between requests as object instances. If an object instance makes a
connection to a database, there is no need to make another connection for the second
request. Threads also persist as in any Java program, unless they die in the natural thread
life cycle.
You can override the init()method, which is invoked by the servlet engine before the
servicing of client requests, and the destroy()method, which is invoked after the
engine removes the servlet.
A servlet can also be explicitly written in a single-threaded model. In this case, if two
requests are received at the same time, the servlet engine uses another instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 7
Copyright 2009, Oracle. All rights reserved.
Request
Response
HTTP Servlets
HTTP servlets extend the HttpServlet class, which
implements the Servlet interface.
A client makes an HTTP request, which includes a method
type that:
Can be either a GET or POST method type
Determines what type of action the servlet performs
The servlet processes the request and sends back a status
code and a response.
HTTP protocol Client Servlet
HTTP Servlets
HTTP servlets extend the javax.servlet.http.HttpServlet class, which extends the
GenericServlet class. The GenericServlet class implements the Servlet interface.
These servlets provide more features than just providing fast responses to clients. For instance,
the GET parameters that are passed through a Web browser to a Web server are available to the
user of the servlet API. Similarly, data submitted by means of a form is sent to the servlet by
using the doPost()method.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 8
Copyright 2009, Oracle. All rights reserved.
Inside an HTTP Servlet
The servlet overrides the doGet() or the doPost()
method of the HttpServlet class.
The servlet engine calls the service() method, which in
turn calls one of the appropriate doXxx() methods.
These methods take two arguments as input:
HttpServletRequest
HttpServletResponse
Browser
HttpServlet class
service()
doGet()
Request
Response
Inside an HTTP Servlet
When an HTTP servlet is invoked, the servlet engine calls the service()method in your
servlet. This is possible because you have implemented the Servlet interface. If the Web
browser has invoked the GET method in the HTTP protocol, the service()method invokes
the doGet()method in your object. Therefore, it makes sense to override this method, which
has two parameters as input. Similarly, if the browser invokes the POST method in the HTTP
protocol (for example, when the user submits an HTML form), the service()method invokes
the doPost()method. Sometimes, the functionality that you want is the same; you often see
servlets in which doPost()calls doGet(). Many examples mention only doGet(), even
though the concept is equally applicable for the doPost()method.
The servlet engine provides the Web browser input to your doGet()method and, therefore, you
do not have to worry about the difference between the two HTTP methods. This is another
advantage of using the servlet API.
Note that other methods are available in servlets, such as doPut()and doDelete(), for FTP
operations.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 9
Copyright 2009, Oracle. All rights reserved.
doGet() Method
The most common HTTP request method type made to a
Web server is GET.
The service() method in your servlet invokes the
doGet() method. The service() method is invoked on
your behalf by the Web server and the servlet engine.
The doGet()method receives two parameters as input:
HttpServletRequest
HttpServletResponse
Pass parameters by appending them to the URL:
http://www.oracle.com/servlet?param1=value1
doGet() Method
The doGet() method, which receives two parameters as input, is usually the first method that
you must modify from the JDeveloper-generated stubs. The request parameters are passed to the
doGet() method by appending them to the URL, for instance
http://www.oracle.com/servlet?param1=value1. Multiple parameters can be accessed by using
the following:
http://www.oracle.com/servlet?param1=value1&param2=value2
Additionally, a helper class, java.net.URLEncoder, exists for encoding the parameters
that are passed in the URL. The encode(String s, String enc) method of this class
converts a string (s) using the encoding character (enc), and returns the converted string.
This is helpful for passing parameters that include special characters.
GET requests are generated by a browser in the following instances:
When a user enters a URL in the address line
When a user follows an href link from another page
When a user submits an HTML form that does not specify a method
When the method is specified as GET: <FORM METHOD="GET">
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 10
Copyright 2009, Oracle. All rights reserved.
doPost() Method
The doPost() method can be invoked on a servlet from
an HTML form by using:
<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">
doPost() Method
The doPost() method is used in conjunction with an HTML form. When the user clicks
Submit, specified parameters are passed to the servlet that is specified in the action tag. Like the
doGet() method, doPost() receives two parameters as input: HttpServletRequest
and HttpServletResponse. Parameter namevalue pairs are passed to the Web server in
an additional HTTP request header, and not by appending them to the URL. Therefore, the
advantages of using POST include the following:
Parameters (like passwords) are not visible in the browsers URL field.
You cannot bookmark a URL containing the parameter values.
Web servers usually limit the amount of characters that can be passed in the URL (24
kilobytes), but there is no theoretical limit to the size of POST parameters.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 11
Copyright 2009, Oracle. All rights reserved.
HttpServletRequest Object
The HttpServletRequest object encapsulates the
following information about the client:
Servlet parameter names and values
The remote host name that made the request
The server name that received the request
Input stream data
You invoke one of several methods to access the
information:
getParameter(String name)
getRemoteHost()
getServerName()
HttpServletRequest Object
The doGet() and doPost() methods take the HttpServletRequest object as a
parameter. The following table describes several methods in the HttpServletRequest
object and their purposes, based on the example URL:
http://bighost:7101/finance/servlet/Ledger/June?region=east
/finance/servlet/Ledger.June getRequestURI()
/finance getContextPath()
/servlet/Ledger.June getServletPath()
/finance/servlet/Ledger/June.class getPathInfo()
7101 getServerPort()
bighost getServerName()
Return values Request methods
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 12
Copyright 2009, Oracle. All rights reserved.
HttpServletResponse Object
The HttpServletResponse object encapsulates
information that the servlet has generated:
The content length of the reply
The Multipurpose Internet Mail Extension (MIME) type of the
reply
The output stream
You invoke one of several methods to produce the
information:
setContentLength(int length)
setContentType(String type)
sendRedirect()
HttpServletResponse Object
The second parameter for the doGet() and doPost() methods is the
HttpServletResponse object. The first bullet in the slide describes that an HTTP response
consists of a status line (whether or not the call to the servlet was successful), one or more
headers (the content type and optional content length), and the actual output, in that order. The
following table describes several methods that are available in the HttpServletResponse
object and their purposes:
Sets the Location header and sets the status code to 302 sendRedirect()
An optional method that sets the Content-Length header;
useful for persistent HTTP connections
setContentLength()
Sets the Content-Type header for the document. This must
be used for servlets that return the document content. Common
settings include text/html, application/pdf, and
image/gif.
setContentType()
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 13
Copyright 2009, Oracle. All rights reserved.
HttpSession
The unique identity for the client is an HttpSession
object.
The object is created by using the getSession() method
of the HttpRequest object.
Any servlet that responds to a client request can create
this object.
An object can be potentially shared across several
servlets. (Every servlet within an application can identify
with this client.)
HttpSession session = req.getSession(true);
HttpSession
HttpSession is an interface. The object is obtained by using the getSession() method in
the HttpServletRequest object. This is done by extracting a user ID from a cookie or
attached URL data, and then by using that ID as a key into a table of previously created session
objects. However, all this is done automatically for you, and all you need to do is create a new
session (if there is no existing session) by using the code that is listed in the slide. If you pass
false to the getSession() method, it returns null, if there is no existing session.
The servlet specification states that HttpSession objects can be shared by different servlets
in a servlet engine. Therefore, HttpSession objects must be synchronized by the
implementation. For example:
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getAttribute("shoppingCart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart); }
...
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 14
Copyright 2009, Oracle. All rights reserved.
Session Objects
With session objects, you can:
Put items into the object (values persist across multiple
invocations from the same client)
Access items from the object
Obtain the session identity
Find out when the session was last accessed
Items put in a session object can:
Implement the Serializable interface
Be relocated to a different server
Persist across servlet crashes
Session Objects
The table below describes the methods in the HttpSession class and their meanings:
A Boolean method that returns false, if
the session existed previously for the
client, and true, otherwise
isNew()
Retrieves the previously stored value from
the session object
getAttribute(String name)
Places an object with the name alias in the
HttpSession object (You must make
sure that the name is unique across all
possible servlets in the engine.)
setAttribute(String name,
Object value)
A string denoting the unique identity of a
client
getId()
A long object denoting when the session
was last accessed by the client
getLastAccessedTime()
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 15
Copyright 2009, Oracle. All rights reserved.
Methods for Invoking Servlets
Invoke servlets from a client by:
Entering the servlet URL in a browser
Embedding the servlet URL in an HTML, or a JSP page, or
another servlet (an href link)
Submitting a form to the servlet (using the action tag)
Using URL classes in client Java applications
Invoke servlets inside the Java EE container by defining a
chain of servlets or JSPs.
Methods for Invoking Servlets
You can use the following methods to invoke a servlet:
You can directly enter the URL in a browser.
Any HTML page can contain a servlet URL by using either the <a href=> or the
<FORM action=> tag.
JSPs provide yet another way of invoking a servlet. The JSP can have Java code directly
embedded in it.
A servlet can be invoked by another servlet through chaining. A servlet chain is a sequence
of servlets in which the output of a servlet is sent to the next servlet in the chain. The last
servlet produces the actual output that is seen by the Web browser. A servlet chain has the
same advantages that the pipe command has in an operating system. Any number of
servlets can be chained together. Additionally, servlet filters can intercept the request and
pass the output to the next filter or servlet in the filter chain.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 16
Copyright 2009, Oracle. All rights reserved.
Quiz
HttpSession is an interface that provides a way to
identify a user across more than one page request.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 17
Copyright 2009, 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>
Handling Input: The Form
You can use an HTML form and the doPost() method to
modify the HelloWorld servlet.
Handling Input: The Form
In this slide, an HTML form is used, which passes the input to the Web server. Your task is to
process this input. The HTML output is shown below.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 18
Copyright 2009, 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>");
}}
Handling Input: The Servlet
Handling Input: The Servlet
The preceding slide shows an HTML form that passes some input. This slide shows how you can
process the input. Note that the content type, res.setContentType("text/html"), is
set before submitting the document. In the example in the slide, getParameter() is used to
retrieve the case-sensitive firstName parameter as a string from the HTML form. If no value
is found, an empty string is returned, and null is returned, if there is no parameter by that name.
getParameter() is used in the same way for GET and POST requests. Additionally,
getParameterValues() can be used to return an array of strings, if the parameter can have
more than one value.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 19
Copyright 2009, Oracle. All rights reserved.
Initialization and Destruction
Servlets also define the init() and destroy() methods in
addition to the service() method.
init():
Can be used to retrieve initialization parameters
Takes a ServletConfig object as a parameter
Is invoked when the servlet instance is created
Is useful for obtaining database connections from a
connection pool
destroy():
Takes no arguments
Is invoked when the servlet is about to be unloaded
Is useful for releasing resources
Initialization and Destruction
The ServletConfig object of init() can be used to find the initialization parameters that
are associated with the servlet. It uses the getInitParameter() method to retrieve the
name of the initialization parameter. Note that you must call super.init() in the init()
method if you use the ServletConfig object, because the ServletConfig object can be
used elsewhere in the servlet. For instance:
public void init(ServletConfig config) throws
ServletException
{ super.init(config);
... // your initialization here }
In a Java EE Web application, an initialization parameter is defined in the web.xml file as
follows:
<init-param>
<param-name>message</param-name>
<param-value>Hello From Init Parameter</param-value>
</init-param>
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 20
Copyright 2009, Oracle. All rights reserved.
Error Handling
ServletException:
Is generated to indicate a generic servlet problem
Is subclassed by UnavailableException to indicate
that a servlet is unavailable, either temporarily or
permanently
Is handled by the servlet engine in
implementation-dependent ways
IOException is generated if there is an input or output
error when processing the request.
Error Handling
The doXxx() method throws both ServletException and IOException. The init()
method throws ServletException. These exceptions contain the same constructors as the
Exception class. Generally, an IOException is returned only when there is some kind of
stream operation on the servlet (in the case of working with applets, for example).
ServletException is returned if the servlet cannot be reached. For additional exceptions,
an error page can be set for error codes in the <web-app> element of web.xml as follows:
<error-page>
<exception-type> java.lang.NumberFormatException </exception-
type>
<location>MyExceptionServlet</location>
</error-page>
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 21
Copyright 2009, Oracle. All rights reserved.
Debugging a Servlet
Servlets can be debugged in the following ways:
By setting breakpoints and using the debugger in
JDeveloper
By viewing the source of the generated HTML
Debugging a Servlet
Servlets can be debugged in JDeveloper by setting breakpoints in the code (by clicking the line
number where you want to set the breakpoint), and then by right-clicking the servlet name in the
navigator and selecting Debug in the menu. Additionally, selecting View > Source in the
browser displays the generated HTML of the servlet.
Note that you can also debug servlets or other Java EE components that are running in a
different JVM. The detailed steps to do this can be found in the online Help of JDeveloper,
under the topic Remote Debugging. There is a wizard to create a project that is configured for
remote debugging.
Typically, you perform these tasks:
1. Specify the source directory and any necessary libraries.
2. Copy the jdev-rt run-time libraries to the remote server.
3. Bind the Web sites in the J2EE server configuration files.
4. Run the servlet (with breakpoints set) in the remote server.
5. Start the debugging process in JDeveloper as in the slide above.
6. Begin debugging the servlet.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 22
Copyright 2009, Oracle. All rights reserved.
JDeveloper Environment
The Servlet Wizard in JDeveloper makes it easy for you to write
servlets. The wizard:
Provides the doGet() and doPost() method skeletons
Provides an environment for running the servlet within the
integrated development environment (IDE)
Dynamically creates the web.xml file for running the
servlet from the IDE
JDeveloper Environment
The Servlet Wizard in JDeveloper gives you an easy way to start your servlet development. It
also creates an environment for running and debugging your servlet.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 23
Copyright 2009, Oracle. All rights reserved.
Servlet Mapping
Mapping a servlet refers to how a client can access a
servlet.
You can map a servlet by using the mapped URL:
http://host:port/<context-root>/<mappedservletname>
<context-root> is the mapping for the Web module.
Servlet Mapping
Servlet mapping refers to the process by which a servlet is invoked. This is application
serverdependent. In general, you can map a servlet by using the mapped URL:
http://host:port/<context-root>/<mappedservletname>
where host is the host name or IP address of the server machine, and port is the port number of
the server. (For example, Apaches default port is 80 and WebLogic Servers default port is
7001.) This is not enabled by default.
<context-root> is the mapping for the Java EE Web module.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 24
Copyright 2009, Oracle. All rights reserved.
Servlet Mapping in JDeveloper
JDeveloper provides the standard Java EE model for mapping
servlets by using the web.xml file:
<?xml version = '1.0' encoding = 'UTF-8'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>oracle.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/loginservlet</url-pattern>
</servlet-mapping>

</web-app>
Servlet Mapping in JDeveloper
The web.xml file is primarily used to map a servlet to a virtual directory and name it. This
standard Java EE file is created automatically when a servlet is created in JDeveloper, and the
appropriate XML tags are included in the file. To modify the file, right-click the web.xml file
and select Properties from the context menu. In the above example, the servlet named
LoginServlet is mapped to a virtual directory of /loginservlet. Therefore, this servlet
can be accessed with the following URL:
http://localhost:<port>/<context-root>/loginservlet
The virtual directory of /loginservlet comes from the Java EE Web server configuration.
It is included automatically when running a servlet that is mapped in the web.xml file.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 25
Copyright 2009, Oracle. All rights reserved.
Invoking a Servlet
Invoking a Servlet
This slide shows an example of how a servlet can be invoked in JDeveloper. When the servlet is
run, the Java EE server installed with JDeveloper is started, the mapping is retrieved from the
web.xml file, and the resulting servlet is displayed from the default browser.
Note: The context root of this application is servlets-context-root.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 26
Copyright 2009, Oracle. All rights reserved.
Specifying Java EE Web Module Settings
Specifying Java EE Web Module Settings
The slide shows the Java EE Web module settings for a project in JDeveloper. This is accessed
by right-clicking the project and selecting Project Properties. The slide shows the default
settings for the lesson04Demo project, which can be changed as necessary.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 27
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe the servlet life cycle
Develop and run a servlet in JDeveloper
Map a servlet in a Java EE server
Collect information from a client
Respond to the client
Handle errors in a servlet
Summary
In this lesson, you have examined the role of servlets in the client tier of an application. You
have also seen how a servlet manages the request and response from a client, each request
running independent threads. You have explored the servlet life cycle and how a servlet is
initialized, executed, and destroyed. An HTTP servlet provides doPost() and doGet()
methods supporting HTML POST and GET methods. You can invoke servlet methods directly in
the URL, within any HTML page or a Java Server Page, or from another servlet. Finally, you
have seen how a servlet maps to a client to access the servlet methods.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 28
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices cover the following topics:
Developing a simple servlet application in JDeveloper 11g
Testing the servlet in a Web browser
Modifying an HTML form to access the servlet
Modifying the servlet application to extract the user
credentials, connect to a database table, and validate the
user
Practice: Overview
The aim of the practices for this lesson is to develop a servlet application. You learn to develop a
simple servlet application by using the Oracle JDeveloper 11g integrated development
environment, and execute it from a Web browser. Later, you modify a login HTML form that
accepts a username and password, and makes a call to the servlet application. The servlet
application extracts the user credentials from the HTML form and validates it against a database
table.
Copyright 2009, Oracle. All rights reserved.
Developing a Web Application Using
JavaServer Pages
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Describe the relationship between JavaServer
Pages (JSP) and servlets
List implicit objects on JSP pages
Describe the semantics of JSP tags
Create a JSP segment
Explain the use of JSP tag files
Run and debug a JSP-based application
Objectives
The JavaServer Pages (JSP) specification is closely related to the servlet specification. It enables
you to create Web applications in a more productive manner. This lesson covers in detail JSPs
and their role in the Model-View-Controller (MVC) framework. JDeveloper provides a complete
environment for the creation, editing, and debugging of JSP pages. You learn how to use these
features in JDeveloper to simplify the development of JSP pages.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 3
Copyright 2009, Oracle. All rights reserved.
JavaServer Pages
Generates
Dynamic content
JSP
Connects to
EJB
Client
Request
Database
Response
JavaServer Pages
The idea behind servlets and JSP technology is to separate the presentation logic and business
logic and, therefore, to have thin clients. JSPs are based on Java servlet technology and are an
extension of servlets. JSPs can generate dynamic content just as servlets can. However, a JSP
has its own advantages.
The advantage of the JSP model is that Web designers need not be familiar with the Java
programming language to create JSPs. Programmers can provide JavaBeans and custom tags to
Web designers who are familiar with HTML. In this model, there are well-defined job roles for
Web page designers and application programmers.
Given that JSPs are built on servlet technology, the focus is on improving the programmers
productivity. JSP leverage the benefits of component technologies and, therefore, simplify the
task of the programmer.
The graphic in the slide shows that a client invokes a JSP with a URL. Note that, like servlets,
JSPs function by using the request-response model. Depending on the request from the client,
the JSP connects to a database or calls an Enterprise JavaBean (EJB), which in turn can connect
to a database. The JSP then creates dynamic content by using the output from the database or an
EJB, and returns the content to the client.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 4
Copyright 2009, Oracle. All rights reserved.
Comparing Servlets and JSPs
Servlets:
Are Java programs with
embedded HTML code
Generate dynamic content
Do not separate static and
dynamic content
JSPs:
Are HTML pages
with embedded Java code or
pure XML
Generate dynamic content
Separate static and dynamic
content
Comparing Servlets and JSPs
A JSP is an HTML page with embedded Java code. JSPs can also be pure Extensible Markup
Language (XML). A JSP takes an HTML page, adds a few tags, and automatically generates
dynamic content. A servlet also generates dynamic content, but it is not an HTML page. A
servlet is a Java program with embedded HTML code. Because a servlet is a Java program, the
programmer must take care of the syntax and semantics while developing a servlet. The servlet
must be compiled before it is executed.
Though you must know Java programming language and the API well before you can develop a
servlet, you need not be an expert in Java to develop a JSP. A Web page designer can develop a
JSP because JSPs mainly contain HTML/XML tags and additional JSP tags containing the Java
code.
In servlets, most of the Java code is written in the service method. However, in JSPs, the Java
code is embedded in JSP tags. This enables separation of the static and dynamic content in JSP.
All the static content is in the HTML tags, and the dynamic content (Java code) is in the JSP
tags.
Because a servlet is a Java program, the .class file must be created before it can be invoked.
A JSP is automatically compiled into a servlet when it is invoked for the first time. You need not
explicitly compile the source. However, if you use integrated development environment (IDE) to
develop JSPs, the JSPs are automatically compiled when you run them.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 5
Copyright 2009, Oracle. All rights reserved.
Invoking JSPs
HTML
JSP
Invoke
Servlet
JSP
Invoking JSPs
You can invoke a JSP in different ways, depending on the needs of your application:
Invoking a JSP with a URL: You can invoke a JSP directly with the URL
http://host:port/context-root/main.jsp, where:
- host is the name or IP address of the machine where JSP is running
- port is the port number on which the server is running
- context-root is the name with which the document is mapped to a client
- main.jsp is the name of the JSP file
Invoking a JSP from an HTML page, a servlet, or a JSP: In a practical scenario, the first
page is designed as a controller servlet, which invokes a JSP depending on user inputs.
You can also invoke a JSP from another JSP.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 6
Copyright 2009, Oracle. All rights reserved.
Date.jsp
<%@ page contentType="text/html;charset=WINDOWS-1252"%>
<html> <head>
<meta http-equiv="Content-Type" content="text/html;
charset=WINDOWS-1252">
<title> Show Date </title>
</head>
<body>
<h2> The current time is: </h2>
<p> <%= new java.util.Date() %> </p>
</body>
</html>
Date.jsp
The slide shows the JSP code for displaying the current time and date, and the result of invoking
the JSP. Note that the code mainly contains HTML tags. The Java code that is highlighted in the
slide displays the date and time dynamically. The content in the HTML tags form the static part
of this page.
JSPs are primarily component centric and not page centric. The page-centric model is easy to
learn and enables rapid development. However, users eventually realized that this is not the way
to build large, scalable Web applications. The logic that is written for scripted environments is
locked inside pages. Presentation logic is mixed with business and data logic, making
application maintenance difficult because programmers attempted to modify the look-and-feel of
an application without breaking the tightly coupled business logic. As Web application
complexity increased, the limitations of the page-centric model became obvious.
At the same time that users were looking for better ways to build Web applications, components
were being actively developed in the client and server world. Java and Windows application
developers were using JavaBeans and ActiveX, respectively.
JSPs are primarily a component-centric platform. Components can be shared across JSPs, and
both non-Java developers and Java developers can use them.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 7
Copyright 2009, Oracle. All rights reserved.
Date Servlet
...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Show Date
</title></head><body><h2>The current time
is:</h2><p>");
out.println(new java.util.Date());
out.println("</body></html>");
out.close();
}
...
Date Servlet
The previous slide talked about Date.jsp. Consider writing a servlet instead of JSP to display
the date. The code in the slide shows the doGet() method of the date servlet. Note that all the
HTML tags (highlighted in the slide) and their data are passed to the println() method as a
java.lang.String. This is a simple servlet that displays the date, but still includes many
println statements. It is too cumbersome to design a complex page, which includes both
static and dynamic content.
Note that a single println statement can replace all the println statements in the servlet:
out.println("<html><head><title>Show
Date</title></head><body><h2>The current time is:</h2><p>"+
new java.util.Date()+ "</body></html>");
However, if you split the HTML tags with different println statements, it is much easier to
revisit or debug the servlet.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 8
Copyright 2009, Oracle. All rights reserved.
Automated JSP Features
A JSP is automatically converted into a servlet the first
time it is invoked:
Java source files are generated.
Java class files are generated.
The Java Just-In-Time compiler can be used.
A JSP can contain extensible components:
Tags: Libraries such as custom-developed tags
JavaBeans (Beans are reused and their properties are
automatically introspected.)
Automated JSP Features
Unlike servlets, you need not compile JSPs. When you invoke a JSP for the first time, the JSP is
automatically converted into a servlet. The dynamic content (Java code) in the JSP is inserted in
the _jspService() method of the servlet and the static content remains untouched.
Therefore, the first time a JSP is invoked, your response time is likely to be slow. With
subsequent requests, however, you obtain the full benefits of the servlet technology.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 9
Copyright 2009, Oracle. All rights reserved.
JSP Life Cycle
http://host/date.jsp
Java EE
container
Create servlet
date.java.
Compile servlet
date.class.
1
Servlet life cycle
First
time
Yes
2
3
No
WebLogic
Server
JSP Life Cycle
When the Web server receives a request, the server deciphers the request to determine whether
the request is for a JSP. The JSP engine verifies whether the corresponding servlet class exists.
If the servlet does not exist, this is the first time the JSP has been requested. Thus, the JSP life
cycle is traversed as follows:
1. The JSP is translated into a servlet. During the translation phase, each tag in the JSP is
handled differently because some of the tags provide instructions for the container and
some are used to create dynamic content.
2. After the translation is done, the servlet source file is compiled and a servlet class file is
generated.
3. The server then executes the servlet by following the life cycle of the servlet.
If the servlet already exists, the servlet is executed as mentioned in step 3.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 10
Copyright 2009, Oracle. All rights reserved.
Basic JSP Elements
A JSP contains three main elements:
Text elements
Directives
Scripting elements:
Declarations
Expressions
Scriptlets
Basic JSP Elements
Text elements: Text elements represent the static portion of the page and are formatted through
standard HTML or XML.
Directives: These elements provide instructions to the JSP at run time. The JSP container
processes the instructions that are provided in the directives while compiling the JSP.
Scripting elements: These elements represent the dynamic portion of the page. They contain
Java code. They are used to perform computation and to generate dynamic content. They include
tags called scriptlets, expressions, and declarations. The code in these scripting elements is put
in the _jspService method, which in turn is called by the service method of the servlet when
the JSP is translated to a servlet.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 11
Copyright 2009, Oracle. All rights reserved.
Declarations
Are used to define methods or variables
Begin with the sequence <%!
End with the sequence %>
Are inserted into the body of the servlet class, not within a
method, during translation
Are used in conjunction with expressions or scriptlets
<%! private int i=3; %>
<%! private String a="Hello", b=" World"; %>
Declarations
JSP declarations <%!...%> are used to declare the methods or variables that are inserted outside
the _jspService() method, whereas the scriptlet tag <%...%> generates code inside the
_jspService() method.
Here is an example of a JSP followed by the generated servlet code. The servlet code is not the
complete class, but shows the relevant parts.
<%! private int useCount = 0;
private static int countryCode = 25;
public int getSquare(int k){
return k*k;
}
%>
<TABLE BORDER="1">
<% int n =8;
for (int j=1; j <=n;j++){ %>
<TR><TD><%=j%></TD><TD><%=getSquare(j)%></TR>
<%}%>
</TABLE>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 12
Declarations (continued)
private int useCount = 0;
private static int countryCode = 25;
public int getSquare(int k){
return k*k;
}
public void _jspService(...){
// generated page context code not shown
out.write(_text[1]);
int n =8;
for (int j=1; j <=n;j++){
out.write(_text[2]);
out.print(j);
out.write(_text[3]);
out.print(getSquare(j));
out.write(_text[4]);
}
out.write(_text[5]);
}//end _jspService( )
private static final char _text[][]=new char[6][];
static {
_text[0] ="\n<html>\n <head>\n ...".toCharArray() ;
_text[1] ="\n<TABLE BORDER=\"1\">\n".toCharArray();
_text[2] ="\n<TR><TD>".toCharArray();
// finishing code not shown
}
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 13
Copyright 2009, Oracle. All rights reserved.
Expressions
Begin with the sequence <%=
Contain Java expressions that are evaluated and inserted
into the servlets output
End with the sequence %>
Do not end with a semicolon
<%= i+1 %>
<%= a + b %>
<%= new java.util.Date() %>
1
2
Expressions
Expressions are used to insert values directly into the output. The expression is evaluated first
and the result is converted to a string. For every expression in the JSP, a print statement is
inserted in the _jspService() method. Therefore, the resultant string is then written to the
output. The expressions are evaluated at run time.
1. The variable I is declared and initialized to 3 (in the previous slide). Therefore, this
expression prints the value 4. Similarly, a is initialized to Hello and b is
initialized to World. The expression a + b prints Hello World. This is the same as:
<%= "Hello" + " World" %>
2. This expression prints the current time and date.
The slide shows three expressions. The corresponding translated code that is put in the
_jspService() method is as follows:
out.print(i+1);
out.print("Hello" + " World");
out.print(new java.util.Date());
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 14
Copyright 2009, Oracle. All rights reserved.
Scriptlets
Begin with the sequence <%
Contain a block of Java code that is executed every time a
request is made
End with the sequence %>
<% if (i<3)
out.print("i<3");
if (i==3)
out.print("i==3");
else
out.print("i>3");
%>
Scriptlets
Scriptlets enable you to write blocks of Java code inside the JSP. This code is executed every
time the JSP is invoked. The code inside the scriptlet is inserted exactly as it is written into the
_jspService() method. A scriptlet can contain any valid Java code. Any errors in the
scripting elements are thrown during translation time or compilation time.
The slide shows an example of a scriptlet. You can alternatively write the code as shown below:
<%if (i<3) %>
i<3
<%if (i==3) %>
i==3
<%else %>
i>3
In this code, whatever is not enclosed within the scriptlet is treated as HTML code and gets
converted to print statements during translation. Therefore, you need not enter the print
statements repeatedly.
In the example shown in the slide, the out variable, which has not been declared so far, is used.
The following slide discusses this variable.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 15
Copyright 2009, Oracle. All rights reserved.
Implicit Objects
There are eight implicit objects, also known as predefined
variables, in JSP:
request
response
session
out
application
config
pageContext
page
Note: These objects are created in the generated servlet.
Implicit Objects
In JSP, implicit objects are provided. You can use these predefined variables without explicitly
declaring them. Implicit objects are created by the container, and contain information related to
a particular request, page, or session.
request: This variable is the HttpServletRequest object that is associated with
the request. You can access the request parameters, such as request type, HTTP headers,
and so on with this variable.
response: This variable is the HttpServletResponse object that is associated with
the response to the client.
session: This variable is the HttpSession object that is associated with the request.
Sessions are created automatically. You can also disable the sessions if you do not want to
associate a session with each client.
out: This variable is the PrintWriter object that is used to send the output to the
client.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 16
Implicit Objects (continued)
application: Servlets and JSPs store persistent data in the ServletContext
object. The application variable is the ServletContext object.
config: This variable is used to store the ServletConfig object for the page.
pageContext: The pageContext object is used to give a single point of access to
page attributes.
page: The page object is a synonym for this. It is useful if the JSP is not scripted in
Java.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 17
Copyright 2009, Oracle. All rights reserved.
Example
Example
You have learned about declarations, expressions, and scriptlets. This slide shows the result of
putting them together. The code for the example is as follows:
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
<title> Declaration Expression and Scriptlet </title> </head>
<body bgcolor="pink">
<h3> Declarations </h3>
<b> Declare i </b> &lt%! private int i=3; %&gt <%! private
int i=3; %><br>
<b> Declare Strings a and b </b>&lt%! private String
a="Hello", b=" World"; %&gt <%!
private String a="Hello", b=" World"; %>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 18
Example (continued)
<h3> Expressions </h3>
&lt%= i+1 %&gt <b> output </b> <%= i+1 %> <br>
&lt%= a + b %&gt<b> output </b><%= a + b %>
<h3> Scriptlet </h3> &lt% if (i<3) <br> out.print("i<3");
<br> if (i==3) <br>
out.print("i==3"); <br> else <br>
out.print("i>3"); %&gt <b> output </b> <% if
(i<3)out.print("i<3"); if (i==3)
out.print("i==3"); else out.print("i>3"); %> </body> </html>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 19
Copyright 2009, Oracle. All rights reserved.
Quiz
Which of the following pieces can a JSP be broken down into?
1. Static data such as HTML
2. JSP directives
3. JSP scripting elements and variables
4. A servlet class
Answers: 1, 2, 3
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 20
Copyright 2009, Oracle. All rights reserved.
Directives
Are used to set global values such as class declarations
and method implementations
Begin with the sequence <%@
End with the sequence %>
Are of the following types:
page
include
taglib
Directives
JSP directives contain messages to the JSP container. They are used to set global values. All
directives have the scope of the JSP that contains the directives.
The page directive: The page directive is used to define the important attributes for a JSP.
You can include a page directive any number of times in a JSP. You learn about the various
attributes of the page directive later in this lesson.
The include directive: This directive is used to include files in the current JSP. The file
output occurs at the location of the directive in the JSP file. Whatever file you include is
interpreted when the JSP is translated into a servlet. Typically, you use the include directive
to include files that rarely change (such as a navigation bar). For example:
<%@ include file="/navigation.jsp" %>
You cannot include another dynamic page with the include directive.
The URL that is specified for the file is interpreted relative to the path of the JSP page.
The taglib directive: This directive is used to specify custom markup tags.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 21
Copyright 2009, Oracle. All rights reserved.
include: Example
include: Example
The slide shows the result of including an HTML page in a JSP. The include directive is used
to include the file, and the file attribute is used to hold the path of the file. The HTML file that is
included is as follows:
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;
charset=windows-1252"/>
<TITLE>untitled</TITLE>
</HEAD><BODY >
<b><font color="red" size="3" >CONTENT FROM INCLUDED FILE
</font> </b>
</BODY>
</HTML>
The JSP code that is used to include the file is as follows:
...
<body>
<b>Including the content from a file here, using the &lt%@
include file=" " %> tag </b>
<br><%@ include file="includefile.html" %>
</body> ...
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 22
Copyright 2009, Oracle. All rights reserved.
page Directive
You can define the following attributes by using the page
directive:
import
contentType
isThreadSafe
session
buffer
autoFlush
extends
info
errorPage
isErrorPage
language
page Directive
The page directive can specify several attributes for the JSP:
import: This attribute takes a list of packages or classes, separated by commas that must
be imported by the servlet class created for a JSP.
contentType: This attribute sets the Multipurpose Internet Mail Extensions (MIME)
type for the response of the JSP. The default is text/html.
isThreadSafe: If this attribute is set to false, the client requests are queued for
processing because the generated servlet implements SingleThreadModel. The default
value is true.
session: If this attribute value is false, a clients request is not associated with a session.
The default value for a session attribute is true.
buffer: The buffer attribute can take a size in KB or the value none for the amount of
data that is to be buffered before the page is sent to the client. The default is 8 KB.
autoFlush: If the autoFlush attribute is set to false, a run-time exception is raised to
indicate buffer overflow. The default value is true, in which case the buffer to the client is
flushed automatically when it is full.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 23
page Directive (continued)
extends: The extends attribute is used to specify the class name that the generated
servlet class must extend.
info: This attribute is used to define a string that can be retrieved from the generated
servlet by using the getServletInfo() method.
iserrorPage: This attribute is used to specify whether or not the JSP is an error page.
If it is an error page, the implicit variable exception is available. This page can be invoked
by another JSP when an unchecked run-time exception is thrown.
errorPage: This attribute defines the URL to another JSP, which is an error page that is
invoked when an unchecked run-time exception is thrown.
language: This attribute defines the scripting language that is to be used in JSP.
taglib Directive
A taglib directive defines a tag library and prefix for the custom tags used on the JSP page.
The taglib directive declares that the JSP page uses custom tags, names the tag library that
defines them, and specifies their tag prefix. You must use a taglib directive before you use
the custom tag on a JSP page. You can use more than one taglib directive on a JSP page, but
the prefix defined in each must be unique.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 24
Copyright 2009, Oracle. All rights reserved.
JSP and JavaBeans
package lesson05;
import java.lang.*;
import java.util.*;
public class LuckyNumberBean {
private int luckyNum;
public LuckyNumberBean() {
luckyNum = (int) (1000 * Math.random());
}
public int getLuckyNum() {
return luckyNum;
}
public void setLuckyNum(int luckyNum) {
this.luckyNum = luckyNum;
}
}
JSP and JavaBeans
As mentioned already, JSP is component centric. You can use reusable components, such as
JavaBeans, in a JSP. A JSP provides tags to use JavaBeans. In simple applications, a JSP
includes the presentation logic as well as the business logic. The Date JSP is an example of such
a page. When there is more code involved, it is important to separate business logic and
presentation logic. You can use JavaBeans to implement the business logic and return data to the
JSP, which, in turn, formats the data and displays it in the browser. The following are the
benefits of using JavaBeans on JSP pages:
JavaBeans are reusable components. Therefore, different applications can use these
components.
Using JavaBeans results in the separation of business logic and presentation logic.
The slide shows an example of JavaBeans. According to the JavaBean specification, a JavaBean
should:
Have a zero-argument constructor
Have no public instance variables
Have accessor methods to set or get a value for each property
The example shown in the slide has a zero-argument constructor. LuckyNumberBean has a
luckyNum property. getLuckyNum() and setLuckyNum(int) are the accessor and
mutator methods, respectively, for the luckyNum property.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 25
Copyright 2009, Oracle. All rights reserved.
Using JavaBeans with JSP
Accessing JavaBeans with the <jsp:useBean> tag:
<jsp:useBean id="myBean" scope="session"
class="lesson05.LuckyNumberBean" />
Using JavaBeans with JSP
Actions are specific tags that affect the run-time behavior of the JSP and affect the response.
Note that these tags are in the XML format. The action tags in JSP are:
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:include>
<jsp:forward>
<jsp:plugin>
<jsp:param>
The <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> tags are the
action tags that are used with JavaBeans. The code given in the slide is used to instantiate an
object of the LuckyNumberBean class, and to bind it to the myBean variable. The
<jsp:useBean> tag hides the Java syntax and makes it easier to associate request parameters
with Java objects. You can also share the objects among multiple requests.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 26
Using JavaBeans with JSP (continued)
The attributes of the <jsp:useBean> tag are:
id: This attribute is used to specify a name for the object of the class.
scope: This attribute defines the scope of the object. You learn more about this
attribute in the following slide.
<jsp:include>: This tag includes a file (usually, .html or .jsp) in a JSP at request
time.
<jsp:include page="{relativeURL | <%= expression %>}" />
<jsp:forward>: This tag is used to send a request to a file. A JSP file can use this tag to
forward the client request to an HTML file, a JSP file, or a servlet for processing.
For example:
<jsp:forward page="{ relativeURL | <%= expression %> } />
<jsp:plugin>: This tag downloads a Java plug-in to the client Web browser to execute
an applet or a bean:
<jsp:plugin type=" bean| applet "
code=" classFileName "
codebase="classFileDirectoryName"
[ name=" instanceName " ][ archive="URIToArchive, ..." ]
[ align=" bottom | top | middle | left | right" ]
[ height=" displayPixels " ]
[ width="displayPixels " ]
[ hspace=" leftRightPixels " ]
[ vspace=" topBottomPixels "]
[ jreversion=" JREVersionNumber | 1.1 " ]
[ nspluginurl="URLToPlugin " ]
[ iepluginurl=" URLToPlugin "] >
[ <jsp: params>
[ <jsp: param name=" parameterName " value="
parameterValue " /> ] +
</ jsp: params> ]
[ <jsp: fallback> text message for user
</ jsp: fallback> ]
</ jsp: plugin>
<jsp:param>: This tag is used with <jsp:plugin> to specify values for the applet
parameters.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 27
Copyright 2009, Oracle. All rights reserved.
page scope
scope Attribute of <jsp:useBean> Tag
Client
Page 1 Page 2 Page 3
Request
Forward
Response
Request
Response
page scope page scope
request scope
request scope
session scope
scope Attribute of <jsp:useBean> Tag
The scope attribute determines the life of the bean object depending on the context to which it
is bound. The scope attribute can have the following values:
page: This is the default value. The bean object is placed in the pageContext object
and the servlet code can access it by calling the getAttributes() method on the
predefined pageContext variable.
request: The bean object is placed in the ServletRequest object. Use the
request object to include the bean from any JSP that is processing the same request
(until the JSP sends a response to the client, or forwards the request to another file). You
can use the request object to access the bean.
session: The bean object is stored in the HttpSession object that is associated with
the client. It can be retrieved by using the getSession() method.
application: The bean object is stored in the shared ServletContext.
ServletContext is shared by all servlets in the same Web application. You can use the
getAttribute() method to retrieve values from ServletContext.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 28
Copyright 2009, Oracle. All rights reserved.
Accessing and Setting Bean Properties
Accessing bean property:
Setting bean property:
<jsp:getProperty name="myBean"
property="luckyNum" />
<jsp:setProperty name="myBean"
property="luckyNum" value="10" />
Accessing and Setting Bean Properties
Accessing Bean Property
The <jsp:getProperty> action is used to access bean property as shown in the slide. The
value of the name attribute should match the value of the ID that is given in the
<jsp:useBean> tag. The property attribute identifies the property of the bean that is being
accessed. You can also use the following code to retrieve the bean property:
<%= myBean.getLuckyNum() %>
You can use this when with loops, conditional statements, and so on.
Setting Bean Property
The <jsp:setProperty> action is used to set the bean property. The value of the name
attribute should be the name of the bean instance that is defined by the <jsp:useBean> tag.
The property attribute holds the name of the property that is being changed, and the value
attribute holds the new value for the property.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 29
Accessing and Setting Bean Properties (continued)
The property in a bean can be set from request parameters, expressions, and a specified
string.
Example:
<jsp:setProperty name="myBean" property="luckyNum"
value='<%= Integer.parseInt(request.getParameter("num"))
%>' />
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 30
Copyright 2009, Oracle. All rights reserved.
JSP XML Document
Contains <jsp:root> as its root element
Includes only the XML syntax and does not include the
traditional JSP tags
Can be processed directly by the JSP container
Can be used with XML development tools
JSP XML Document
Traditional JSP tags cannot be used within an XML document. JSP 1.1 defines JSP syntax that is
compatible with XML. For example, the XML syntax for a traditional declaration tag is: <%!
%>, <jsp:declaration> </jsp:declaration>.
In JSP 1.1, a JSP can contain both traditional syntax and XML syntax. However, beginning with
JSP 1.2, you cannot intermix these tags on a page.
A JSP that contains the XML syntax is called a JSP XML document or a JSP document. A JSP
document is well-formed and contains only the XML syntax. <jsp:root> is the root element
of this document. The following are the three important goals of the root element:
Establishing the document as a JSP XML document, so that the JSP container can process
it
Identifying the namespaces for the XML syntax and custom tag libraries through the
xmlns attribute
Specifying a JSP version number
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 31
Copyright 2009, Oracle. All rights reserved.
Traditional Syntax Versus XML Syntax
Traditional:
It has no root element.
page directive
<%@page %>
Declaration tag
<%! %>
Expression tag
<%= expression %>
Scriptlet
<% %>
XML:
<jsp:root> is the root
element.
<jsp:directive.page/>
<jsp:declaration>
...
</jsp:declaration>
<jsp:expression>
...
</jsp:expression>
<jsp:scriptlet>
...
</jsp:scriptlet>
Traditional Syntax Versus XML Syntax
The slide shows the XML syntax for some of the traditional tags described in this lesson. You
have already learned that <jsp:root> is the root element of a JSP document. You now see
how to use the XML syntax in a JSP document.
<jsp:root xmlns:jsp="http://.."
xmlns:temp="http://"
version="1.2" >
body elements
</jsp:root>
The page Directive and include Directive
<jsp:directive.page language=" " import=" " />
<jsp:directive.include file=" " />
Declaration Tag
<jsp:declaration>
public void setCount(int i) { if(i &lt; 10) count=i;}
</jsp:declaration>
Expression Tag
<jsp:expression> (user==null)? " ":user </jsp:expression>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 32
Traditional Syntax Versus XML Syntax (continued)
Scriptlet
<jsp:scriptlet>
if (request.getParameter("name").equals(" "))
{........}
</jsp:scriptlet>
The JSP action tags, such as <jsp:useBean>, <jsp:forward>, and so on, are XML
compatible.
Text Element
When a JSP container encounters the text element, <jsp:text>, it passes the contents to the
current JSP out object. The code <jsp:text> Hello World </jsp:text> displays
Hello World when you run the JSP document.
JSP XML View
In JSP1.2, the JSP document can be directly processed by a JSP container. The container creates
an XML version, called XML view, of the parsing result. This XML view is the mapping of a
JSP (either a traditional page or a JSP XML document) into an XML document that describes it.
The XML view can be used by validator classes to validate a page.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 33
Copyright 2009, Oracle. All rights reserved.
JSP Segments
Use a JSP segment for creating a partial JSP page.
Include one or more segments in a JSP using
<jsp:include>.
JSP segment footer.jspf:
JSP:
Copyright 2005,
<a href="http://www.oracle.com">
Oracle
</a>
<%@ include file="/footer.jspf"%>
JSP Segments
Using JSP segments adds a degree of consistency to an overall application. An application may
have hundreds of pages and each one should have the same branding or header information and
appearance. If the developer had to create a header for each page, there is a good chance of
creating inconsistencies across pages. Instead of coding each page, the developer can create a
single header segment and include it on each of the pages.
The JSP2.0 specification recommends that developers name these segments *.jspf and
include them in a separate directory such as /web-inf/jspf.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 34
Copyright 2009, Oracle. All rights reserved.
Quiz
A JSP XML document contains both XML syntax and the
traditional JSP tags.
1. True
2. False
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 35
Copyright 2009, Oracle. All rights reserved.
What Is a Tag Library?
JSPs define six standard actions: useBean,
getProperty, setProperty, include, forward and
plugin.
JSPs allow developers to define custom actions that can
be invoked by using custom tags.
A tag library is a collection of custom tags.
Custom tags can be used to process forms, send mails,
access database, control flow, or perform business logic.
What Is a Tag Library?
JSP 1.1 introduced the ability to create and use custom tags in JSP pages. Custom tags enable
you to abstract the complexity of business logic from the presentation of Web pages. This makes
it easy for the Web author to use and empowers Web page designers, who are often not fluent in
Java coding, to have access to powerful functions using an easy tag-based interface. You can use
custom JSP tag extension in JSP pages to generate dynamic content, and you can use several
Web development tools to create the presentation. WebLogic Server 10.3 fully supports the JSP
2.0 specification.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 36
Copyright 2009, Oracle. All rights reserved.
Tag Interfaces
Implement tags using interfaces and classes in
javax.servlet.jsp.tagext.*.
Custom tags implement interfaces Tag, BodyTag, and
SimpleTag, and are called as tag handlers.
Tag Interfaces
You write a custom JSP tag by writing a Java class called a tag handler. You write the tag
handler class by implementing any one of the three interfaces. Tag, BodyTag, or SimpleTag
defines methods that are invoked during the life cycle of the tag or by extending an abstract base
class that implements one of these interfaces. Extending an abstract base class relieves the tag
handler class from having to implement all methods in the interfaces and also provide other
convenient functionality. The TagSupport, BodyTagSupport, and
SimpleTagSupport classes implement these interfaces and are included in the API.
One or more custom JSP tags can be included in a tag library. A tag library is defined by a tag
library descriptor (TLD) file. TLD describes the syntax for each tag and binds it to the Java
classes that execute its functionality.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 37
Copyright 2009, Oracle. All rights reserved.
Tag Handlers
Are objects that a JSP invokes when it encounters a
custom tag
Provide several methods that are called at various stages
of a tags life cycle. For example:
import javax.servlet.jsp.tagext.*
...
public class SayHelloTag extends SimpleTagSupport {
private String var;
...
public void doTag() throws JspException {
//contains tag logic, iteration, body evaluations
...
}
...
public void setVar( String var ) {
...
}
Tag Handlers
Simple tag handlers differ from classic tag handlers in supporting doStartTag() and
doEndTag(). The SimpleTag interface provides a simple doTag() method, which is
called only once for any given tag invocation. All tag logic, iteration, body evaluations, and so
on are to be performed in this single method. A SimpleTag handler must have a public no-
argument constructor. Most simple tag handlers should extend the SimpleTagSupport class.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 38
Copyright 2009, Oracle. All rights reserved.
Tag Library Descriptor
A tag library descriptor describes a custom tag library.
<?xml version = '1.0' ...?>
<taglib ... >
<tlib-version>1.0</tlib-version> <!-- Tag lib version -->
<short-name>...</short-name> <!- Preferred name -->
<uri>...</uri> <!- uniquely identifies the tag library-->
<tag>
<description>...</description> <!- Describes tag library -->
<name>sayHello</name> <!- Defines tag name -->
<tag-class>tag.SayHelloTag</tag-class> <!- Specify tag handler class-->
<body-content>empty</body-content>
<attribute> <!-- Declares an attribute -->
<name>var</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Tag Library Descriptor
A tag library descriptor is an XML document that contains information about a library as a
whole and about each tag contained in the library. TLDs are used by a Web container to validate
the tags and by JSP page development tools. The tag library descriptor file names must have the
extension .tld and must be packaged in the /WEB-INF/ directory or subdirectory of the
WAR file or in the /META-INF/ directory or subdirectory of a tag library packaged in a JAR
file.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 39
Copyright 2009, Oracle. All rights reserved.
Implementing Simple Tags
Implementing Simple Tags
The slide shows the invocation of a custom tag. The JSP locates the tag library by referring the
Web.xml file.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 40
Copyright 2009, Oracle. All rights reserved.
JSP Expression Language
Enables access to application data stored in JavaBeans
component
Is simple to implement as compared to custom tags and
scriptlets
Syntax (JSP and XML)
${expression}
Examples:
${1.2 + 2.3}
${4.0 >= 3}
${customer.firstName}
JSP Expression Language
The JSP expression language (EL) greatly simplifies JSP authoring by removing the need to use
embedded Java scriptlets and expressions to access request parameters or application data stored
in JavaBeans.
The expression language has its own syntax, partially based on the JavaScript syntax. The
expression language is invoked through the ${expression} syntax. The most basic semantic
is that invocation of a named variable ${foo} yields the same result as the method call
PageContext.findAttribute(foo).
To access named properties within JavaBeans and within collections such as lists, maps, and
arrays, the expression language supports the "." and "[]" operators. For example,
employee.phones.cell is equivalent to employee.getPhones().getCell() in
Java syntax.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 41
Copyright 2009, Oracle. All rights reserved.
Expression Language Implicit Objects
...
First Name: <input type='text' name='Name'/>
Last Name: <input type='text' name='Address'/>
<input type='submit' value='Submit'/>
...
...
Name is : ${param.Name}
Address is : ${param.Address}
...
Second.jsp
First.jsp
The expression language provides the following implicit objects:
pageScope
requestScope
sessionScope
param
header
pageContext
Expression Language Implicit Objects
The expression language provides the following implicit objects:
pageScope: Allows access to page-scope variables
requestScope: Allows access to request-scope variables
sessionScope: Allows access to session-scope variables
pageContext: Allows access to all properties of the page context of a JSP page
param: A Java Map object containing request parameters typically accessed using the
request.getParameter() method. The expression ${param["foo"]} or the
equivalent ${param.foo} both return the first string value associated with the request
parameter foo.
header: As with param, you can use this object to access the first string value
associated with a request header
The example in the slide shows a part of the code from two JSP files: First.jsp and
Second.jsp. In First.jsp, you enter the name and address, click the Submit button, and
the flow goes to Second.jsp. You can retrieve the values by using the
${param.xxxx}syntax.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 42
Copyright 2009, Oracle. All rights reserved.
JDeveloper and JSPs
The JSP Wizard in JDeveloper is used to create JSPs
containing skeleton code.
Structure Pane helps to ensure that the JSP and HTML
tags are properly formatted.
Tag Insight automatically inserts end tags after starting a
scriptlet.
The JSP code is automatically created and recompiled.
JDeveloper increases productivity while debugging JSPs:
Automatically includes source Java files such as your
JavaBean source
Enables you to set breakpoints and watch expressions in
JSPs
JDeveloper and JSPs
JDeveloper gives you many tools for simplifying your JSP development.
The JSP Wizard creates a JSP that contains skeleton code.
The Structure Pane and Tag Insight features help you develop syntactically correct JSPs.
When you launch your JSP, the code is re-created when needed, and recompiled.
The integrated debugger enables you to systematically run the JSP that you have written,
while viewing the generated servlet code and any JavaBeans.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 43
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Identify the differences and similarities between JSPs and
servlets
Use declarations, expressions, scriptlets, and implicit
objects on JSP pages
Use JavaBeans with JSPs
Create a JSP segment
Explain the use of JSP tag files
Run and debug a JSP-based application
Summary
JSPs are based on Java servlet technology and are an extension of servlets. JSPs can generate
dynamic content just as servlets can. However, Web designers can create JSPs with no Java
knowledge, with JavaBeans and custom tags written by programmers. A JSP is automatically
compiled into a servlet when it is invoked for the first time.
There are eight implicit objects, or predefined variables, that are created by the JSP container:
request, response, session, out, application, config, pageContext, and page.
JSP syntax includes directives (<%@directive%>) and action tags (<jsp:action>). You can
define JSP segments as .jspf files and include them on a page with the <%@include%
file="<filename>"> directive. Beginning with JSP 2.0, you can use tag files to abstract a
segment of JSP code and make it reusable using a custom action.
JDeveloper provides tools to help you create, run, and debug JSPs.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 44
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Building a basic JSP application
Building a JSP application that uses a Java bean to
implement the business logic
Building a JSP application using custom tags and
expression language
Copyright 2009, Oracle. All rights reserved.
Accessing Resources with JNDI
and Dependency Injection
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Describe the Java Naming and Directory Interface (JNDI)
Locate or look up resources and EJBs by using:
JNDI APIs
Dependency injection (DI)
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 3
Copyright 2009, Oracle. All rights reserved.
Java Naming and Directory Interface
The JNDI is:
A standard set of interfaces that provide:
Naming services
Directory services
A service provided by Java EE containers to locate Java
EE resources or objects such as:
Data sources
Environment references
EJBs and JMS components
JNDI API JNDI SPI
Programmatic interfaces
RMI Registry
COS Naming
LDAP
JNDI provider
implementations
JNDI client
Object
Java Naming and Directory Interface
Java EE applications use the following parts of the JNDI specifications to find other distributed
objects:
An application-level interface used by client programs to access a naming and directory
service
A service-provider interface used by the JNDI API to communicate with a provider of a
naming and directory service, in a vendor-independent manner
Client applications use JNDI properties and the API to:
Connect with a JNDI service provider by establishing an initial context
Locate an object by its registered name by calling a lookup operation from the initial
context
The server implements the JNDI Service Provider Interface (SPI) library that generalizes access
to different types of JNDI provider implementations, such as Remote Method Invocation (RMI)
Registry, Common Object Services Naming, Lightweight Directory Access Protocol (LDAP),
and others. This enables different types of directory-service and naming-service
implementations to be transparently used by the Java EE container.
The types of objects typically stored in a JNDI service provider include the bean interface for
Enterprise JavaBeans (EJB) components, Java Database Connectivity (JDBC) data sources, and
Java Message Service (JMS) resources.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 4
Copyright 2009, Oracle. All rights reserved.
JNDI Structure
WLS
Server
WLS
Driver
Naming Manager
Service
Purchased
JNDI API
Written by
Developer
Other
DNS
System
File
System
LDAP
Server
Other
DNS
Driver
File Sys
Driver
LDAP
Driver
JNDI SPI
JNDI API
Application Code
JNDI Structure
As you can see, a variety of naming and directory services exist in production today. These
include services such as:
Lightweight Directory Access Protocol (LDAP)
Domain Name Service (DNS)
Network Information Service (NIS)
Remote Method Invocation (RMI)
Using the JNDI SPI, service providers for these industry naming and directory services provide a
mapping from JNDI to their particular service. Java applications can then use the JNDI API to
access any individual service uniformly. Access to the service is provided using a Naming
Manager.
A complete list of existing service providers can be located at:
http://java.sun.com/products/jndi/serviceproviders.html
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 5
Copyright 2009, Oracle. All rights reserved.
Naming Service
A naming service provides a
method for mapping identifiers
to entities or objects:
Naming Service vocabulary:
ID3
ID2
Objects
ID1
Namespace
Binding
Term
www.oracle.com is bound
to 209.10.217.38
Association of an atomic name
and an object
www.oracle.com/products
Example
A set of unique names in a
naming system
Definition
Naming Service
WebLogic Server provides naming services to client applications. These are mainly used for
looking up EJBs, DataSources, JMS queues, and so forth.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 6
Copyright 2009, Oracle. All rights reserved.
JNDI Tree
Context B
is bound to
Initial Context.
Object 3
is bound to both
Context A and B.
A binding associates an object
with a logical name and a context.
IC
A
Object 1
is bound to
Initial Context.
Object 2
is bound to
Context A.
R Root Context
Initial Context
Object 1 Object 2 Object 3 Object 4
B
JNDI Tree
A JNDI tree is described in terms of the following components:
Context: A node in the JNDI tree. It can only contain a list of Objects and Contexts.
Object: A leaf in the JNDI tree. It is bound to a Context. It cannot contain other
Objects or Contexts.
Root Context: The topmost context in the whole tree
Initial Context: A Context chosen as a starting point for all future operations. This is
somewhat like a current directory that you choose. It does not always have to be the root
context of your directory structure. For instance, if you use your file system as a directory
structure for JNDI, the root context would be C:\. It does not, however, have to be the
initial context. The initial context is merely the starting point that can traverse through the
application. For example, in a JNDI program, to locate all the text files in the windows
temporary directory, the initial context might appropriately be C:\windows\temp
instead of C:\.
Observe the Object3 object in this diagram. It is binding to two different contexts: A and B.
Does the object bound in two different contexts exist once or twice in the naming service? Or,
worded differently, was the object accessed by value or by reference?
The truth is JNDI stores the objects by value, copying them into the tree. That means there are
multiple copies in the tree. To create a by reference binding, you need to use the LinkRef
class, which is not discussed here.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 7
JNDI Tree (continued)
Modifying an object under a context does not change the same object under a different context. In
the tree above, Object3 has really two different instances. The first instance lives under context
A, the second under context B.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 8
Copyright 2009, Oracle. All rights reserved.
Contexts and Subcontexts
Subcontexts are referenced through dot delimiters (.).
Subcontexts must be created before objects are placed
into them.
Typically, when objects are bound to the JNDI tree,
subcontexts are automatically created based on the JNDI
name.
For example, if the following context exists:
com.bea.examples
you cannot bind:
com.bea.examples.ejb.SomeObject
without first creating:
com.bea.examples.ejb
Contexts and Subcontexts
Subcontexts are referenced through simple dot delimitationfor instance, the name
com.bea.examples.
You cannot insert an object into the naming service unless its subcontext already exists. Suppose
SomeObject refers to an object in the examples context, which is a subcontext of com.bea.
In this example, you cannot bind an object named com.bea.examples.ejb.SomeObject
unless the ejb subcontext was first created. The JNDI will not automatically create the
subcontext because the name of the bound object has a subcontext listed in it.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 9
Copyright 2009, Oracle. All rights reserved.
Referencing Java EE Resources with JNDI
Provide JNDI properties:
java.naming.factory.initial
java.naming.security.principal
java.naming.security.credentials
java.naming.provider.url
Establish an initial context:
Perform the lookup operation:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, t3://localhost:7001"); ...
Context ctx = new InitialContext(env);
import javax.sql.DataSource; ...
DataSource ds =
(DataSource)ctx.lookup("jdbc/Data_Source");
Initial context
Lookup
jdbc ejb
Data_Source bean
client
Referencing Java EE Resources with JNDI
To reference a Java EE resource, such as a data source or a session EJB, the client code must:
Provide JNDI properties for establishing an initial context with a JNDI service
Establish an initial context (starting point) for a directory search (lookup) operation
Perform the lookup operation relative to the initial context
Standard JNDI Properties
JNDI properties are typically required when the client is executing remotely from the JNDI
resources it uses.
The following JNDI properties are used by the client and Java EE applications to reference JNDI
resources from a JNDI service:
java.naming.factory.initial specifies the initial context factory class used
when creating a new initial context object that establishes a connection to the JNDI
service.
java.naming.security.principal specifies a username with access to the JNDI
service. Some JNDI services do not require this property to be set.
java.naming.security.credentials specifies a password for the principal
specified in the principal property.
java.naming.provider.url specifies a URL that the application client code uses
to connect to the JNDI service provider.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 10
Copyright 2009, Oracle. All rights reserved.
Providing JNDI Properties
JNDI properties may be provided as:
A jndi.properties file in the CLASSPATH application
Entries added to a java.util.Hashtable object in the
application code
java.naming.factory.initial=weblogic.jndi.Environment.
DEFAULT_INITIAL_CONTEXT_FACTORY
java.naming.provider.url=t3://localhost:7001
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic
import javax.naming.*;
...
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001"); ...
Context ctx = new InitialContext(env);
Providing JNDI Properties
JNDI properties can be specified:
In a jndi.properties file located in the CLASSPATH application
In entries programmatically added to a java.util.Hashtable object in the
application code
The code example in the slide uses the second (programmatic) technique to set the JNDI
properties. However, it is more flexible to use the first technique to provide JNDI properties
because changes can be localized to the properties file without changing the source code.
The principal and credential values must be configured in the JNDI namespace of the target
container. Consider using the Hashtable technique to avoid placing unencrypted security
credentials in the property file. Use a Hashtable if there is a need to access the EJB with
different security credentials each time a lookup request is performed.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 11
Copyright 2009, Oracle. All rights reserved.
Referencing a Local Session EJB with JNDI
Within the same Java EE container (local reference):
Define dependency in the deployment descriptor:
In web.xml, from a servlet or JSP
In ejb-jar.xml, from another session EJB
Look up EJB using the reference name:
<ejb-local-ref>
<ejb-ref-name>ejb/sessionBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>ejb.EJBLocal</local>
</ejb-local-ref>
Context ctx = new InitialContext();
EJBLocal ref = (EJBLocal)
ctx.lookup("java:comp/env/ejb/sessionBean");
...
Referencing a Local Session EJB with JNDI
An EJB is packaged into an EJB-JAR file that is deployed as part of an Enterprise Archive
(EAR) file. The EJB component and its JNDI name are typically defined in the EJB deployment
descriptors stored in the EJB-JAR file. At deployment time, the JNDI name is bound to an EJB
interface object located in the JNDI service.
How you reference an EJB component depends on where the client code executes relative to the
EJB component. The client is one of the following:
A local client, which executes in the same Java EE container as the EJB component
A remote client, which executes in a different Java Virtual Machine (JVM) or Java EE
container from the EJB component
For a local EJB client application to reference a session EJB in the same Java EE container, it
must do the following:
1. Specify an <ejb-local-ref> element for the session EJB being referenced in the
deployment descriptor.
2. Obtain an initial context by using the default no-argument constructor of
InitialContext(). The JNDI properties are implicitly acquired from a
jndi.properties file provided by the container.
3. Execute a lookup operation with the EJB reference name in the deployment descriptor.
The client application lookup request is relative to the java:comp/env root, which may be
excluded from the JNDI name in the argument to the lookup() method.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 12
Copyright 2009, Oracle. All rights reserved.
Referencing a Remote Session EJB with JNDI
From a different JVM or Java EE container (remote reference):
Define dependency in the deployment descriptor:
In web.xml, from a servlet or JSP
In ejb-jar.xml, from another session EJB
In application-client.xml, for applications outside a
container
Look up EJB reference (provide jndi.properties):
<ejb-ref>
<ejb-ref-name>ejb/session</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>ejb.EJBRemote</remote>
</ejb-ref>
Context ctx = new InitialContext();
EJBRemote ref = (EJBRemote) PortableRemoteObject.narrow(
ctx.lookup("java:comp/env/ejb/session"),SessionBean.class);
...
Referencing a Remote Session EJB with JNDI
For a remote EJB client code (in another Java EE container or running as a stand-alone Java
application), the client application:
Defines an <ejb-ref> element with the JNDI name, the remote session EJB, and its
interface in the client deployment descriptor
Obtains an initial context by using a client-supplied set of JNDI properties in a
jndi.properties file in the CLASSPATH application
Performs the lookup operation by using the EJB reference name specified in the client
application deployment descriptor
Note: By convention, the remote Java code uses the
javax.rmi.PortableRemoteObject.narrow() method to assist casting the remote
object reference returned by the lookup operation to the appropriate Java interface class.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 13
Copyright 2009, Oracle. All rights reserved.
JNDI State Replication
The JNDI state replication feature is being supported in a
clustered WebLogic Servers environment.
WebLogic Server WebLogic Server
JNDI cluster
1 4
Bind message
sent to the
cluster
Bind message
propagated to all
the members of
the cluster
Instance 1 binds the
message
Instance 2 looksup the
bind message
2 3
JNDI State Replication
The JNDI state replication causes changes made to the context on one WebLogic Server instance
of a cluster to be replicated to the JNDI namespace of other WebLogic Servers in the cluster. By
enabling JNDI state replication, you can bind a serializable value into an application context
(using a remote client, EJB, or a servlet) on one server and read it on another server.
When a client connects to a cluster, it is actually connecting to one of the WebLogic Servers in
the cluster. Because the JNDI tree for this WebLogic Server contains the RMI stubs for all
services offered by the other WebLogic Servers in the cluster, in addition to its own services, the
cluster appears to the client as one WebLogic Server hosting all the clusterwide services. When
a new WebLogic Server joins a cluster, each WebLogic Server already in the cluster is
responsible for sharing information about its own services to the new WebLogic Server. With
the information collected from all the other servers in the cluster, the new server will create its
own copy of the clusterwide JNDI tree.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 14
Copyright 2009, Oracle. All rights reserved.
Quiz
When objects are bound to the JNDI tree, subcontexts are
automatically created based on the JNDI name.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 15
Copyright 2009, Oracle. All rights reserved.
What Are Annotations?
They are additional information (metadata) in the operating
code that instructs a development tool to process a Java
class in a specific way.
They are used to mark methods, classes, fields,
parameters, variables, and constructors.
What Are Annotations?
In Java, there are several classes, methods, and members that contain operating code. JSR-175
enables these sets of classes, methods, and members to be marked with additional information
that is not part of the operating code. For example, a Fuji apple has the attribute that it is red.
Assuming that there is a FujiApple class, you can specify its color by using an annotation of
the @Color annotation type. By doing this, you have provided metadata about the apple. This
information is used by development tools, deployment tools, or run-time libraries to process the
color attribute of the FujiApple class in a specific way. Such annotations are called metadata.
They can be used to describe the usage and meaning of entities such as methods and classes. For
example, the Java beans architecture uses different naming conventions for different methods
(such as getName and setName) to indicate what a particular method does (getName
retrieves the name; setName provides the name). Similarly, the EJB architecture also uses a
specific naming pattern to mark methods as remote method and home method.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 16
Copyright 2009, Oracle. All rights reserved.
Dependency Injection
The concept of dependency injection implies that it is:
A programming design pattern that enables you to inject
resources at run time
Based on the principle of Inversion of Control (IOC)
An alternative to the JNDI implementation
JMS resources
EJB
container/
Web
container
EJB/
Servlet
Injection
EJBs
Dependency Injection
Dependency injection (DI) is a programming design pattern that enables you to declare
component dependencies. It is based on the principle of Inversion of Control (IOC) that is used
to reduce dependencies between systems (loose coupling). DI enables one component to call
another component or resources through interfaces. The components are glued together by using
configuration, instead of code. The complexities of the service or resource instantiation,
initialization, sequencing, and lookup are handled by the specific container (EJB container for
the EJBs and Web container for the servlet).
DI enables you to declare the component dependencies at design time. The EJB container reads
the target EJB configuration, figures out what beans and resources the EJB requires, and injects
them into the target EJB at run time. For example, you can use @EJB annotation in a session
bean to inject EJBs. Similarly, the @Resources annotation can be used to inject non-EJB
resources such as a database connection.
The implementation of DI is totally opposite to that of the implementation of JNDI. In case of
JNDI, it is the responsibility of the EJB to do a lookup and obtain a reference of the resources.
As a result, the component and resource name are hard-coded in the EJB.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 17
Copyright 2009, Oracle. All rights reserved.
Dependency Injection
Dependency injection is introduced in the Java EE 5.0
specification:
Is based on declaring resources by using annotations (or
deployment descriptors)
Eliminates writing explicit JNDI API calls
Is used by classes managed by a Java EE container
Cannot be used by classes external to a Java EE
container
Is implemented by using the following key annotations:
@Resource (javax.annotation.Resource)
@EJB (javax.ejb.EJB)
Dependency Injection (continued)
In Java EE 1.4, many enterprise Java applications reference external resources and services, such
as DataSource, EJB, or Web services. As previously discussed, a client must:
Explicitly declare dependency on a resource in a deployment descriptor element
Obtain an initial context for a JNDI service
Perform a JNDI lookup operation to obtain a reference to the resource
Dependency injection:
Eliminates the requirement to write JNDI calls to reference resources, the inverse of JNDI
Is declared by using annotations or deployment descriptors. In Java EE 5, dependency
injection is provided through the declaration of a resource annotated with:
- @Resource for dependencies of resources, such as data sources, JMS resources,
and so on
- @EJB for a dependency on another EJB component
Note: The Java API for XML Web Services 2.0 defines the @WebServiceRef
annotation for injecting Web services references.
Is managed by the Java EE containerthat is, the Java EE 5.0 container handles the
complexities of service or resource instantiation and initialization by injecting an instance
of the dependent resource when required
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 18
Copyright 2009, Oracle. All rights reserved.
Types of Dependency Injection
The Java EE 5.0 specification supports the following types of
dependency injection:
Field injection, which injects a resource to a field
Setter (property) injection, which injects a resource by
invoking a setter method
@Resource (name = "jdbc/fodDS")
private javax.sql.DataSource fodDS;
private DataSource fodDS;
...
@Resource (name = "jdbc/fodDS")
private void setfodDS(javax.sql.DataSource ds) {
fodDS = ds;
}
Types of Dependency Injection
To use field injection, simply define a field and annotate it to be a resource reference. If you do
not define the resources name and type, the container derives this information from the fields
name and type. For example, you can inject a data source to a field as follows:
@Resource
private javax.sql.DataSource fodDS;
In the example, the data source within a JNDI name jdbc/fodDS must be available;
otherwise, the container throws an exception. Field injection must be completed before methods
of the managed class are invoked.
To use setter (or property) injection, define a set method and annotate it as a resource reference.
The application does not need to invoke the setter method; the Java EE container invokes the
setter method before the business methods into which the resources are being injected. If the
annotation name property or the data type of the setter injection is not defined, it is derived from
the setter methods name and parameter type.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 19
Copyright 2009, Oracle. All rights reserved.
Defining the @Resource Annotation
The @Resource annotation definition is:
The @Resource annotation parameters can be:
Derived
Explicitly specified
public @interface Resource {
public enum AuthenticationType {CONTAINER, APPLICATION}
String name() default "";
Class type() default Object.class;
AuthenticationType authenticationType()
default AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
}
Defining the @Resource Annotation
The parameters of the @Resource annotation (injecting only one resource) or @Resources
annotation (injecting two or more resources) are as follows:
name is a String type specifying the JNDI name of the resource.
type is a Class type of the resource being used.
authenticationType is an enum type value set to CONTAINER or APPLICATION
specifying the type of authentication needed to use the resource.
shareable is a boolean type indicating whether the resource is sharable. The default
value is true.
mappedName is a String type specifying the product-specific name that the resource
should be mapped to. This is a vendor-dependent name that is not portable across
containers.
description is a String type providing a brief description of the resource.
Note: Most annotation parameters (if not specified) are derived from the type of field or
property being injected. Other parameters have a default value if not specified, such as the
authenticationType, which has a default value of CONTAINER.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 20
Copyright 2009, Oracle. All rights reserved.
Using Java EE Resources with
Dependency Injection
Using Java EE resources with dependency injection is
performed with the @Resource annotation. Examples are:
Data sources:
JMS resources (a queue or topic):
Environment entries:
@Resource(name="jdbc/fodDS")
private javax.sql.DataSource myDS;
Connection conn = myDS.getConnection();
@Resource(name="jms/demoQueue")
private Queue myQueue;
@Resource int maxItemsPerCart = 20;
Using Java EE Resources with Dependency Injection
The first example shows how to reference a data source with dependency injection. The data
source with the JNDI name jdbc/fodDS must be defined.
The second example uses a resource annotation to inject a JMS destinationin this case, a
queue. To use the JMS queue as a resource, it must be defined in the JMS server configuration
file before you can define the dependency.
The third example defines environment entries, which generally specify business parameters that
may vary from one environment to another or from time to time. However, because this is a part
of the code, to change it requires modifying the code. It is better to use an <env-entry>
element in the deployment descriptor instead. Other resource examples can include:
Mail resources. For example:
- First, configure a mail resource in the application server.
- Use the Resource annotation to inject an instance of a mail session:
@Resource(name="mail/OrderEntry")
private javax.mail.Session ms;
EJB context. For example, to inject a SessionContext object, use:
@Resource javax.ejb.SessionContext ctx;
Timer service. For example, to inject TimerService to an EJB, use:
@Resource javax.ejb.TimerService ts;
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 21
Copyright 2009, Oracle. All rights reserved.
Working with Dependency Injection
Dependency injection:
Eliminates use of JNDI complexities
Results in fewer lines of code
Yields more concise code. However, annotations can:
Hard-code resources
Be overridden with XML elements in deployment descriptors
Cannot be used with helper classes, which must use JNDI
services
Working with Dependency Injection
Dependency injection makes resources and services easier to use because you eliminate the need
to manage the complexities of using JNDI. A number of lines of code or service locator patterns
written are reduced or eliminated.
Because Java EE supports dependency injection via either XML or annotation, use annotation
when it makes sense. An annotation can make your code more readable and concise but can also
cause maintenance problems, because they require that resource references be hard-coded into
the application code, as in the environment entry example seen earlier. However, annotations
can be overridden using XML elements in deployment descriptors.
A limitation of dependency injection is that it supports managed classes. Therefore, dependency
injection cannot be used from helper classes or from classes executing outside a Java EE
container. These helper classes must still use JNDI to use Java EE resources or services.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 22
Copyright 2009, Oracle. All rights reserved.
Referencing EJBs with Dependency Injection
In EJB 3.0, dependency is expressed by using:
The @EJB annotation:
The <ejb-ref> deployment descriptor element as an
alternative method
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface EJB {
String name() default "";
String beanName() default "";
String mappedName() default "";
String description() default "";
Class beanInterface() default Object.class;
}
Referencing EJBs with Dependency Injection
The parameters of the @EJB (referencing a single EJB 3.0 session bean) annotation or the
@EJBs (referencing multiple EJB 3.0 session beans) annotation are:
name: A String specifying the JNDI name of the EJB referenced
beanName: A String specifying the name of the EJB, defined by using either the
<ejb-name> element or the name parameter of the bean class
beanInterface: A Class type identifying the interface implemented by the object
mappedName: A String for a product-specific name to which the service is mapped
description: A String specifying a brief description of the EJB
Note: If a parameter is not specified, it is derived from the name of the field or property being
injected; otherwise, the default value is applied.
For example, to use an EJB named ShoppingCart from a servlet or another EJB, you can use
dependency injection to get an instance of the ShoppingCart EJB and invoke a method:
@EJB(mappedName="ShoppingCart")
private ShoppingCart myCart;
myCart.addItem("Item 1");
In this example, the name is the JNDI name of the EJB being injected. beanName is used to
remove ambiguity from a bean when more than one bean implements the same interface.
beanInterface is used when the EJB is used on a class without knowing which interface is
being used by the component.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 23
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe the Java Naming and Directory Interface (JNDI)
Locate or look up resources and EJBs by using:
JNDI APIs
Dependency injection
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 24
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Using the @Resource annotation in a servlet application to
access a database table
Using the @EJB annotation in a servlet application to inject
an EJB
Copyright 2009, Oracle. All rights reserved.
Developing the Business Logic with
Session Beans
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Describe session beans
Create stateless and stateful session beans by using
annotations
Describe the passivation and activation of stateful session
beans
Use interceptor methods and classes
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 3
Copyright 2009, Oracle. All rights reserved.
What Is a Session Bean?
A session bean is a type of Enterprise JavaBean (EJB) that:
Implements a business process
Represents a client/server interaction
Has a short lifespan
Lives in memory rather than in persistent storage
Is used to create a Session Facade
What Is a Session Bean?
Session beans represent actions in the business process, such as process order. A session bean
implements one or more business processes. For example, it can retrieve and update inventory
data in a database.
Note: A session bean can retrieve or update the data, but it does not necessarily represent
persistent data. That is, a session bean is not directly associated with a row of a database table.
As the name suggests, session beans are often used to model a client/server session or
conversation. The Session Facade pattern uses a session bean to provide a business service
interface to clients, while hiding the business objects that implement that service and their
interactions inside the application server.
Session beans are short-lived. Their life cycles are dependent on the clients session. When there
is a request for a session bean, the container instantiates the session bean and associates one
instance of this bean to the client. The EJB container uses management methods for creating and
destroying session beans.
Session beans are transient because they do not survive a server crash or a network failure. If,
after a crash, you instantiate a bean that had previously existed, the state of the previous instance
is not restored.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 4
Copyright 2009, Oracle. All rights reserved.
Stateless Versus Stateful Session Beans
There are two types of session beans:
Stateless session bean (SLSB):
Conversation is contained in a single method call.
Business process does not maintain client state.
Stateful session bean (SFSB):
Conversation may invoke many methods.
Business processes can span multiple method requests,
which may require maintaining a client state.
EJB container
Client 1
Client 2
Pool of SLSBs
EJB container
Client 1
Client 2
SFSBs
Stateless Versus Stateful Session Beans
Stateless session beans do not maintain client state between method calls. Thus, each invocation
of a stateless business method is independent of its previous invocation (for example, calculating
taxes or shipping charges). When the client requests a stateless bean instance, it can receive an
instance from the pool of instances or a new instance created by the container.
Stateful session beans maintain a conversational state across method invocations (for example,
an online shopping cart of a customer). When the customer starts online shopping, the
customers details are retrieved from the database. The same details are available for the other
methods that are invoked when the customer adds or removes items from the cart, places the
order, and so on.
Stateful session beans are transient because the state does not survive session termination,
system crash, or network failure. When a client requests a stateful session bean instance, the
client is assigned one stateful instance, and the state of the bean is maintained for that client.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 5
Copyright 2009, Oracle. All rights reserved.
Dependency Injection in EJB
The concept of dependency injection implies that it is:
A programming design pattern that enables you to inject
resources into a session bean at run time
Based on the principle of Inversion of Control (IOC)
An alternative to the JNDI implementation
EJB
container
EJB Injection
EJBs
JMS resources
Dependency Injection in EJB
Dependency injection (DI) is a programming design pattern that enables you to declare
component dependencies. It is based on the principle of Inversion of Control (IOC) that is used
to reduce dependencies between systems (loose coupling). DI enables one component to call
another component or resources through interfaces. The components are glued together by using
configuration, instead of code. The complexities of the service or resource instantiation,
initialization, sequencing, and lookup is handled by the EJB container.
DI enables you to declare the component dependencies at design time. The EJB container reads
the target EJB configuration, figures out what beans and resources the EJB requires, and injects
them into the target EJB at run time. For example, you can use the @EJB annotation in a session
bean to inject EJBs. Similarly, the @Resources annotation can be used to inject non-EJB
resources, such as a database connection.
The implementation of DI is totally opposite to that of implementing Java Naming and Directory
Interface (JNDI). In case of JNDI, it is the responsibility of the EJB to do a lookup and obtain a
reference of the resources. As a result, the component and resource name are hard-coded in the
EJB.
Note: Dependency injection is not limited to EJBs. You can use it in the Web tier (such as in
JSPs and servlets) and in the EJB tier with any EJB or JPA entity.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 6
Copyright 2009, Oracle. All rights reserved.
Life Cycle of a Stateless Session Bean
Ready
Creation
@PostConstruct
Does not
exist
Destruction
@PreDestroy
Method
Life Cycle of a Stateless Session Bean
Creation: Creation of an SLSB is initiated by the EJB container. The container typically creates
a pool of SLSBs that wait to service the requests of any clients. A stateless session bean is
created in the following sequence (as needed):
1. newInstance()
2. Dependency injection
3. PostConstruct callback
The @PostConstruct annotated method will be called by the container after the bean has
been constructed and before any business methods of the bean are executed. It is not a
mandatory feature. Similarly, a @PreDestroy annotated method will execute before the bean
instance is removed by the container. After this method has executed, the bean can be garbage
collected. This is also not mandatory.
Method: When a client invokes a method, the container chooses an SLSB from the pool and
invokes the requested method on it. Because SLSB conversations last for only one method call
and do not retain state, the container can return the SLSB to the available pool after the method
is complete. The bean will then wait in the pool until it is selected to fulfill another request.
Destruction: While managing the pool of SLSBs, the container may choose to destroy a bean
based on its age or to manage other resources (for example, memory limitations). At this point, a
predestroy callback is invoked if one is defined, and the SLSB is then destroyed.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 7
Copyright 2009, Oracle. All rights reserved.
Elements of a Stateless Session Bean
A stateless session bean contains:
Business interfaces, which contain the business method
definition
A bean class, which implements the business method
@Remote
@Local
Interfaces Bean class
String sayHello()
String sayHello()
{
return "Hello";
}
Remote
client
@Stateless
Local
client
JVM
String sayHello()
Elements of a Stateless Session Bean
Stateless session beans comprise the following elements:
Business interfaces: A stateless session business interface is a standard Java interface that
has a list of business method definitions, accessible by the client application. Business
interfaces can also use annotations:
- The @Remote annotation can be used to denote the remote business interface. You
use this interface to execute a session bean remotely.
- The @Local annotation can be used to denote the local business interface. You can
use this interface to execute a session bean locally. It is applicable if the client
application and the EJB container (executing the session bean) are running on the
same Java Virtual Machine (JVM).
It is possible that the application architecture requires both the remote and local interfaces.
For example, in an order processing application, the Web client (local client) can run in the
same JVM as the session bean. The Web client application can be used to submit new
orders. Simultaneously, the same session bean can be executed remotely by a rich client
application (remote client, executing on an end-user desktop machine) for entering data.
The business interfaces are generated at design time by tools such as Oracle JDeveloper,
Netbeans, or Eclipse, or generated at deployment time by the EJB container.
The bean class: A stateless session bean class is any standard Java class that has a class-
level annotation of @Stateless. The bean class implements the business methods that
are defined in the business interfaces.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 8
Copyright 2009, Oracle. All rights reserved.
Defining the Stateless Session Bean
// HelloWorldBean.java
package helloworld.ejb;
import javax.ejb.Stateless;
@Stateless(name="HelloWorld",
mappedName="HelloWorldSessionEJB")
public class HelloWorldBean implements HelloWorld
{
public String sayHello()
{
return "Hello World!";
}
}
1
3
4
5
2
Defining the Stateless Session Bean
Following are the code sections (numbered in the slide) for a HelloWorld SLSB:
1. Library: Stateless session beans import the javax.ejb.Stateless annotation class.
In general, EJBs import the javax.ejb.* class that corresponds to the type of bean
being created.
2. Annotations: The @Stateless annotation here identifies this as a stateless session bean.
The name parameter specifies the bean name. It forms a part of the JNDI lookup name,
and the mappedName parameter specifies the other part of the JNDI lookup name for the
bean (which means, EJB is published to JNDI with the name
HelloWorldSessionEJB#helloworld.ejb.HelloWorld). Annotations are
extensively used by EJB 3.0 to assist in generating or documenting code or in providing
services (for example, security) during run time. Annotations are discussed throughout this
course as you encounter them.
3. Bean class name: This is the name of the stateless session bean class.
4. Interface class name(s): This code section contains the names of the interfaces that are
defined for the bean class.
5. Bean methods: This section contains the code that defines the beans methods.
Note: Because EJB 3.0 beans are Plain Old Java Objects (POJOs) instead of extensions of
the generic javax.ejb.EnterpriseBean interface, the bean methods section is not
filled with no-op methods. Only methods that actually implement behavior are defined
here, making the code much more readable.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 9
Copyright 2009, Oracle. All rights reserved.
Analyzing the Remote and Local Interfaces
// HelloWorld.java
package helloworld.ejb;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
public String sayHello();
}
1
2
3
4
// HelloWorldLocal.java
package helloworld.ejb
import javax.ejb.Local;
@Local
public interface HelloWorldLocal {
public String sayHello();
}
1
2
3
4
Analyzing the Remote and Local Interfaces
The following code sections are highlighted in the slide:
1. Library: The remote interfaces import the javax.ejb.Remote interface.
2. Annotations: The @Remote annotation identifies this as a remote interface. Alternatively,
the bean class could have included the @Remote annotation and it could have been left out
here.
3. Interface class name: This code section contains the name of the interface for the bean
class. The client looks up this name to retrieve the interface for the bean.
4. Bean method declarations: This section includes declarations for the public methods of
the bean class.
A session bean, by default, defines a couple of interfaces: local interface and remote interface.
Each interface is meant for a different type of client. By default, the local interface is for a local
client that runs in the same JVM as the EJB 3.0 containerfor instance, a JSP page making a
call to an EJB, both executing in the same JVM for a Java EE server instance. When the client
looks up a bean stub via the local interface, the container returns a Java reference of the session
bean object. The method call invocations over Java references are very fast and efficient.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 10
Analyzing the Remote and Local Interfaces (continued)
The remote interface is for remote clients. When a client looks up the session bean stub via the
remote interface, the container returns a serialized stub object that implements the remote
interface. The remote stub knows how to pass remote procedure calls (RPCs) to the server, even
in a clustered environment. The remote interface may contain the same methods as the local
interface.
In terms of structure, local interfaces are identical to remote interfaces except that they import
the javax.ejb.Local interface and use the @Local annotation. The local and remote
interfaces may differ in terms of the methods that you want to expose to local or remote clients.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 11
Copyright 2009, Oracle. All rights reserved.
Creating a Test Client for the SLSB
// HelloWorldClient.java
import helloworld.ejb;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloWorldClient {
public static void main(String [] args)
throws NamingException {
try {
final Context context = new InitialContext();
HelloWorld helloWorld =
(HelloWorld)context.lookup(
"HelloWorldSessionEJB#helloworld.ejb.HelloWorld");
System.out.println(helloWorld.sayHello());
} catch (Exception ex) { ex.printStackTrace(); }
};
}
1
2
3
Creating a Test Client for the SLSB
The following code sections are highlighted in the slide:
1. Library: Import the package with the bean interface and the javax.naming.* libraries
for handling the JNDI lookup.
2. Bean lookup: The test client looks up the bean interface via JNDI.
3. Bean method execution: The test client invokes a bean interface method to test the SLSB.
Note: JDeveloper generates most of this code to simplify testing of your EJBs.
After the session bean is deployed into the EJB 3.0 container, a stub object is created and it is
registered in the servers JNDI registry. The client code obtains a stub of the bean from the JNDI
using its default JNDI name. You can make method calls against the stub object and the call is
transparently delegated to the bean instance in the EJB 3.0 container.
Local clients should use a beans local interface. A beans local interface provides much better
performance than its remote interface because the network is not needed for communication. In
addition, some EJB container services are available only to local clients (for example, EJB
TimerService).
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 12
Copyright 2009, Oracle. All rights reserved.
Life Cycle of a Stateful Session Bean
Ready
Creation
Passive
Activation Passivation
Does not
exist
Destruction
Ready (in TX)
Commit/
roll back
TX method
Method
TX method
Timeout
Life Cycle of a Stateful Session Bean
Creation: Unlike stateless session beans, creation of a stateful session bean (SFSB) is triggered
by a client. The execution will then proceed according to the following sequence of steps where
applicable:
1. When a client first invokes a method of an SFSB, the EJB container invokes
newInstance() to create the bean.
2. The container implements dependency injection.
3. The container execute the PostConstruct callback.
4. The container execute the Init() or ejbCreate() method.
Transactions: Stateful session beans can live across multiple method invocations and, therefore,
their life cycle includes a Ready (in Transaction) state and transaction-related callbacks as
follows:
1. TX Method - afterBegin(): After a transaction is started, this callback can be
triggered.
2. Commit - beforeCompletion() & afterCompletion(true): When
completing a transaction, these two callbacks are available.
3. Rollback - afterCompletion(false): This callback is available if the transaction
fails.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 13
Life Cycle of a Stateful Session Bean (continued)
Passivation and activation: Passivation and activation processes result in two additional life
cycle callback methods:
Passivation: Pre-passivate callback
Activation: Post-activate callback
The concepts of passivation and activation are discussed in detail in the following slide.
Destruction and timeout: Whenever a client invokes a method marked with the @Remove
annotation, the container destroys the bean after the execution of the method completes. Stateful
session beans are destroyed explicitly or by the container due to timeout (an extended period of
client inactivity). A predestroy callback is available for use before the destruction of an SLSB.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 14
Copyright 2009, Oracle. All rights reserved.
Passivation and Activation Concepts
Passivation and activation are stages in a session beans life
cycle controlled by the EJB container.
Passivation:
Serializes the bean state to secondary storage
Removes the instance from memory
Activation:
Restores the serialized beans state from secondary storage
Creates a new bean instance or uses a bean from the pool
(initialized with the restored state)
Passivation and Activation Concepts
Stateful session bean instances are assigned to individual clients because their current state
depends on earlier interactions with the client. If a clients bean instance is used by another
client, that SFSB may no longer have the proper state for the first client. To improve the
scalability of the system, the container can choose to passivate an SFSB instance, storing the
beans state in secondary storage and making that bean instance available for recycled use by
another client. In this way, the container can manage a larger number of clients with fewer
active SFSB instances in memory.
Passivation enables the container to preserve the conversational state of a bean instance by
serializing the bean and its state into a secondary storage and removing it from memory.
Activation occurs when a client invokes one of the methods of a passivated bean instance. The
preserved conversational state data is activated by deserializing the bean from secondary storage
and bringing it back into memory. The container can passivate a bean instance for reasons
controlled by the environment into which the bean is deployed (for example, limited available
memory, period of bean inactivity, and so on). However, the container will always activate a
passivated bean when a client calls one of its methods. During the passivation process, the
container serializes the bean state and saves it to temporary storage. However, some state
variables may hold resources (such as a data source connection) or violate rules for successful
passivation. These variables typically cannot be serialized and must be reinstated when the bean
instance is activated again.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 15
Copyright 2009, Oracle. All rights reserved.
Creating a Stateful Session Bean
To create a stateful session bean, perform the following steps:
1. Define the @Stateful class-level annotation in any
standard Java class.
2. Implement the business methods defined in the business
interfaces.
Creating a Stateful Session Bean
With EJB 3.0, you can develop a stateful session bean in nearly the same way that you would
develop a stateless session bean. The differences are highlighted in the next few slides as you
examine the sample code for a shopping-cart stateful session bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 16
Copyright 2009, Oracle. All rights reserved.
Defining the Stateful Session Bean
// CartBean.java
package cart.ejb;
import javax.ejb.Stateful;

@Stateful(name="Cart", mappedName="CartSessionEJB")
public class CartBean implements Cart {
private ArrayList items;
@PostConstruct
public void initialize() { items = new ArrayList(); }
public void addItem(String item) { items.add(item); }
public void removeItem(String item) {
items.remove(item); }
public Collection getItems() { return items; }
@PreDestroy
public void cleanup() {System.out.println("CLEAR!");}
@Remove
public void dumpCart() {System.out.println("BYE!");}
}
1
3
4
2
5
Defining the Stateful Session Bean
The following code sections are highlighted in the slide:
1. Library: Stateful session beans import the javax.ejb.Stateful annotation class. As
stated previously, EJBs import the javax.ejb.* package that corresponds to the type of
bean being created.
2. Annotations: The @Stateful annotation here identifies this as a stateful session bean.
3. @PostConstruct callback is used in this code example. Both stateless and stateful
session beans can have a PostConstruct callback to initialize complex attributes. The
use of the @PostConstruct annotation here indicates that initialize() is the
PostConstruct callback method.
4. @PreDestroy annotation is used as a callback notification to signal that the instance is
in the process of being removed by the container. The method annotated with
@PreDestroy is typically used to release resources that it has been holding.
5. @Remove annotation here indicates that the bean should be destroyed after the execution
of the dumpCart() method.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 17
Copyright 2009, Oracle. All rights reserved.
Analyzing the Remote and Local Interfaces
// Cart.java
package cart.ejb;
import javax.ejb.Remote;

@Remote
public interface Cart {
public void addItem(String item);
public void removeItem(String item);
public Collection getItems();
}
1
3
2
// CartLocal.java
package cart.ejb
import javax.ejb.Local;

@Local
public interface CartLocal {
1
2
Analyzing the Remote Interface and Local Interfaces
The following code sections are highlighted in the slide:
1. Library: Remote interfaces import the javax.ejb.Remote library, and local
interfaces import the javax.ejb.Local library.
2. Annotations: The @Remote and @Local annotations identify these as remote and local
interfaces, respectively.
3. Methods: Only those public methods that need to be exposed to a client are included in the
interfaces.
Note: There is really no substantive difference between developing the remote and local
interfaces of stateful and stateless session beans.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 18
Copyright 2009, Oracle. All rights reserved.
Creating a Test Client for the SFSB
// CartClient.java
import
public class CartClient {
public static void main(String[] args) throws
Exception {
Context context = new InitialContext();
Cart cart = (Cart)
context.lookup("CartSessionEJB#cart.ejb.Cart");
cart.addItem("Item1");
cart.addItem("Item2");
Collection items = cart.getItems();
for (Iterator i = items.iterator(); i.hasNext();) {
String item = (String) i.next();
System.out.println(" " + item);
}
}
}
Creating a Test Client for the SFSB
In the code in the slide, note that each execution of cart.addItem() modifies the state of
the carts items attribute. The return of cart.getItems() depends on the current state of the
bean as modified by the prior calls to cart.addItem().
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 19
Copyright 2009, Oracle. All rights reserved.
Calling a Stateless Bean from a Stateful Bean by
Implementing DI

@Stateful(name="Cart"", mappedName="CartSessionEJB")
public class CartBean implements Cart {
@EJB private HelloWorld obj;

// A demo method to call the sayHello() method defined


// in HelloWorld stateless session bean
public String callEJB() {
return obj.sayHello();
}

}
Calling a Stateless Bean from a Stateful Bean by Implementing DI
Dependency injection is the easiest way to access a session bean. You just have to use the @EJB
annotation to obtain a reference to an EJB that you want to inject in your managed class (classes
such as servlets, whose life cycle is managed by the container). You can then use the EJB object
as any other Java object in your managed class.
The @EJB annotation defines two optional attributes: name and beanInterface. The name
attribute specifies the JNDI name of the referenced EJB, and the businessInterface
attribute specifies the interface class (either remote or local bean interface). For example, the
@EJB annotation shown in the slide can also be written as @EJB(name="Cart",
beanInterface=Cart.class).
Note: Only managed classes (such as servlets, JSF managed beans, and EJBs) can use
dependency injection to access a session bean. Nonmanaged application components (such as
JSPs and helper classes) have to use JNDI lookup to obtain a reference to a session bean. For
example, in the preceding scenario, if you remove the dependency injection to call the
HelloWorld EJB, the JNDI lookup code to refer to the HelloWorld EJB inside the Cart
EJB should be:
...
InitialContext context = new InitialContext();
HelloWorld helloWorld =
(HelloWorld)context.lookup("java:comp/env/ejb/HelloWorld");
...
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 20
Copyright 2009, Oracle. All rights reserved.
Interceptor Methods and Classes
EJB 3.0 introduces the ability to create custom interceptor
methods and classes that are called before invoking the
methods they intercept. Interceptors:
Are available only for session beans (stateless and
stateful) and message-driven beans
Provide more granular control of a beans method
invocation flow
Can be used to implement custom transaction or security
processes instead of having those services provided by
the EJB container
Interceptor Methods and Classes
An interceptor catches invocation of a beans methods and executes its own methods prior to
executing the beans methods. The interceptors are typically used to implement common code.
For example, any enterprise application can use interceptors to implement common logging code
that is being used by all the EJBs. The interceptors can also be used to implement application
security to block the execution of a beans methods by users whose identities have not been
verified.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 21
Copyright 2009, Oracle. All rights reserved.
Interceptor Method
import javax.ejb.Stateless;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
@Stateless
public class HelloWorldBean implements HelloWorld
{
@AroundInvoke
public Object myInterceptor(InvocationContext ctx)
throws Exception {
System.out.println("Entering method: " +
ctx.getMethod().getName());
return ctx.proceed();
}
public void sayHello()
{ System.out.println("Hello World!"); }
}
1
2
3
4
Interceptor Method
A bean class can define an internal interceptor method to be used when any of its methods are
invoked. Only one interceptor method may be defined. Here are the relevant code sections:
1. Libraries: Include the javax.ejb.AroundInvoke and
javax.ejb.InvocationContext libraries
2. @AroundInvoke annotation: Identifies the interceptor method of the bean class
3. InvocationContext: Provides the environmental context for the call to the bean
4. proceed(): Allows execution flow to continue
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 22
Copyright 2009, Oracle. All rights reserved.
Interceptor Classes
External interceptor classes can be created to abstract the
behavior of interceptors and to define multiple interceptors for a
bean.
// Bean Class
@Stateless(name = ... , mappedName = ... )
@Interceptors(CheckUserInterceptor.class)
@Interceptors(LogActivity.class)
public class HelloWorldBean implements HelloWorld
{ }
// Interceptor Class
public class CheckUserInterceptor {
@AroundInvoke
public Object checkId(InvocationContext ctx) {}
}
Attaching the
interceptor class in
the bean class
Defining the interceptor
class and specifying the
interceptor method
Interceptor Classes
By using external interceptor classes, interceptor behavior can be abstracted and shared by
multiple beans.
Although there can be only one interceptor method for a bean, you can associate multiple
interceptor classes for a bean. In that case, the interceptors execute according to the order in
which they are declared. If there is a bean interceptor method as well, it executes last (just before
the invocation of the bean method).
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 23
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe session beans
Create stateless and stateful session beans by using
annotations
Describe the passivation and activation of stateful session
beans
Use interceptor methods and classes
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 24
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Creating a stateless session bean and implementing a
business method
Creating a test client to invoke the stateless session bean
Creating a stateful session bean that calls the stateless
session bean by implementing dependency injection
Creating a test client to invoke the stateful session bean
Creating an interceptor class that contains a method to
calculate the time to execute a beans method
Practice Overview: Creating Session Beans
In this practice, you learn to work with session beans by using JDeveloper. You create both the
stateless and stateful session beans and execute them by creating a sample test Java client. You
perform the following set of tasks in this practice:
Create a stateless session bean and implement a business method.
Create a test client to invoke the stateless session bean.
Create a stateful session bean that calls the stateless session bean by implementing
dependency injection. Here you expose a set of methods to store the clients information.
Create a test client to invoke the stateful session bean.
Create an external interceptor class that defines a method, which can be used to determine
the time that a method takes to execute. You can then use the interceptor class in any of the
session beans to find out the exact time a beans method take to execute.
Copyright 2009, Oracle. All rights reserved.
Developing the Persistence Layer with
JPA Entities
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Create a JPA entity
Select a primary key field
Perform object-relational mapping (ORM) by using
annotations
Map inheritance between entities
Map relationships between entities
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 3
Copyright 2009, Oracle. All rights reserved.
What Are JPA Entities?
A Java Persistence API (JPA) entity is:
A lightweight object that manages persistent data
Defined as a Plain Old Java Object (POJO) marked with
the @Entity annotation (no interfaces required)
Not required to implement interfaces
Mapped to a database by using annotations
@Entity
@Table(name="ORDERS")
Database
@Id
@Column(name="ORDID")
POJO
ORDERS
What Are JPA Entities?
The JPA is a part of the Java EE 5/EJB 3.0 specification that simplifies Java persistence to a
database. It provides an ORM approach that enables you to declaratively define how to map Java
objects to relational database tables. The JPA works both inside a Java EE 5 application server,
and outside an EJB container in a Java Standard Edition 5 (Java SE 5) application.
A JPA entity, or simply, entity:
Manages persistence data
Has fields that are mapped to columns in a relational database table by using annotations
Does not require that any interfaces be defined
Using JPA, you can designate any POJO class as a JPA entity by marking the POJO with the
@Entity annotation. An entity is not required to implement any interfaces. In an entity, all
fields are considered persistent unless annotated with the @Transient annotation.
Note: You need to implement the java.io.Serializable interface if the entity needs to
be passed by value through a remote interface.
The following annotations are used to map a POJO to a relational data construct:
@Table maps the object to a table.
@Column maps a field to a column (required if the field and column names are different).
@Id identifies primary key fields.
Note: Annotations for mapping relationships are discussed later in this lesson.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 4
Copyright 2009, Oracle. All rights reserved.
What Are JPA Entities?
@Entity
@Table(name="Orders")
public class Orders {
@Id
@Column(name="ORDERID")
int orderId;
@Column(name="ORDER_DATE
")
Date orderDate;

}
JPA entity
Database table
ORDER_DATE
ORDERID
Orders
What Are JPA Entities? (continued)
The slide displays a simple mapping between a JPA entity and a database table.
Note: If you do not specify the @Table annotations by default, the name of the generated table
is the name of the Java class. This also applies to the class variables. By default, the column
name is the name of the class variable if you do not specify the @Column annotation.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 5
Copyright 2009, Oracle. All rights reserved.
Domain Modeling with Entities
Entities support standard object-oriented domain modeling
techniques:
Inheritance
Encapsulation
Polymorphic relationships
Entities can be created with the new operator.
Domain Modeling with Entities
Domain modeling is the process of listing the entities in an enterprise application domain, and
defining the relationship between them. It displays the relationships among all major entities
within the system and usually identifies their important methods and attributes.
Entities are a metadata-driven POJO technology that does not require the implementation of any
predefined system interfaces or extension of a predefined system class. To create a domain
model with entities, code the domain model as POJOs and use annotations or XML to give the
persistence provider the following information:
What are the domain objectsusing the @Entity and @Embedded annotations
How to uniquely identify the domain objectsusing the @Id annotation
What are the relationships between the domain objectsusing the @OneToOne,
@OneToMany, and @ManyToMany annotations
How the domain objects are mapped to the database tablesusing annotations such as
@Table, @Column, or @JoinColumn
Entities also provide support for rich domainmodeling capabilities, such as inheritance and
polymorphism. It supports several inheritance mapping strategies: single table, joined subclass,
and table per class.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 6
Copyright 2009, Oracle. All rights reserved.
Managing Persistence of Entities
The life cycle of an entity is managed by using the
EntityManager interface, which is part of the JPA.
An entity can be created by using:
The new operator (creates detached instance)
The EntityManager Query API (synchronized with the
database)
An entity is inserted, updated, or deleted from a database
through the EntityManager API.
new
Entity Entities
EntityManager
Database
find()
Query
persist()
merge()
remove()
DML
Managing Persistence of Entities
Because an entity is a memory representation of persistent data, the storage and retrieval of an
entity and its life cycle are managed by using the JPA. This API provides the
EntityManager interface whose methods are used to find, insert, update, and remove entity
instances that are associated with a row in a database table. Entities can be created with:
The new operator and a constructor of the entity. In this case, the entity remains in a
detached state (not managed by the EntityManager). An entity can become attached to
the EntityManagers context when you pass the entity to the persist(), merge(), or
refresh() method.
The EntityManager and its Query API, which are part of the JPA
The EntityManager interface provides:
The find() method to retrieve a database row and instantiate an entity copy
Access to a Query API for creating and executing queries based on either of the following:
- Java Persistence Query Language (JPQL)
- Native SQL statements
Methods to perform persistent operations, as in the following examples:
- persist() to mark a new instance for insertion into the database
- merge() to integrate (either insert or update) an instance into the database
- remove() to remove an instance from the database
Note: The data manipulation language (DML) statements executed on the data store are
performed by the EntityManager API.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 7
Copyright 2009, Oracle. All rights reserved.
Declaring an Entity
Declare a new Java class with a no-arg constructor.
Annotate it with @Entity.
Add fields corresponding to each database column:
Add setter and getter methods.
Use the @Id annotation on the primary key getter method.
@Entity // annotation
public class Customer implements java.io.Serializable {
private int customerID;
private String name;
public Customer() { ... } // no-arg constructor
@Id // annotation
public int getCustomerID() { ... }
public void setCustomerID(int id) { ... }
public String getName() { ... }
public void setName(String n) { ... }
}
Declaring an Entity
As discussed earlier, an entity is a POJO marked with the Entity annotation.
The POJO generally follows JavaBeans naming conventions. To create an entity, perform the
following steps:
1. Declare a standard Java class. The class must have a no-arg constructor, as required by the
EJB 3.0 specifications. It may have additional constructors if desired.
2. Insert the @Entity annotation before the public modifier of the class definition.
3. Add the entity fields that represent the persistent state of the bean, where each field is
associated with a column in the database table.
4. Define the public getter and setter methods for fields in the class.
5. Insert the @Id annotation before at least one getter method whose field is used as a way to
uniquely identify the instance. This becomes the primary key field.
Note: The EJB 3.0 specification requires that an entity have a primary key.
Without @Table and @Column annotations being specified, the following default entity
mappings are applied:
The class name is mapped (as is) to the database table name. It is case-sensitive.
The field names are mapped (as is) to the column names.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 8
Copyright 2009, Oracle. All rights reserved.
Mapping Entities
Mapping of an entity to a database table is performed:
By default
Explicitly using annotations or in an XML deployment
descriptor
@Entity
@Table(name="CUSTOMERS")
public class Customer implements java.io.Serializable {
@Id
@Column(name="CUSTID")
private int customerID;
private String name;

public int getCustomerID() { ... }
public void setCustomerID(int id) { ... }
public String getName() { ... }
public void setName(String n) { ... }
}
NAME
CUSTID (PK)
CUSTOMERS
Mapping Entities
Mapping an entity to a database table is performed:
By default:
- The class name is mapped as the table name.
- The field names are mapped as the column names.
Explicitly (overriding default mapping) by using:
- The @Table annotation to specify the corresponding database table name
- The @Id annotation to specify the entitys primary key, or identifier
- The @Column annotation to specify the corresponding column name
The example shows the Customer class being mapped to the CUSTOMERS table by setting the
name parameter in the @Table annotation. The customerID field is mapped to the CUSTID
column through the use of the @Column annotation that appears before the getCustomerID()
method declaration. The name parameter of the @Column annotation specifies the column name.
The @Id annotation indicates that it is a primary key field.
An entity can be mapped to more than one table sharing a relationship. The primary table is
mapped using the @Table annotation and the secondary table is mapped using the
@SecondaryTable annotation. The primary and the secondary tables must have the same
primary key.
Note: The Transient annotation can be used for a property or field of the entity bean class that
is not persistent.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 9
Copyright 2009, Oracle. All rights reserved.
Quiz
An entity is a lightweight persistence domain object that
represents:
1. A relational database
2. A table in a relational database
3. Entity beans in EJB 2.x specification
4. Persistence data in a file
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 10
Copyright 2009, Oracle. All rights reserved.
Mapping Inheritance
Entities can implement inheritance relationships.
You can use three inheritance mapping strategies to map
entity inheritance to database tables:
Single-table strategy
Joined-tables strategy
Table-per-class strategy
Use the @Inheritance annotation.
Mapping Inheritance
You can map object-oriented inheritance into relational databases by implementing inheritance
relationship between different entities. You can use the following inheritance mapping strategies
supported by JPA.
Single-table strategy: The single-table strategy specifies that there should be one and only
one table per class hierarchy. This table should have a column for each unique field for
every class in the hierarchy. The table must have an additional column (also called a
discriminator column) that identifies the objects type. The @DiscriminatorColumn
annotation maps to a specific database column whose values are used to differentiate classes
in an inheritance hierarchy by type. The single-table strategy is the optimal strategy for
performance as the persistence engine does not have to do any complex joins when loading
such an object.
Joined-tables strategy: In joined-tables strategy, each entity in the hierarchy maps to its
own dedicated table (one-to-one relationship). The specific table maps the fields declared
on the respective entity. The parent entity in the hierarchy is mapped to a base table. All the
other child entities in the hierarchy are mapped to separate tables that join the base table.
From a performance perspective, the joined-table strategy is worse than the single-table
strategy because it requires the joining of multiple tables for polymorphic queries.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 11
Mapping Inheritance (continued)
Table-per-class strategy: In table-per-class strategy, both the superclass and the subclasses
are stored in their own tables and no relationship exists between any of the tables. The
greatest disadvantage of using this mapping type is that it does not provide good support for
polymorphic queries because each subclass is mapped to its own table.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 12
Copyright 2009, Oracle. All rights reserved.
Single-Table Strategy
//Parent entity
@Entity
@Table(name="USERS")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="USER_TYPE", ... )
public class user implements java.io.Serializable { ... }
//Child entity
@Entity
@DiscriminatorValue(value="C")
public class customer extends user ...
//Child entity
@Entity
@DiscriminatorValue(value="S")
public class supplier extends user ...
USERS table
3
4
2
1
Single-Table Strategy
The slide displays the single-table inheritance mappings strategy. The USERS table contains
data common to all the users, including the customer-specific data and supplier-specific data.
The first and second records in the USERS table contain the customer information, whereas the
third record contains the supplier information. This segregation of the customer data and the
supplier data is being indicated by the USER_TYPE column (of the USERS table) and, therefore,
is the discriminator column. The "C" and "S" values in the USER_TYPE discriminator column
indicate the customer-specific record and the supplier-specific record, respectively.
The slide also displays the inheritance mapping for the user, customer, and supplier entities. The
annotations are described as follows:
1. The @Inheritance annotation specifies the strategy to be
InheritanceType.SINGLE_TABLE on the user entity.
Note: The @Table annotation specifies the name of the single table used for inheritance
mapping.
2. The @DiscriminatorColumn annotation specifies the details of the discriminator
column. The name element specifies the name of the discriminator, which is
USER_TYPE.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 13
Single-Table Strategy (continued)
3. The customer class (subclass of user) specifies the discriminator value to be "C", by
using the @DiscriminatorValue annotation. That is, when the persistence provider
saves a customer object into the USERS table, it sets the value of the USER_TYPE
column to "C".
4. The supplier class (subclass of user) specifies the discriminator value to be "S", by
using the @DiscriminatorValue annotation.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 14
Copyright 2009, Oracle. All rights reserved.
Joined-Tables Strategy
//Parent entity
@Entity
@Table(name="USERS")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="USER_TYPE", ... )
public class user ...
//Child entity
@Entity
@Table(name="CUSTOMER")
@DiscriminatorValue(value="C")
@PrimaryKeyJoinColumn(name="UID")
public class customer extends user ...
//Child entity
@Entity
@Table(name="SUPPLIER")
@DiscriminatorValue(value="S")
@PrimaryKeyJoinColumn(name="UID")
public class supplier extends user ...
USERS table
CUSTOMER table
SUPPLIER table
1
2
3
Joined-Tables Strategy
The slide displays the joined-tables inheritance mappings strategy. In this type of strategy, the
parent of the hierarchy contains only columns common to its children. The USERS table
contains columns (such as the UID column) that are common to all the user types. The child
tables in the hierarchy contain columns specific to the entity types. For example, the C_RATING
column is specific to the CUSTOMER table.
The parent/child object-oriented hierarchy chain is implemented by using one-to-one
relationships. For example, the USERS and CUSTOMERS tables are related through the UID
foreign key in the CUSTOMER table pointing to the primary key of the USERS table. The
discriminator column is still used in the parent table to differentiate the users type in the
hierarchy.
The inheritance mapping for the user, customer, and supplier entities are basically
similar to that of the single-table strategy. Here, you need to add some additional annotations to
identify the tables mapped to the child entities, and also their respective primary keys. The
annotations are described as follows:
1. The @Inheritance annotation specifies the strategy to be
InheritanceType.JOINED on the user entity.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 15
Joined-Tables Strategy (continued)
2. The @Table annotation specifies the table name, CUSTOMER, mapped to the customer
entity. The @PrimaryKeyJoinColumn annotation specifies the foreign key column,
UID, on the CUSTOMER table that implements the one-to-one relationship between the
USERS and CUSTOMER tables.
3. The @Table annotation specifies the table name, SUPPLIER, mapped to the supplier
entity. The @PrimaryKeyJoinColumn annotation specifies the foreign key column,
UID, on the SUPPLIER table that implements the one-to-one relationship between the
USERS and SUPPLIER tables.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 16
Copyright 2009, Oracle. All rights reserved.
Specifying Entity Identity
The identity of an entity can be specified by using:
The @Id annotation
The @IdClass annotation
The @EmbeddedId annotation
Specifying Entity Identity
Every entity in a domain model should be uniquely identifiable and, therefore, must have a
primary key. The identity of an entity can be specified by using the following annotations:
@Id annotation: The @Id annotation can be used to mark a field or property as identity
for an entity. The only consideration in this case is that it works only for identities with just
one field or property. If you have to use more than one property or field (also known as a
composite key) to uniquely identify an entity, you can do it by implementing either the
@IdClass or the @EmbeddedId annotation.
@IdClass annotation: The @IdClass annotation enables you to specify a composite
primary key class that is mapped to multiple fields or properties of the entity. The names of
the fields or properties in the primary key class must correspond to the primary key fields
or properties of the entity, and their types must also be the same.
@EmbeddedID annotation: The @EmbeddedID annotation is applied to a persistent
field or property of an entity class or mapped superclass to denote a composite primary
key. The composite primary key is defined in an embeddable class in the entity class. The
embeddable class must be annotated as @Embeddable.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 17
Copyright 2009, Oracle. All rights reserved.
Generating Primary Key Values
Use the @GeneratedValue annotation.
@Entity
@Table(name="CUSTOMERS")
public class Customer implements java.io.Serializable {
@Id
@SequenceGenerator(name = "CUSTOMER_SEQ_GEN",
sequenceName = "CUSTOMER_SEQ", initialValue = 1,
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "CUSTOMER_SEQ_GEN")
@Column(name = "CUSTID", nullable = false)
private Long customerId;
...
public int getCustomerID() { ... }
...
}
1
2
3
4
Generating Primary Key Values
A primary key for an entity (which is usually annotated with the @Id annotation) can be given a
value manually, or you can use the underlying persistence framework to automatically generate
the primary key values. The @GeneratedValue annotation tells the persistence framework to
autopopulate the column with the specified sequence generator.
Consider the code in the slide. Because customerID is going to be the primary key for the
Customer entity, you have to mark the field with the @GeneratedValue annotation. The
annotation delegates the burden of creating values from developers to the persistence engine.
The types of primary key valuegeneration strategies that can be specified in the
@GeneratedValue annotation are as follows:
TABLE indicates that the container assigns values by using an underlying database table.
SEQUENCE and IDENTITY specify the use of a database sequence or identity column,
respectively.
AUTO indicates that the JPA persistence provider should pick an appropriate strategy for
the particular database.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 18
Generating Primary Key Values (continued)
The code in the slide depicts the following:
1. The @ID annotation marks the customerId property as the primary key for the
Customer entity.
2. The @SequenceGenerator annotation creates a sequence generator named
CUSTOMER_SEQ_GEN that references a CUSTOMER_SEQ database sequence object. The
initial value of the sequence is 1, and is being incremented by 1 each time that a value is
generated.
3. The @GeneratedValue annotation specifies a primary key value generator based on a
primary key identity column.
4. The customerId property of the Customer entity is mapped to the CUSTID column
of the CUSTOMERS table, being specified as the primary key.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 19
Copyright 2009, Oracle. All rights reserved.
Mapping Relationships Between Entities
Annotations for entity relationships:
@OneToOne
@ManyToOne
@OneToMany
@ManyToMany
Customer Address
Order Customer
Customer
Order
Customer
Supplier
Mapping Relationships Between Entities
The following annotations are used to specify relationships between entities:
The @OneToOne annotation defines a single-valued association to another entity.
Example: A Customer object may be associated with one and only one Address
object.
The @ManyToOne annotation defines a single-valued association to another entity that
has many-to-one multiplicity. Example: Many Order can be placed by one Customer.
A @OneToMany annotation defines a many-valued association with one-to-many
multiplicity. Example: One Customer can place many Order.
A @ManyToMany annotation defines a many-valued association with many-to-many
multiplicity. A many-to-many association has two sides: an owning side and a nonowning
(or inverse) side. Example: Many Customer can buy products from many Supplier.
Relationships can be unidirectional or bidirectional. Bidirectional relationships, which have an
owning side and an inverse side, are persisted based on references held by the owning side of the
relationship. Unidirectional relationships have only an owning side.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 20
Mapping Relationships Between Entities (continued)
The developer must maintain consistent in-memory entity references on both sides of the
relationship.
Rules that apply to bidirectional relationship:
The inverse side refers to its owning side by using the mappedBy element of the
OneToOne, OneToMany, or ManyToMany annotation. The mappedBy element
designates the relationships owning field.
The mappedBy element cannot be specified on the ManyToOne annotation and must be
on the inverse side of a OneToMany or OneToOne relationship.
In OneToOne relationships, the owning side contains the foreign key.
In ManyToMany relationships, either side can be the owning side.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 21
Copyright 2009, Oracle. All rights reserved.
STREET
ADDRESS_ID (FK)
Implementing One-to-One Relationships
You can map one-to-one relationships by using the
@OneToOne annotation.
Depending on the foreign key location, the relationship can
be implemented by using:
The @JoinColumn annotation
The @PrimaryKeyJoinColumn annotation
CUST_NAME
CUSTID (PK)
CUSTOMER
HOUSE_NO
ADDRESS_ID (PK)
ADDRESS
Address Customer
Mapped to Mapped to
Implementing One-to-One Relationships
The one-to-one relationships are mapped by using the primary key and foreign key association.
Depending on where the foreign key resides (either in the parent table or child table), the
relationship can be implemented by using the @JoinColumn annotation or the
@PrimaryKeyJoinColumn annotation.
@JoinColumn annotation: You can use the @JoinColumn annotation to implement a
one-to-one relationship between two tables if the underlying table for the referencing entity
is the one containing the foreign key to the table to which the referenced child entity is
mapped. For example, consider the CUSTOMER table to be the parent table and the
ADDRESS table to be the child table. You can use the @JoinColumn annotation to map
these two tables if the CUSTOMER table contains a foreign key column that is the primary
key column in the ADDRESS table.
@PrimaryKeyJoinColumn annotation: You can use the
@PrimaryKeyJoinColumn annotation to implement a one-to-one relationship between
two tables if the foreign key reference exists in the table to which the referenced entity is
mapped. For example, consider that table A and table B share the same primary key, and
the primary key of table B is also a foreign key referencing the primary key of table A.
Such associations are mapped by using the @PrimaryKeyJoinColumn annotation.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 22
Copyright 2009, Oracle. All rights reserved.
Implementing One-to-One Relationships
Example: Mapping a one-to one relationship between the
Customer class and the Address class by using the
@JoinColumn annotation
// In the Customer class:
@Table(name="CUSTOMER")
...
@OneToOne
@JoinColumn(name="MAILING_ADDRESS_REF",
referencedColumnName="ADDRESS_PK")
protected Address address;
...
// In the Address class:
@Table(name="ADDRESS")
...
@column(name="ADDRESS_PK")
...
Implementing One-to-One Relationships (continued)
The slide shows a code example of implementing a one-to-one relationship between the
Customer and Address entities by using the @JoinColumn annotation. The CUSTOMER table
contains a foreign key named MAILING_ADDRESS_REF that refers to the ADDRESS tables
ADDRESS_PK primary key. The @JoinColumn annotations name element refers to the name of
the foreign key in the CUSTOMER table. The referencedColumnName element specifies the
name of the primary key in the ADDRESS table that the MAILING_ADDRESS_REF foreign key
(located in the CUSTOMER table) refers to. The relationship is defined in the
Customer.address field in the Customer entity.
In case of a bidirectional one-to-one relationship, the entity in the inverse side of the relationship
contains the mappedBy element in the @OneToOne annotation. For example, to make the
relationship between the Customer entity and the Address entity bidirectional, add the
following code to the Address entity:
...
@OneToOne(mappedBy="address")
protected Customer customer;
...
Note: You do not have to redundantly specify the @JoinColumn annotation in the
Address.customer field in the Address entity. Moreover, if you want to make the
relationship unidirectional in the opposite direction, move the @JoinColumn annotation from
Customer.address into the Address.customer field.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 23
Copyright 2009, Oracle. All rights reserved.
Implementing Many-to-One Relationships
Mapping a many-to-one relationship:
Using the @ManyToOne annotation
Defines a single-valued association
Example: Mapping an Orders class to a Customer
// In the Order class
@Entity
@Table(name="ORDER")
public class Order ... {
...
@ManyToOne
@JoinColumn(name="ORDERS_CUSTID_REF",
referenceColumnName="CUSTID_PK", updatable=false)
protected Customer customer;
...
}
Implementing Many-to-One Relationships
The @ManyToOne annotation defines a single-valued association to another entity that has many-to-one
multiplicity. The Order entity shares a many-to-one relationship with the Customer entity. The name
element of the @JoinColumn annotation refers to the foreign key in the ORDER table. The
referencedColumnName element specifies the primary key in the CUSTOMER table (which is
mapped to the Customer entity) that the foreign key in the ORDER table refers to. The relationship is
defined in the Order.customer field in the Order entity.
Note: The @OnetoOne, @ManyToOne, @OneToMany, and @ManyToMany annotations also provide
the following optional attributes:
targetName identifies the fully qualified class name of the associated entity. It is optional because
the name of the associated target entity can usually be inferred from the type of the object being
referenced.
cascade defines a comma-separated set of operations propagated to the associated entity. The
types of cascade operations are:
- PERSIST: Causes associated entities to be inserted
- MERGE: Causes associated entities to be merged (inserted or updated)
- REMOVE: Causes associated entities to be deleted
- REFRESH: Causes associated entities to be refreshed
- ALL: Includes all the four operations
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 24
Implementing Many-to-One Relationships (continued)
Note: When true, the nullable attribute of @Column or @JoinColumn indicates that the field
allows database NULL values to be inserted; otherwise, a NULL is not allowed. When the updatable
attribute is false for the @Column or @JoinColumn annotations, the persistence provider cannot
modify the column value; otherwise, it can be changed.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 25
Copyright 2009, Oracle. All rights reserved.
Implementing One-to-Many Relationships
Mapping a one-to-many relationship by using the @OneToMany
annotation.
//In the Customer class:
@Table(name="CUSTOMER")
...
@OneToMany(mappedBy="customer")
protected Set<Order> order;
...
// In the Order class:
@Table(name="ORDER")
...
@ManyToOne
@JoinColumn(name="ORDERS_CUSTID_REF",
referenceColumnName="CUSTID_PK", updatable=false)
protected Customer customer;
...
Implementing One-to-Many Relationships
A @OneToMany annotation defines a many-valued association with one-to-many multiplicity.
The Set<Order> type defines a generic collection of Order objects. By using generic
collection types, the JPA persistence provider determines the entity type at the other end of the
relationship. As a result, all that is required to resolve the mapping for the @OneToMany side is
the field or property specified on that entity, which in this case is customer.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 26
Copyright 2009, Oracle. All rights reserved.
Implementing Many-to-Many Relationships
Mapping a many-to-many relationship by using the
@ManyToMany annotation.
// In the Customer class:
...
@ManyToMany(cascade=PERSIST)
@JoinTable(name="CUST_SUP",
joinColumns=
@JoinColumn(name="CUST_ID",referencedColumnName="CID"),
inverseJoinColumns=
@JoinColumn(name="SUP_ID", referencedColumnName="SID"))
protected Set<Supplier> suppliers;
...
// In the Supplier class:
...
@ManyToMany(cascade=PERSIST, mappedBy="suppliers")
protected Set<Customer> customers;
...
Implementing Many-to-Many Relationships
A @ManyToMany annotation defines a many-valued association with many-to-many
multiplicity. A customer can purchase goods from multiple suppliers, and a supplier can sell
goods to multiple customers. This type of mapping requires an association or join tables that
holds references back (foreign key) to the primary keys of the entities at either end of the
relationship. For example, the CUST_SUP association table (specified by the name attribute of
the @JoinTable annotation) has two columns: CUST_ID is a reference column pointing back
to the CID primary key column in the CUSTOMER table, and SUP_ID is a reference column
pointing to the SID primary key column in the SUPPLIER table.
The use of the mappedBy element in the @ManyToMany annotation allows the mapping
information contained in the @JoinTable annotation to be shared by both the relationship
fields.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 27
Copyright 2009, Oracle. All rights reserved.
Quiz
In a unidirectional relationship, both the entities have a
relationship field or property that refers each other.
1. True
2. False
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 28
Copyright 2009, Oracle. All rights reserved.
Managing Entities
Entities are managed by using the EntityManager API.
EntityManager performs the following tasks for the
entities:
Implements the object-relational mapping between Java
objects and database
Performs the CRUD operations for the entities
Manages the life cycle of the entities
Manages transactions
Managing Entities
The JPA EntityManager interface manages entities in terms of actually providing
persistence services. The entities do not persist themselves. The EntityManager interface
reads the ORM metadata for an entity and performs persistence operation. The
EntityManager knows how to create, read, update, and delete (CRUD) entities from the
database. In addition, you can use EntityManager to manage the life cycle, performance
tuning, caching, and transactions for the entities.
You learn more about the EntityManager interface in the lesson titled Manipulating JPA
Entities with the EntityManager API.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 29
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Create an JPA entity
Select a primary key field
Perform object relational mapping by using annotations
Map inheritance between entities
Map relationships between entities
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 30
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practice covers the following topics:
Creating a simple entity bean by coding the bean
Using the JDeveloper wizards to create a set of entity
beans
Creating and managing a session bean that provides client
access to the entity beans
Creating a test client to invoke the session bean
Copyright 2009, Oracle. All rights reserved.
Manipulating JPA Entities with the
EntityManager API
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Declare an EntityManager reference with the
@PersistenceContext annotation
Look up an EntityManager reference by using
dependency injection
Use the EntityManager API to:
Find an entity by its primary key
Insert a new entity
Modify an existing entity
Delete an entity
Execute dynamic queries with the Query API
Write simple JPQL queries
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 3
Copyright 2009, Oracle. All rights reserved.
What Is EntityManager?
EntityManager:
Is an interface defined in JPA
Is a standard API for performing CRUD operations for
entities
Acts as a bridge between the object-oriented and the
relational models
JPA
EntityManager Entities
manages
What Is EntityManager?
EntityManager is an interface that is defined as a part of the EJB 3.0 Java Persistence API
(JPA) specification. It specifies standard APIs for managing the life cycle of the entities, and
also for performing a create, read, update, and delete (CRUD) operation on the entities. The
EntityManager acts as a bridge between the object-oriented and the relational worlds. It
interprets the object-relational mapping (ORM) specified for an entity and saves the entity in the
database.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 4
Copyright 2009, Oracle. All rights reserved.
Application entity classes
(Persistence unit)
Persistence
context
What Is EntityManager?
EntityManager is:
Associated with a persistence context
An object that manages a set of entities defined by a
persistence unit
EntityManager
Database
manages
What Is EntityManager? (continued)
EntityManager is also an instance that is associated with a persistence context. A
persistence context is defined as a set of managed entity instances, each of which has a unique
persistent identity. The persistence context shown in the diagram is the set of entity instances
associated with a row in a database. The EntityManager interface provides methods that
manage entity instances and their life cycles within the persistence context. The
EntityManager API is used to create and remove persistent entity instances to find entities
by their primary key and to query entities.
By default, the lifetime of the persistence context corresponds to the life of a transaction. An
extended persistence context can be extended beyond that of a single transaction. The
EntityManager API assumes that the mapped database is accessed using read-committed
isolationthat is, it uses an optimistic locking strategy.
A persistence unit defines a set of:
Entities that can be managed by a specific EntityManager instance
Related and grouped application classes that are mapped to a single database
An entity has a persistence identity when it has been assigned a unique identifier value, such as
the primary key. The persistence identity is used to ensure that an entity is unique.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 5
Copyright 2009, Oracle. All rights reserved.
Persistence context
Managing an Entity Life Cycle
with EntityManager
New
Managed
Detached
Removed
EntityManager
Database
= Persistent identity
1
4
persist()
merge()
remove()
INSERT
DELETE
flush()
3
merge()
UPDATE
SELECT
2
find()
flush()
Managing an Entity Life Cycle with EntityManager
The diagram shows the life cycle of an entity as managed by the EntityManager API. The
diagram does not illustrate the handling of related entities or error scenarios. The numbers
represent state changes of entities while the methods of the
javax.persistence.EntityManager interface are executed on the entity.
1. A new entity does not have a persistent identity and is not associated with a persistence
context until either a persist() or merge() operation is executed by the
EntityManager. In either case, a database INSERT statement is executed, the entity
enters the managed state, and it becomes known as a managed entity.
2. A managed entity has a persistence context and identity that is initialized when the find()
method is called. A find() method executes a SELECT statement based on the primary
key and results in a new instance of an entity that forms a part of the managed persistence
context. On a managed entity, flush() causes an UPDATE, and a merge() is ignored.
3. A detached entity is an object resulting from a transaction commit or rollback scenario, or
a serialized instance passed as a parameter from a separate application tier. A detached
entity is not associated with a persistence context until a merge() is performed. Then the
entity becomes managed and an UPDATE is applied to the associated database row.
4. A removed entity has a persistence context and identity, and is marked for DELETE when
the remove() method is executed. A flush() removes the entity from the database.
Note: Not all the methods from the EntityManager interface are shown.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 6
Managing an Entity Life Cycle with EntityManager (continued)
A detached entity instance continues to live outside the persistence context in which it was
persisted or retrieved. Therefore, the state of the detached entity may not synchronize with the
database.
An application can access the available state of the detached entity instance after the persistence
context ends, provided that the available state is a persistent field that:
Is not annotated with fetch=LAZY
Was accessed by the application
If the persistent field is an association, its available state can be accessed only if the associated
instance is available.
Note: The EntityManager contains() method can be used to check whether an entity
instance is managed in the current persistence context. The contains() method returns:
TRUE if the entity was retrieved and not removed or detached, or if the entity is new and
persisted
FALSE if the entity is detached or removed, or if it is new and not persisted
Entity Life-Cycle Callback Methods
Each entity may implement various callback methods during the management of an instances
life cycle. A method designated as a life-cycle callback method receives notification of events
that affect the entity during its life cycle. A life-cycle callback method may be defined in either
the entity class or entity listener class. Any entity may have any number of listener classes
defined. A callback method defined in the entity class has the following signature:
void method-name()
A callback method defined in the entity listener class has the following signature:
void method-name(Object obj)
Here, the Object argument is the entity instance for which the callback is invoked.
Callback methods can be public, private, protected, or at the package level, but they
cannot be static or final. The Java Persistence API specification defines the following
annotations to designate a life-cycle event callback method:
PrePersist is invoked before the EntityManager persist() method is
executed.
PostPersist is invoked after the entity has been made persistent.
PreRemove is invoked before the EntityManager remove() method is executed.
PostRemove is invoked after the entity has been removed.
PreUpdate is executed before the database update operation occurs.
PostUpdate is executed after the database update operation occurs.
Note: PreUpdate and PostUpdate methods are invoked before or after (respectively)
when the entity state is updated, or when the changes are flushed to the database, which
may occur at the end of a transaction.
PostLoad is invoked after the entity has been loaded into the current persistence context
or after the refresh operation (before a query result is accessed or an association is
traversed).
Note: Life-cycle methods are also invoked on operations with appropriate cascade-type
operations on associated entities.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 7
Copyright 2009, Oracle. All rights reserved.
Accessing an EntityManager Instance
in an Application
Container-managed EntityManager instances:
Are implemented inside a Java EE container
Use the @PersistenceContext annotation
Are obtained in an application through dependency injection
or JNDI lookup
Application-managed EntityManager instances:
Are implemented outside a Java EE container
Are obtainable by using the EntityManagerFactory
interface
Accessing an EntityManager Instance in an Application
The most common and widely used EntityManager in a Java EE environment is the
container-managed EntityManager. In this mode, all the EntityManager instances are
injected into the applications by using the @PersistenceContext annotation. The Java EE
container manages the task of looking up, opening, and closing the EntityManager, and is
also responsible for managing the transaction boundaries. Therefore, a container-managed
EntityManager must implement the Java Transaction API (JTA) transactions. You can
obtain a container-managed EntityManager in an application through dependency injection
or through JNDI lookup.
The application-managed EntityManager enables you to control every aspect of
EntityManagers life cycle in the application code. In this mode, the EntityManager is
retrieved through the EntityManagerFactory API. Because application-managed
EntityManager is implemented outside a Java EE container, the transactions in application-
managed EntityManager is controlled through the EntityTransaction API.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 8
Copyright 2009, Oracle. All rights reserved.
Creating a Container-Managed EntityManager
Instance
A session bean using container injection:
@Stateless
public class CustomerBean {
@PersistenceContext(unitName="Model")
private EntityManager em;
...
public void createCustomer() {
final Customer cust = new Customer();
cust.setName("Valli Pataballa");
...
em.persist(cust);
}
...
}
Creating a Container-Managed EntityManager Instance
The slide shows an example of a session bean acquiring an EntityManager instance through
container injection (dependency injection) by implementing the @PersistenceContext
annotation. In this case, the EntityManager instance is bound to the Model persistence unit,
which includes the Customer entity. If a Java EE module has a single persistence unit,
specifying the unitName is redundant. The EntityManager is used to persist a new
Customer instance by invoking the persist() method.
Note: Persistence units cannot be set up using code. You need to configure them by using the
persistence.xml deployment descriptor.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 9
Copyright 2009, Oracle. All rights reserved.
Creating an Application-Managed
EntityManager Instance
A Java SE application using an EntityManagerFactory
API:
public class CustomerApp {
public static void main(String args[]) {
final EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Model");
final EntityManager em =
emf.createEntityManager();
final Customer cust = new Customer()
cust.setName("Ron Howard");
...
em.persist();
}
}
Creating an Application-Managed EntityManager Instance
The slide shows an example of how a Java SE application obtains an EntityManager
instance. In this case, an EntityManagerFactory instance is created and bound to the
Model persistence unit (defined in the persistence.xml deployment descriptor), which
includes the Customer entity. The createEntityManagerFactory() method of the
javax.persistence.Persistence object is essentially a programmatic substitute for
the @PersistenceUnit annotation that is used to inject an instance of
EntityManagerFactory in a Java EE environment. An EntityManager instance is then
created from that factory and is used to persist a new Customer instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 10
Copyright 2009, Oracle. All rights reserved.
Specifying Database Operations with
the EntityManager API
The EntityManager API provides the following methods that
map to CRUD database operations:
find(classname,pk)
SELECT
createQuery()
createNamedQuery()
persist(o)
INSERT DELETE
remove(o)
Specifying Database Operations with the EntityManager API
The EntityManager API provides the following methods that map to CRUD database
operations:
persist() maps to an INSERT (create) operation.
find() maps to a SELECT (read) operation.
remove() maps to the DELETE operation.
merge() attaches an entity instance to the EntityManagers persistence context,
making the instance managed. You can update an entity by using the entitys public API to
modify its persistent state, or by using an update query. In both the cases, the actual
database update happens when the current transaction context commits. Alternatively, you
can call the flush() method to persist entity state before the current transaction context
commits.
Note: The Java Persistence API specification assumes the use of optimistic locking, where the
databases to which persistence components are mapped are accessed by implementations using
read-committed isolation. The specification does not define database isolation levels.
Note: The EntityManager interface provides additional methods, known as the Query API,
for finding entities:
createQuery() creates a Query object for executing a Java Persistence Query
Language (JPQL) statement.
createNamedQuery() creates a Query object for executing a named JPQL or native
query.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 11
Copyright 2009, Oracle. All rights reserved.
Commonly Used Methods in the
EntityManager Interface
Method signature of the most commonly used methods of the
EntityManager interface:
public void persist(Object entity);
public <T> T merge(T entity);
public void remove(Object entity);
public <T> T find(class<T> entityClass, Object
primaryKey);
public void flush();
public void refresh(Object entity);
public void clear();
public Query createQuery (String jpqlString);
public Query createNamedQuery (String name);
Commonly Used Methods in the EntityManager Interface
The slide shows the method signature of the most commonly used methods of the
EntityManager interface.
persist()saves an entity instance into the database, and also makes the entity managed.
It takes an entity object as a parameter.
merge()merges the state of the given entity into the EntityManagers persistence
context. It takes an entity object as the parameter and returns the entity instance that the
state was merged to.
remove()removes the entity instance from the database.
find()finds an entity instance by its primary key. It retrieves an entity instance from the
database by using the entity class name and the entity ID, which are passed as the methods
parameter.
flush()synchronizes the state of the entities in the EntityManagers persistence
context with the database.
refresh()resets the state of the instance from the database, overwriting any changes
made to the entity. It takes an entity object as its parameter.
clear()clears the EntityManagers persistence context, causing all managed entities
to become detached. Changes made to entities that have not been flushed to the database
are not persisted.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 12
Commonly Used Methods in the EntityManager Interface (continued)
createQuery()creates a dynamic query by using a JPQL statement. It takes a JPQL
query string as its parameter.
createNamedQuery()creates an instance of Query for executing a named query (in
the JPQL or in native SQL) on the entity instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 13
Copyright 2009, Oracle. All rights reserved.
Quiz
The application-managed EntityManager is implemented
outside a Java EE container.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 14
Copyright 2009, Oracle. All rights reserved.
Inserting New Data
To insert new data, perform the following steps:
1. Create a new entity object.
2. Call the EntityManager.persist() method.
@PersistenceContext(unitName="Model")
private EntityManager em; // inject the EntityManager
... // object
public void persistUser() {
Users user = new Users();
user.setFirstName("Steve");
user.setLastName("King");
em.persist(user);
// On return the user object contains persisted state
// including fields populated with generated id values
}
Inserting New Data
The process of creating new data rows requires two steps, provided that you have created an
instance of EntityManager:
1. Create an instance of the entity by using the new operator and a constructor of the entity
class. Optionally, call the setter methods of the new object to set the state (except for the
generated or calculated values, such as primary key fields).
2. Call the persist() method of the EntityManager object with the entity instance to
be persisted.
Note: If the assigned or generated primary key value is not unique, an exception is thrown.
On return, the object supplied as the parameter is updated with the persistent state of the object.
This means that the generated primary key and calculated fields of the entity are updated to be
consistent with the state of the associated data row in the database table. For this reason, you are
able to determine the value of generated primary key fields after the persist() operation is
successfully executed.
Note: If the entity being persisted has relationships with other entities, the related entity objects
are also inserted in the same persistence context. The related entities can be created in the same
way or can be located by using a find() or Query API method.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 15
Copyright 2009, Oracle. All rights reserved.
Deleting Data
To delete data, perform the following steps:
1. Find, set, or refresh the state of the entity to be deleted.
2. Call the EntityManager.remove() method.
@PersistenceContext(unitName="Model")
private EntityManager em;
...
// Remove a Product by primary key Id value
public void removeProducts(Products products) {
products = em.find(Products.class,
products.getProdId());
em.remove(products);
}
...
Deleting Data
To delete an entity instance, perform the following steps:
1. Either query, refresh, or create the entity with its state containing the primary-key value.
2. Execute the remove() method of the EntityManager object.
Note: A removed entity becomes detached, and the state of the deleted entity is available in
memory after the call is made. If the deleted entity is related to other entity objects, the related
entities may be deleted if the relationship mapping or annotation is specified as
cascade=CascadeType.REMOVE. Otherwise, an exception is thrown if dependent entities
exist.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 16
Copyright 2009, Oracle. All rights reserved.
Updating and Synchronizing the Entity with the
Database
1. Retrieve the rows in a database table into the entity by
using the EntityManager API.
2. Use the setter methods of the entity to update the data
attributes.
3. Use the flush() method to synchronize the state of the
entities in the EntityManagers persistence context with
the database.
4. Use the merge() method to reattach an entity to the
persistence context to synchronize it with the database.
Updating and Synchronizing the Entity with the Database
To update rows in a database table, retrieve those rows into the entities by using the
EntityManager API. Then you can use the setter methods of the entities to update any data
attributes (mapped to table columns in the database). The updates are automatically sent to the
database.
By default, all the EntityManager operations (such as persisting entities, removing entities,
and updating entities) are cached in the memory. They are synchronized to the database in a
single batch when the current thread (the stack of method calls) finishes, or before the next
database query is issued (whichever comes first). Inside a transaction, you can flush the current
in-memory changes in the EntityManager to the database by calling the
EntityManager.flush() method.
The EntityManager keeps track of the entities that it retrieved, and captures all updates to
the entities that need to be synchronized to the database. But how do you update a detached
entity and get the changes synchronized to the database? You can use the
EntityManager.merge() method to perform this task by passing the entity instance as the
call parameter.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 17
Copyright 2009, Oracle. All rights reserved.
Updating Data
To update data, perform the following steps:
1. Find, set, or refresh the state of the entity to be updated.
2. Call the EntityManager.merge() method.
@PersistenceContext(unitName="Model")
private EntityManager em;
...
// Update a Product by primary key Id value
public void updateProducts(Products products) {
products = em.find(Products.class,
products.getProdId());
products.setListPrice("1000");
...
em.merge(products);
}
...
Updating Data
To update an entity instance, perform the following steps:
1. Either query, refresh, or create the entity with its state containing the primary-key value.
2. Update the entity attributes with new values.
3. Execute the merge() method of the EntityManager object.
Note: merge() will insert the object if it does not exist. Therefore, if you want an update,
ensure that the object exists.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 18
Copyright 2009, Oracle. All rights reserved.
Finding an Entity by Primary Key
To locate an entity by primary key, perform the following steps:
1. Create and set the primary key object and value.
2. Call the EntityManager find() method with the
following parameters:
Entity class
Primary-key object
import org.srdemo.persistence.Users;
@PersistenceContext(unitName="Model")
private EntityManager em;
...
public Users findUserByPrimaryKey(Long id) {
Users user = null;
user = em.find(Users.class, id);
return user;
}
Finding an Entity by Primary Key
The find() method of the EntityManager API performs a search by primary key
operation. To use the find() method, perform the following steps:
1. Obtain and set the value of the primary key object.
2. Call the find() method with the first parameter specifying the Java type of the entity to
be retrieved, and the second parameter specifying the identity value for the entity instance
to retrieve.
The find() method will return a null if the entity is not found for an instance of the class for
the entity type specified in the first parameter.
Note: The entity instance returned by the find() method is automatically attached to the
EntityManagers persistence context, which means that you can use the EntityManager
to manage that entity instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 19
Copyright 2009, Oracle. All rights reserved.
Quiz
The EntityManager.flush() method:
1. Retrieves the rows in a database table into the entity
2. Reattaches an entity to the persistence context
3. Synchronizes the state of the entity in the
EntityManagers persistence context with the database
Answer: 3
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 20
Copyright 2009, Oracle. All rights reserved.
What Is JPA Query API?
The JPA Query API:
Includes:
EntityManager methods to create queries
Query interface methods for executing queries
Java Persistence Query Language (JPQL)
Supports:
Named queries
Dynamic queries
What Is JPA Query API?
The JPA Query API enables you to use either JPQL or SQL to create and execute queries. The
Query API includes EntityManager interface methods for creating instances, the Query
interface methods that define and execute the query, and JPQL that defines searches against
persistent entities independent of the mechanism used to store those entities.
The Query API supports two types of queries: named and dynamic. Named queries are meant
to define complex or commonly used queries, and are intended to be stored and reused.
Alternatively, dynamic queries are created without disturbing normal operations at run time. The
named queries are prepared once at the time of initialization, whereas dynamic queries are
prepared every time they are executed.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 21
Copyright 2009, Oracle. All rights reserved.
Retrieving Entities by Using the Query API
The EntityManager interface provides the Query API
methods to execute JPQL statements:
createQuery(String jpql)
createNamedQuery(
String name)
EntityManager
Query instance methods:
setParameter(String, Object)
Object getSingleResult()
List getResultList()
int executeUpdate()
Query setMaxResults(int)
Query setFirstResult(int)
Retrieving Entities by Using the Query API
The EntityManager interface exposes a Query API through the following methods:
createQuery()creates a dynamic query and accepts a JPQL query as its parameter.
createNamedQuery() creates a query instance based on a named (precompiled)
query. In this case, the query can be JPQL or native SQL.
All methods return a javax.persistence.Query instance, which provides the following
API calls:
setParameter(String, Object) sets the named parameter to the object value.
getSingleResult() returns a single Object instance result, if any.
getResultList() returns a List collection of entity instances, if any.
setMaxResults(int) and setFirstResult(int) return a Query object and
accept integer parameters. The former sets the maximum number of instances returned,
and the latter sets the first instance to be returned. These methods are useful for paging
through large sets of data.
executeUpdate() executes a JPQL UPDATE or DELETE operation returning the
number of rows affected, and throws an exception for a SELECT statement.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 22
Copyright 2009, Oracle. All rights reserved.
Writing a Basic JPQL Statement
Syntax for a simple JPQL statement:
Examples:
Find all Users entities:
Find a Users entity with a specific email address:
Find a Users entity based on a parameter value:
SELECT object(o)
FROM abstract-schema-name o
[WHERE condition]
SELECT object(o) FROM Users o
SELECT object(o) FROM Users o
WHERE o.email = 'steve.king@srdemo.org'
SELECT object(o) FROM Users o
WHERE o.firstName = :givenName
Writing a Basic JPQL Statement
The slide illustrates the basic query syntax for a JPQL statement, which has:
A mandatory SELECT clause that returns a single entity instance or a collection of entity
instances, whose types are determined by the abstract-schema-name specified in the FROM
clause
A mandatory FROM clause that identifies the abstract-schema-name of the entity being
queried. The abstract-schema-name is the name of the entity class, which is given an
identifier name (such as the alias o in the slide examples). The identifier refers to an
instance of the entity and is used as a prefix for field names, such as o.firstName in the
last example in the slide.
An optional WHERE clause with one or more conditions
The OBJECT()function that is applied to the abstract-schema-name identifier indicates that
instances of the identifier type are being retrieved. The first example returns a collection of all
Users entity instances. The second query example returns a single Users instance where the
email property has the string value steve.king@srdemo.org. The last example is a
parameterized JPQL statement. The named parameter givenName is preceded by a colon and
acts as a placeholder that supplies the value for the conditional expression at run time. The
parameterized query can be written by using the following syntax:
SELECT object(o) FROM Users WHERE o.firstName = ?1
Note: The numbered parameter notation is an alternative to the named notation.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 23
Copyright 2009, Oracle. All rights reserved.
Creating Named Queries
To create a named query, perform the following steps:
1. Define the query with the NamedQuery annotation.
2. Create a Query object for the named query with the
createNamedQuery() method, setting parameters and
returning results.
public List<Users> findUsersinCity(String cityName) {
Query query = em.createNamedQuery("findUsersByCity");
query.setParameter("city", cityName);
return query.getResultList();
}
@NamedQuery(name="findUsersByCity",
query="SELECT object(o) FROM Users o " +
"where o.city = :city");
Creating Named Queries
Often queries are predefined and stored with EntityManager, allowing queries to be defined
ahead of time, recalled, and used at run time.
To create a named query, write a NamedQuery annotation to define the query name and query
string in the entity bean. In the example in the slide, the findUsersByCity named query is
declared in the Users.java entity class definition.
To use the named query with the Query API, perform the following steps:
1. Create a Query object with the createNamedQuery() method, whose argument is the
name assigned to the name attribute of the NamedQuery annotation.
2. With the query instance returned, call the setParameter() method to supply values
for each named parameter or placeholder in the query string. The example uses one
parameter called city, whose value is supplied by the cityName argument in the
findUsersinCity() method.
3. Call the getResultList() method to return a collection of entities.
Note: You call the getSingleResult() method to execute a SELECT query that returns a
single result, and you call the getResultList() method to execute a SELECT query that
returns the query results as a list. If you call the getSingleResult()method and more than
one result is returned, it will throw a NonUniqueResultException.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 24
Copyright 2009, Oracle. All rights reserved.
Writing Dynamic Queries
Example: Find service requests by primary key and a specified
status.
public List findServiceRequests(Long id, String status){
if (id != null && status != null ) {
Query query = em.createQuery(
"select object(sr) from ServiceRequests sr " +
"where sr.svrId = :srvId and sr.status = :status");
query.setParameter("srvId", id);
query.setParameter("status", status);
return query.getResultList();
}
return null;
}
Writing Dynamic Queries
By using the Query API of EntityManager, you can create dynamic queries that respond to
the application requirements. The createQuery()method accepts a single String
argument that defines a JPQL statement to select ServiceRequests entity object instances
matching particular search criteria supplied by the application user.
Because the parameter is a String, the query string can be dynamically constructed based on
user input to return the desired results.
The example in the slide shows how to use the following:
The setParameter() method supplies values to the :srvId and :status
placeholders in the query string.
The getResultList() method returns a List collection of service-request instances
because the JPQL statement return type is defined by the abstract schema name used in the
FROM clause. In this case, the type is ServiceRequests.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 25
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Declare an EntityManager reference with the
@PersistenceContext annotation
Look up an EntityManager reference by using
dependency injection
Use the EntityManager API to:
Find an entity by its primary key
Insert a new entity
Modify an existing entity
Delete an entity
Execute dynamic queries with the Query API
Write simple JPQL queries
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 26
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers the adding named queries to entities.
Copyright 2009, Oracle. All rights reserved.
Developing the Business Logic with
Web Services
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Describe Web service technologies
Identify the role of SOAP, Web Services Description
Language (WSDL), and Universal Description, Discovery
and Integration (UDDI) in Web services
Decide on the Web service development approach
Develop Web services by using the top-down approach
with JDeveloper
Objectives
This lesson provides an overview of Web services, and covers:
A discussion about some of the de facto standards such as SOAP, WSDL, and UDDI
A complete description about developing a Web service by using the bottom-up approach
and top-down approach
Developing a Web service by using the top-down approach with Oracle JDeveloper 11g
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 3
Copyright 2009, Oracle. All rights reserved.
Web Service
Is a technology that is based on a set of standards for
building interoperable distributed applications
Performs self-describing business functions
External
applications
HTML
XML
Web
presentation
Business
logic
Web
service
Database
Application server
HTTP client
Web Service
A Web service is designed to expose business logic that can be accessed by any application. It is
a software component, identified by a Uniform Resource Identifier (URI), whose interfaces and
bindings can be described by standard Extensible Markup Language (XML) vocabularies.
The Web service technology (based on a set of standards) has revolutionized the way in which
the application-to-application communication used to happen in an enterprise. An enterprise
system usually has multiple applications, each running on different hardware and sometimes
implemented in different languages. These applications often need to exchange data with one
another, and developers must write additional code to make this integration possible. The Web
service technology provides a solution for the enterprise application integration.
A Web service supports direct interaction with other software applications or components and is
network accessible. With a Web service, you can make your applications programmatically
accessible to other applications over the Internet. Web services establish a method to standardize
communication, making it easier for applications to share information.
For example, in the case of a merger or an acquisition, companies can avoid investing large
sums of money on developing software to integrate the systems of the different companies.
The information systems of different companies can be linked by extending each companys
business applications as Web services. These business systems can then be accessed by using
simple SOAP messages over the normal HTTP protocol.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 4
Copyright 2009, Oracle. All rights reserved.
Web Service Standards
Web service standards can be defined in terms of the following:
SOAP
WSDL
UDDI
Web Service Standards
SOAP is an extensible, text-based framework that enables communication between
different applications without prior knowledge of each others environment.
The applications can interoperate with each other or even connect dynamically to services
without establishing any initial agreements between them. SOAP is extensible and is
generous in terms of supporting intermediaries and layered architectures.
WSDL is an XML-based language for describing and accessing Web services. It provides
a simple way for service providers to describe the basic format of requests to their systems
regardless of the underlying protocol (such as SOAP) or encoding (such as Multipurpose
Internet Mail Extensions [MIME]). WSDL describes services as a set of endpoints
operating on messages that are described abstractly.
UDDI is an XML-based registry that enables businesses to list themselves and their
services on the Internet. It is a platform-independent framework for describing services,
discovering businesses, and integrating business services. Its ultimate goal is to streamline
online transactions by enabling companies to find one another on the Web and to make
their systems interoperable for e-commerce.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 5
Copyright 2009, Oracle. All rights reserved.
SOAP: XML Messaging for Web Services
SOAP:
Is an XML-based protocol for exchanging data
Represents requests and responses as XML messages
Uses HTTP and other protocols at the transport layer
Supports data encoding and literal styles
Hides details of implementations
Works with:
Any programming language
Any hardware and software platform
Client
Request (SOAP)
Web service
Response (SOAP)
SOAP: XML Messaging for Web Services
SOAP is a lightweight, XML-based protocol for exchanging data in a distributed environment.
It hides technology choices and implementation details from both the service requestor and the
service provider. SOAP is defined in XML and, therefore, it places no restriction on the format.
It introduces a self-describing data representation in XML. By looking at the request and
response messages, you can easily find out what was sent as part of a request and what the
response was. If the response has a fault element, by looking at it, you know what caused the
error.
SOAP provides a mechanism for exchanging structured and typed information between peers in
a decentralized, distributed environment by using XML. SOAP itself does not define any
application semantics such as a programming model or implementation-specific semantics;
instead, it defines a simple mechanism to express application semantics by providing a modular
packaging model and encoding mechanisms for encoding data within modules.
SOAP V1.2 describes how the data types defined in the associated XML schemas can be
serialized, or marshaled, over HTTP (or other transports such as Simple Mail Transfer Protocol
[SMTP] or FTP). SOAP is transport independent. Most common implementations are over
HTTP. Both the publisher and the consumer of SOAP messages must have access to the same
XML schemas in order to correctly exchange the information. The schemas are normally posted
on the Internet and may have to be downloaded to be used by applications that exchange XML
messages whose structures are based on the schema.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 6
Copyright 2009, Oracle. All rights reserved.
Web Services Description Language (WSDL)
A WSDL document is an XML
document that describes:
What the service does
How the service is accessed
Where the service is located
It defines the messages and
the operations of a service
abstractly in XML.
Types
Messages
Port types
Bindings
Services
WSDL document structure
WSDL document
Web Services Description Language (WSDL)
WSDL corresponds to an interface definition language that provides a standard way to describe
Web services. WSDL uses the XML format for describing Web services. It describes what
functionality a Web service offers, how it communicates, and where it is accessible. Because
WSDL is in the standard XML format, the services developed can easily be made available to
thousands of users. Users must invoke the correct services with the appropriate parameters.
WSDL defines an XML grammar to specify the location of the service and to describe the
operations of a service.
A WSDL document contains the service interface definition, the implementation details, the
access protocol, and the contact endpoints information about an operation. The WSDL document
describes a Web service by using these major elements:
<portType>: Describes a Web service, the operations that can be performed, and the
messages that are involved
<message>: Describes the messages used by the Web service; defines the data elements
of an operation
<types>: Defines the data types used by the Web service
<binding>: Defines the communication protocols used by the Web service
<service>: Describes the name and location of the Web service and the context with
which it can be accessed
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 7
Copyright 2009, Oracle. All rights reserved.
UDDI Registry
The UDDI registry:
Is an online electronic registry for registering businesses
and Web services
Is a specification for description and discovery
Supports Publishing and Inquiry APIs to publish and query
a Web service
UDDI Registry
You should have seen the definition and the benefits of Web services. You should have also
observed that WSDL is used to describe Web services and that SOAP is used to invoke them. To
invoke a Web service, the service requestor should first discover the service, and then send the
SOAP message. Because UDDI is a registry where businesses and Web services are registered,
the requestor can use UDDI to discover a Web service.
UDDI is a directory service where businesses can register and search for Web services. It is a
platform-independent framework for describing services, discovering businesses, and integrating
business services.
The UDDI registry can be used at a business level to verify whether there are any Web service
interfaces with a given type of service. UDDI serves as a mechanism for businesses to reach
their customers and partners. It is used to locate information about how the service is exposed
and to learn the technical details required for interaction with that service.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 8
UDDI Registry (continued)
The UDDI business registry is a logically centralized, physically distributed service with
multiple root nodes that replicate data with each other on a regular basis. After a business
registers with a single instance of the business registry service, the data is automatically shared
with other UDDI root nodes and becomes freely available to anyone who needs to discover
which Web services are exposed by a particular business. These are public registries. You can
also have private UDDI registries.
To ensure that most platforms can access UDDI services, the UDDI directory exposes a set of
APIs. These APIs fall under two main categories: Inquiry and Publishing. To use these APIs,
you must send SOAP messages with appropriate body content. The SOAP response that comes
back from a UDDI registry contains information about the businesses that match the search
criteria.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 9
Copyright 2009, Oracle. All rights reserved.
Web service
Service
implementation
Web Service Architecture
Web service
client application
Web services
directory
Internet
Interface
(WSDL)
WSIL
browser
1
Generate
WSDL
2
Register
(UDDI)
3
Find
(UDDI)
Find Locate
Invoke request (SOAP)
Send response
(SOAP)
4
5
Web Service Architecture
The diagram shows a conceptual architecture of Web services. The provider of a Web service
performs the following steps to expose a Web service endpoint:
1. Generating the WSDL: The Web service is developed and the XML format describing the
service (the WSDL) is generated.
2. Registering with the Web service registry: The Web service provider registers itself as a
business entity and publishes the WSDL in one or more UDDI registries (for example,
Oracle Service registry).
The consumer of a Web service performs the following steps to invoke a Web service:
3. Searching with an UDDI registry or a Web Services Inspection Language (WSIL)
browser: The consumer searches the UDDI registry or uses a WSIL browser to locate the
WSDL for the Web service.
4. Invoking the Web service: The consumer sends a SOAP request to invoke the Web service
by using the information stored in the WSDL. The WSDL information, which is obtained
from the UDDI registry or WSIL browser, includes:
- The URL for the service endpoint to locate the service functions
- The WSDL that defines interface methods and messages provided by the service
5. Communicating the response: The provider responds with a SOAP message that
communicates information to the consumer. The SOAP request and response are typically
transmitted using the simple HTTP request-response protocol.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 10
Web Service Architecture (continued)
WSIL is defined as an XML grammar by the WS-Inspection specification to address the need to
facilitate the aggregation of references to different types of service description documents stored
in the form of WSDL and UDDI registries. The WS-Inspection specification provides a means to
inspect sites for service and locate pointers to service description documents.
Note: Java applications can use the Web Services Invocation Framework (WSIF), which is a
Java API to invoke Web services.
You can use the WSIL browser to search for WSDL descriptions of services. The WSIL browser
can locate services published in UDDI registries or in local file systems.
The following are the file formats used extensively by Web service standards:
XML: Extensible Markup Language (XML) is a set of rules for defining data markup in a
plain text format.
XSD: XML Schema Definition (XSD) specifies how to formally describe the elements in
an XML document.
XSL: Extensible Stylesheet Language (XSL) is a specification (or template) for separating
style from content when you create HTML or XML pages.
XSLT: Extensible Stylesheet Language Transformations (XSLT) is the language used in
XSL style sheets to transform XML documents into other XML documents.
XPath: XML Path (XPath) is a language with a set of syntax rules for defining parts of an
XML document.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 11
Copyright 2009, Oracle. All rights reserved.
Quiz
The <portType> element in a WSDL describes a Web
service, the operations that can be performed, and the
messages that are involved.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 12
Copyright 2009, Oracle. All rights reserved.
Web Service Metadata for
Java Platform (JSR-181)
Is a Java specification to develop Web services by using a
document written in annotated Java syntax
Defines a processor model that acts as a bridge between
the annotated document and the Web service artifacts
Web Service Metadata for Java Platform (JSR-181)
JSR-181 defines an annotated Java syntax to enable easy definition of Web services in Java.
According to JSR-181, a Java Web service is a simple Plain Old Java Object (POJO) with a few
annotations. The annotations are used to define and describe the Web service architecture, such
as the Web service name, all the methods that should be exposed in the Web service interface,
parameters, their types, the bindings, and other information.
JSR-181 also defines a processor (processing environments) that acts as a tool to bridge the gap
between an annotated file and the Web service artifacts. For example, the processor can be used
to generate a WSDL document from an annotated file or vice versa. It can also be used to
generate an Enterprise Archive (EAR) package that can be deployed as a Web service within
any Java 2, Enterprise Edition (Java EE) 1.4compliant container. It is essential to note that JSR-
181 does not define any run-time environment for the Web services, but only provides a model
for processing the annotated file and mapping the annotated file to the Java EE 1.4 run-time
environment.
Note: JSR-175 defines the rules for adding annotations into the Java language syntax.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 13
Copyright 2009, Oracle. All rights reserved.
Examining the JSR-181 Processor Model
JSR-181
processor
WSDL
Deployment
descriptors
Java
classes
Web service artifacts
Annotated
Java file
Generates
Input
Examining the JSR-181 Processor Model
The slide displays a sample JSR-181 processor model. The JSR-181 processor can be any tool
(such as JDeveloper) that enables a Web service program written in Java (by using Java
annotations) to produce the required Web service artifacts. It provides all the functionalities
(such as generating Java-to-WSDL mappings and WSDL-to-Java mappings, and generating
EAR packages) required to develop and deploy the Java Web service.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 14
Copyright 2009, Oracle. All rights reserved.
Describing JSR-181 Annotations
Standard annotations defined by JSR-181:
javax.jws.soap.SOAPBinding
@SOAPBinding
javax.jws.WebResult
@WebResult
@WebParam
@WebMethod
@WebService
Annotation
javax.jws.WebService
javax.jws.WebParam
javax.jws.WebMethod
Java Class or Interface
Describing JSR-181 Annotations
As defined in JSR-181, the important annotations used to define a Java class as a Web service
are the following:
@WebService: Marks the class indicating that it implements the Web service
@WebMethod: Marks methods that generate the service endpoint interface
@WebParam: Defines Web service parameters that are specified in the wsdl:part
element of the WSDL document
@WebResult: Defines the return value in the wsdl:part element of the WSDL
document
@SOAPBinding: Specifies the SOAP binding details, and provides annotation members
for style, use, and parameterStyle properties that customize mappings in the
wsdl:binding element
Oracle WebLogic Server Web Services supports the entire set of annotations described in
JSR-181.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 15
Copyright 2009, Oracle. All rights reserved.
Sample Annotated Java Web Service File
import javax.jws.WebService;
import javax.jws.WebMethod;
@WebService(serviceName = "Hello")
public class Hello {
@WebMethod(operationName="sayHello")
public String sayHello() {
return "Hello World!";
}
}
1
2
Sample Annotated Java Web Service File
The slide shows a sample annotated Java file. The Hello Java class is deemed to be a Web
service implementation class, which defines and implements a sayHello method that can be
exposed as a Web service. The annotations are:
1. @WebService: Marks the Hello class indicating that the class implements the Web
service. The serviceName attribute specifies the name of the Web service.
2. @WebMethod: Marks the sayHello method that generates the service endpoint interface
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 16
Copyright 2009, Oracle. All rights reserved.
What Is JAX-WS?
JAX-WS:
Stands for Java API for XML Web Services
Defines the core specification for the Web services
standard in Java EE 5
Provides an extension to the JAX-RPC 1.0 Web services
standard
Enables you to expose both POJOs and stateless
Enterprise JavaBeans (EJBs) as Web services by
implementing metadata annotations
What Is JAX-WS?
Java API for XML Web Services (JAX-WS) is a specification for building Web services and
Web service clients that communicate by using XML-based protocols (such as SOAP). JAX-WS
allows developers to write message-oriented as well as RPC-oriented Web services.
For more information about Web services technology and its standards, refer to the OracleAS
10g R3: Build Web Services course.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 17
Copyright 2009, Oracle. All rights reserved.
Quiz
As defined in JSR-181, the important annotations used to
annotate a Java class as a Web service are:
1. @SOAPBinding
2. @Resource
3. @WebParam
4. @EJB
5. @WebService
Answers: 1, 3, 5
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 18
Copyright 2009, Oracle. All rights reserved.
Web Service Development Approach
There are two approaches:
Bottom-up approach
You can generate the Web service by using the existing
code.
It requires little or no knowledge of WSDL or XML.
Top-down approach
You can generate the Web service from an existing WSDL
file.
Server-side and client-side development can be done
simultaneously.
Web Service Development Approach
Web services can be generated by using either a bottom-up approach or a top-down approach.
Each of these has advantages and disadvantages that determine the pattern that should be used in
a given situation.
The bottom-up approach starts with coding the business logic that is being abstracted into an
interface definition. The interface is then exposed as a Web service. It requires little or no
knowledge of WSDL or XML because the WSDL document is automatically generated by the
development tools.
With the top-down approach, both the server-side and the client-side developers use a WSDL
document to produce the artifacts necessary for their respective environments. The server-side
developer can start with the WSDL document to define new implementations of portType
(defined by WSDL), and the client-side developer can start with the same WSDL document to
develop a Web service client. This leads to the independent development of the client-side and
server-side simultaneously. The top-down approach model also provides reusability of new
schema types developed for the current Web service. It can be achieved by simply incorporating
the new XML Schema Definition (XSD) schema into the required Web services.
Some developers have also used a third method, primarily because of shortcomings or defects in
tools, and a lack of thorough understanding of Web services tools and technologies. In what is
called round-trip development, the developer uses a part of the top-down process followed by
parts of the bottom-up process. For example, you will follow this approach when you are given a
WSDL and also have to work with existing domain classes.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 19
Copyright 2009, Oracle. All rights reserved.
Web service
client development
Web service
development
Bottom-Up Approach
Web service
client
Java class/EJB
Java-to-WSDL
WSDL
Generate Java
artifacts
Generate WSDL
artifacts
1
2
1
2
WSDL-to-Java
Bottom-Up Approach
Web Service Development
1. The business logic is coded using either Java classes or EJBs. These contain methods that
are exposed in the Web service interface.
2. The Web service generation tool (in this case, Java-to-WSDL) generates the WSDL.
The Web service generation tool can be the WebServicesAssembler (WSA) tool or
JDeveloper.
Web Service Client Development
1. The Web service generation tool (in this case, WSDL-to-Java) generates the client-side
proxy class and other client-side artifacts from the WSDL.
2. The Web service client application uses the proxy class to communicate with the Web
service application.
Note: With the bottom-up approach, the development of the Web service client is dependent on
the implementation of the Web service because all the client-side artifacts (such as the proxy and
the stubs) are developed from the WSDL document. The bottom-up approach also often leads to
very fine-grained services. Therefore, the top-down approach of Web services development is
much preferred.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 20
Copyright 2009, Oracle. All rights reserved.
Web service
client development
Web service
development
Top-Down Approach
Web service
client
Web service
implementation
WSDL-to-Java
WSDL-to-Java
WSDL
XSD schemas
Generate Java
artifacts
Generate Java
artifacts
1
2 2
1
Top-Down Approach
Web Service Development
1. A WSDL document is created. You can incorporate multiple XSD schemas in the WSDL
document, which describes the input and the output data types for the Web service
operation.
2. The Web service generation tool (in this case, WSDL-to-Java) generates the Java artifacts,
such as the service endpoint interface, which are implemented as a Web service.
Web Service Client Development
1. This is similar to Web service development.
2. The Web service generation tool (in this case, WSDL-to-Java) generates the Java artifacts,
such as the client-side proxy class and stub, which are used by the client application to
communicate with the Web service.
Note: In the top-down approach, the development of the client-side and the server-side can be
done in parallel, and without any dependency on each other.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 21
Copyright 2009, Oracle. All rights reserved.
Developing a Web Service by Using
the Top-Down Approach
To develop a Web service by using the top-down approach in
JDeveloper, perform the following steps:
1. Define an XSD schema.
2. Create the WSDL document incorporating the XSD
schema.
3. Generate the Web service artifacts from the WSDL
document by using JDeveloper.
4. Implement the Web service logic.
5. Deploy the generated artifacts by using JDeveloper.
Deploys
Web service
WSDL
Java
classes
XSD
Developing a Web Service by Using the Top-Down Approach
To develop a Web service by using the top-down approach model, you start with defining a
single or a collection of XSD schemas, which describe the input and output data types for the
Web service operations. These XSD schemas are used to design the WSDL document. It can be
done by either creating a new WSDL document or editing an existing one. The WSDL document
is processed to generate the Java artifacts by using JDeveloper. These artifacts are used to
implement the Web service logic. These artifacts are then assembled and deployed to the
application server.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 22
Copyright 2009, Oracle. All rights reserved.
Defining an XSD Schema
Input
type
Output
type
Defining an XSD Schema
You can create an XSD schema by using JDeveloper. You can visually insert or modify the XSD
elements (such as complex types and elements) by using the XSD schema editor utility in
JDeveloper. You can insert an XSD node (such as an element, a complex type, and a simple
type) by right-clicking any existing node and selecting one of the following options: insert
before element, insert inside element, or insert after element, and thereby selecting the
appropriate node to insert. You can modify an existing node by double-clicking a specific node
and modifying its value.
The XSD schema (CreditService.xsd) has been defined that consists of XML complex
type and XML elements. The complex CreditCard type is defined to handle the input
operation type (method parameter), and the elementsvalid and errorare defined to
handle the output operation type (method return type) of the Web service logic (implemented
using a Java method).
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 23
Copyright 2009, Oracle. All rights reserved.
Creating the WSDL Document
XSD
schema
<definitions name="CreditService"...
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org"
...
<xsd:import namespace="http://www.example.org "
schemaLocation="CreditService.xsd"/>
</schema>
</types>
...
WSDL
Imports
Creating the WSDL Document
The slide displays a part of the WSDL document where the specified XSD schema
(CreditService.xsd) has been incorporated.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 24
Copyright 2009, Oracle. All rights reserved.
Creating the WSDL Document
...
<message name="CreditCardValidationRequestMessage">
<part name="CreditCard" element="types:CreditCard"/>
</message>
<message name="CreditCardValidationResponseMessage">
<part name="valid" element="types:valid"/>
</message>
...
<portType name="ValidateCreditCard">
<operation name="VerifyCC">
<input message="tns:CreditCardValidationRequestMessage"/>
<output message="tns:CreditCardValidationResponseMessage"/>
...
</operation>
</portType>
...
Creating the WSDL Document (continued)
The <message> and <portType> elements of the WSDL document are displayed in the
slide. There are two <message> elements: CreditCardValidationRequestMessage
and CreditCardValidationResponseMessage.
CreditCardValidationRequestMessage takes care of handling the input operation
and is associated with defining the input parameter for the Web service operation defined in the
Web service endpoint interface. The part element indicates that the Web service operation
takes a parameter of the CreditCard type. The type is defined as an XML element in the
XSD schema (CreditService.xsd).
Similarly, CreditCardValidationResponseMessage is associated with the output
operation and specifies the return type of the Web service operation.
The <portType> element indicates the name of the implementation class,
ValidateCreditCard. This class implements the method defined in the service endpoint
interface. The <portType> element also specifies the <operation> element whose name
attribute is set to VerifyCC, which is the name of the method defined in the service endpoint
interface. The service endpoint interface is then exposed as a Web service. The <input> and
<output> elements contain the corresponding input message and output message names.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 25
Copyright 2009, Oracle. All rights reserved.
Modifying the WSDL Document
Modifying the WSDL Document
You can create or modify the WSDL document in JDeveloper by using the WSDL editor tool.
The WSDL editor gives you a design view of the WSDL document that enables you to segregate
the different sections of the WSDL document (such as, services, bindings, and port
types) in a hierarchical structure. You can expand the tree of a specific section, and can
modify the values of different elements present in that specific section. You can double-click
any element to modify its value. For example, to modify the value of the VerifyCC element
(in the port types section), click the VerifyCC element to open the dialog box that enables
you to modify the attributes (such as the name attribute) of the VerifyCC element. You can
also perform the same task by using the Structure window. For example, you can insert a
predefined schema in the WSDL document by executing the following steps:
1. Open the WSDL document in design view.
2. In the Structure window of JDeveloper, navigate to definitions > Types > types > schema
node. Right-click the schema node and select Insert inside schema > xsd:import from the
pop-up menu.
3. Enter CreditService.xsd in the schemaLocation field and
http://www.example.org in the namespace field.
4. Click the OK button.
Similarly, you can also modify the values of the other elements present in the WSDL document.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 26
Copyright 2009, Oracle. All rights reserved.
Creating the Web Service by Using
Oracle JDeveloper 11g
1
2
Creating the Web Service by Using Oracle JDeveloper 11g
You can use the Oracle JDeveloper 11g Integrated Development Environment (IDE) to develop
Web services. You can expose any Java resource (such as a Java class or an EJB) as a Web
service in JDeveloper. JDeveloper also enables you to generate a Web service from a WSDL
document and a PL/SQL package.
You can use the Java Web Service from WSDL Wizard to generate the Web services artifacts
from a given WSDL document.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 27
Copyright 2009, Oracle. All rights reserved.
Implementing the Web Service Logic
Implementing the Web Service Logic
The slide displays the JDeveloper IDE. It consists of the Application Navigator pane, Structure
pane, and the code editor. In the Application Navigator, all the necessary resources or artifacts
(such as the WSDL document and XSD schema) to develop and deploy a Web service
application are displayed (generated by the wizard).
If you select any of the Web service artifacts from the Application Navigator pane, the
corresponding structure of the component is displayed in the Structure pane. For example, if you
select the Web service implementation class (ValidateCreditCardImpl.java) in the
Application Navigator pane, you can see its constructor and methods in the Structure pane. Now,
if you select any of the methods of the ValideateCreditCardImpl.java in the
Structure pane, you can see the corresponding code in the code editor. The Web service
application exposes the verifyCC() method as a Web service. You need to modify the code
to implement the verifyCC() method (Web service logic) to validate a credit card.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 28
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe Web service technologies
Identify the role of SOAP, WSDL, and UDDI in Web
services
Decide on the Web service development approach
Develop Web services by using the top-down approach by
using JDeveloper
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 29
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers the following topics:
Creating a Web service application by using the top-down
Web service development approach
Testing the Web service application by using JDeveloper
Copyright 2009, Oracle. All rights reserved.
Developing the Web Interface Using
JavaServer Faces
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Describe the purpose of JavaServer Faces
Use JSF components
Explain the use of managed beans
Describe the life cycle of a JSF application
Explain the role of the JSF tag libraries
Describe how JDeveloper supports JSF
Create a JSF-based JSP in JDeveloper
Objectives
In this lesson, you learn about JavaServer Faces (JSF), which are JavaServer Pages (JSP) that contain
special user interface (UI) components. Like JSP, JSF supports the MVC framework and is,
therefore, a valuable technology for building the view component of Java EE applications. You learn
that JDeveloper provides a feature-rich development environment for building JSF pages quickly and
easily.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 3
Copyright 2009, Oracle. All rights reserved.
JSF: Overview
JavaServer Faces (JSF) is a server-side component
framework for Web applications.
JSF:
Is an implementation of the MVC design pattern
Enables separation of business and presentation logic
Enables separation of navigational and data flow
JSF: Overview
JSF is a server-side UI technology, as opposed to a client-side UI technology such as Swing. JSF is
also a component-based architecture, which means that instead of working with markup, the
developer works with UI components, similar to Swing.
JSF also implements the MVC design pattern, which includes the UI (view), controller, and the
model. The built-in controller provides developers with a technique to cleanly separate the
navigational aspects of an application from the data presentation logic.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 4
Copyright 2009, Oracle. All rights reserved.
JSF: Benefits
Simplifies Java EE development
Is intended for RAD style development tools
Is a component-based architecture
Supports Java EE framework:
State management
Error handling
Input validation
Type conversion
Event handling
Page navigation
Is portable across JSF implementations
JSF: Benefits
The JSF technology provides Web application life cycle management through a controller servlet and
a rich component model with event handling and component rendering.
Because JSF is a component-based architecture, it simplifies the development process. Part of the
direction of the JSF specification is to make the architecture readily accessible by using GUI
development tools, such as JDeveloper.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 5
Copyright 2009, Oracle. All rights reserved.
Key Terms
UI component: The components that manage data to be
displayed on a page
Managed bean: Objects that maintain data and methods
that are used across multiple pages
Expression Language: Shortcut to access properties and
methods from a JSF page
Navigation model: The rules that govern page flow
Life cycle: The processes that are executed from the time
a page is loaded until it is complete
Key Terms
Each of these key terms is discussed in detail later in this lesson.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 6
Copyright 2009, Oracle. All rights reserved.
JSF Architecture
JavaServer Faces has:
A set of prefabricated UI components
An event-driven programming model
A component model that enables third-party developers to
build additional components
It can be thought of as Swing for server-side applications.
JSF Architecture
The UI component classes included with the JavaServer Faces technology include the component
functionality, not the client-specific presentation. With ease-of-use being the primary goal, the
JavaServer Faces architecture defines a separation between application logic and presentation,
making it easy to connect the presentation layer to the application code.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 7
Copyright 2009, Oracle. All rights reserved.
JSF Architecture
Page
HTML
render kit
Page
Back-end
code
HTML
browser
Phone/
PDA
WML
render kit
Front
controller
JSF Architecture (continued)
The slide shows the JSF architecture in a simplified manner. Just like any other MVC-based
architecture, JSF architecture has its own front controller called the FacesServlet. The FacesServlet
acts as a gatekeeper for the application. Upon an initial Web request to access a JSF application, the
FacesServlet handles the request by first preparing the JSF context, which is a Java object that holds
all application data.
As stated earlier, a JSF page is made of a tree of UI components that can be associated with model
objects called backing beans. These backing beans handle application or business logic for the
application.
JSF UI components have the ability to render themselves differently depending on the client type
viewing the component. When a page has to be rendered to a particular client type, whether the client
type is an HTML browser running on a desktop or a Wireless Markup Language (WML) browser
running on a wireless phone, a particular renderer is used for displaying the data maintained in the UI
components. Because JSF decouples the UI component from its rendering logic, the same UI
component is used for displaying information about different client types using different protocols.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 8
Copyright 2009, Oracle. All rights reserved.
JSF Components
JSF Components consists of three parts:
UI components: Functionality, attributes, or behavior
Renderers: Converts components to and from a specific
markup language
Render kits: Library of renderers (The Basic
HTML RenderKit is part of the specification.)
JSF Components
The Components model is a major part of JSF. JSF Components consist of three parts:
The components themselves define basic attributes, functionality, or behavior for the
components. For example, a button has some expected behaviors, such as what happens when it
is clicked. These are defined within the component. If a component has a value-changed event,
the developer can create a listener for that event. The framework then invokes that listener at
the right time. Components are standardized within JSF, so you can use any component from
any vendor with the framework and mix and match them as required, and they all behave in the
same way.
Renderers convert a component to and from a specific markup language. A renderer makes JSF
components flexible with respect to which type of client can use the component. Attributes say
nothing about how the component is displayedthat is the responsibility of the renderer. A
renderer for a component may output very complex HTML, such as a tree control, or a simple
item, such as output text. The generated markup may include JavaScript as well as HTML if a
particular component has complex client-side behaviors.
Render kits are a library of renderers. The Basic HTML RenderKit is part of the JSF
specification.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 9
Copyright 2009, Oracle. All rights reserved.
JSF UI Components
Are the basic building blocks of a JSF application
Are stateful server objects
Do not define rendering
Can represent simple to
complex user interface
components ranging from
a button or input field to a complete page
Can be associated to model data objects through value
binding
Can use helper objects, such as validators, converters,
listeners, and events
JSF UI Components
JSF UI components are what you use to build a JSF user interface. UI components are stateful server
objects. They are maintained on the server. They do not define any rendering characteristics.
Rendering is handled by the renderers.
The components range from simple text field components to complex shuttle type controls. Each
component can be associated to a model by using value binding. Each component can also use helper
objects that are included in JSF, such as validators, converters, listeners, and events.
When a JSP page is created using JSF components, a component tree or view is built into memory
on the server with each component tag corresponding to a UIComponent instance in the tree. The
component tree is used by the JSF framework to handle your application request and create a
rendered response.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 10
Copyright 2009, Oracle. All rights reserved.
JSF Component Architecture
Expr. Language
Managed bean
JSF page
J2EE Persistence Layer/JDBC
<f:view>

<h:inputText
required="true"
value="#{emp.name}"
/>

</f:view>
Markup
RDBMS
UI component
Device Renderer
JSF Component Architecture
In this diagram, all the three main JSF components are highlighted: the component renderer, the
component itself, and the binding expression.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 11
Copyright 2009, Oracle. All rights reserved.
Quiz
Identify the correct statements about JavaServer Faces.
1. It includes a set of APIs for representing the user
interface (UI) components and managing their state,
handling events and input validation, converting values,
defining page navigation, and supporting
internationalization and accessibility.
2. It includes a default set of UI components.
3. It includes a server-side event model.
4. It includes state management.
5. It includes managed beans (JavaBeans created with
dependency injection).
Answers: 1, 2, 3, 4, 5
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 12
Copyright 2009, Oracle. All rights reserved.
Tag Handlers and Component Trees
Each tag has a corresponding tag handler class.
JSF tag handlers collaborate with each other to build a
component tree.
Examples of JSF tags are:
f:form, h:inputText, h:inputSecret,
h:commandButton
UIForm
UIInput UIOutput UICommand
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 13
Copyright 2009, Oracle. All rights reserved.
Tag Libraries
Core tag library
f: tags for faces
Custom actions independent of any rendering kit
Example: f:validator, f:converter,
f:selectItem
HTML tag library
h: tag for HTML
Component tags for all UI components and HTML rendering
kit
Example: h:form, h:inputText, h:messages
Tag Libraries
Core tag library
Validation: It is difficult to imagine a Web application that does not perform a healthy dose of
data validation. JavaServer Faces provides a handful of standard validators and a simple
mechanism for implementing your own validation.
Data Converters: A Web application stores data of many types, but the Web user interface
deals exclusively with text. For example, suppose the user needs to edit a Date object. First,
the Date object is converted to a string that is placed inside a text field. The user then edits the
text field. The resulting string must be converted back to a Date object.
Navigation: Consider what happens when the user of a Web application fills out a Web page.
The user enters text and clicks option buttons and drop-down lists. All of these edits happen
inside the users browser. The changes are transmitted to the server when the user clicks a
button that posts the form data. At that time, the Web application analyzes the user input and
must decide which JSF page to use for rendering the response. The navigation handler is
responsible for selecting the next JSF page.
HTML tag library
This library contains tags for standard HTML style elements.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 14
Copyright 2009, Oracle. All rights reserved.
Configuration Files
faces-config.xml
Defines managed beans
Specifices navigation rules
Must exist with WEB-INF
Similar to struts-config.xml
Servlet mapping in web.xml uses a faces extension.
URL pattern *.faces maps to
java.faces.webapp.FacesServlet.
Configuration Files
One or more configuration files are used to configure a JSF application. The main configuration file
for an application is the WEB-INF/faces-config.xml file. Files in the same format can be
bundled also within JAR files containing custom components, renderers, or any other custom JSF
classes.
Within the <faces-config> element body, top-level elements can be included in any order. Each
top-level element is described in a separate section in the appendix. The
top-level elements are all optional and can be included more than once, unless otherwise stated. Most
top-level elements contain other elements.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 15
Copyright 2009, Oracle. All rights reserved.
JSF Renderers
Two rendering models:
Direct implementation
Delegated implementation
Delegated implementation enables separation of UI from
how they appear to the user.
Each JSF implementation must provide a default RenderKit
instance.
JSF specification includes the Standard HTML RenderKit
Specification.
JSF Renderers
The renderer creates the client-side representation of the component, takes any input from the client,
and transforms it into something that the component can understand. The typical renderer
implementation generates HTML and understands how to transform values from HTML form POSTs
into values the component understands. However, this is not the only client type that can be rendered
by a JSF renderer. For example, the reference implementation comes with a set of Extensible User
Interface Language (XUL) renderers.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 16
Copyright 2009, Oracle. All rights reserved.
Managed Beans
Java objects (empty constructor), maps, lists
Defined in faces-config.xml
Defined with various scopes:
application
session
request
none
Lazy initialization by JSF as needed
Managed Beans
Along with components, managed beans are a key part of JSF. Any Java object can be a managed
bean as long as it has a no-arg constructor. The managed bean is defined in XML in the faces-
config.xml file. This file exists in the WEB-INF directory of the application and is the master file
for a JSF application.
When you create a page, you can automatically create a managed bean with references to the objects
you create on the page. This type of managed bean is called a backing bean, and it also provides a
place to put code. In many cases, the backing bean contains only action code with no references to
the UI components, or references to only a few of the components that you need to manipulate
programmatically.
Managed beans can also be used to hold information about the request, application, or session.
The life cycle of a managed bean is handled by JSF. When the bean is first referenced, JSF creates an
instance of the relevant Java class and keeps it around as long as is specified by the bean definition.
The none scope listed in the slide is used to define transitory objects that are used just to populate
other managed beans and are never used outside that context.
Usage of that managed bean is then through Expression Language, which is discussed in the
following slide.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 17
Copyright 2009, Oracle. All rights reserved.
Expression Language
Dot notation for attributes (JavaBean model):
#{userbean.name} same as
instance.getName();
Map notation:
#{foo["baa"]} same as
instance.get("baa");
Expressions can be of any depth:
#{foo["baa"].person.name}
Expression Language
Expression Language (EL) is the binding factor in JSF. It provides the hook between the user
interface and the managed bean facility. Almost any property in a component can be set to an EL
expression.
The primary use of EL is to set properties is to bind the value of a component to something in the
model. You can also bind attributes to EL, such as the rendered attribute supported by all
components. You can set a value directly or to an expression that evaluates to a Boolean value to do
conditional processing.
You can use EL not only for binding to managed beans, but also for directly referencing various
known scopes, such as request or session scope.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 18
Copyright 2009, Oracle. All rights reserved.
Life Cycle of a JSF Page
A JSF page is represented by a tree of UI components,
called a view.
When a client makes a request for the page, the life cycle
starts.
During the life cycle, JSF implementation must build the
view while considering the state saved from the previous
postback.
When the client performs a postback of the page, JSF
implementation must perform life-cycle steps:
Validation
Conversion
Life Cycle of a JSF Page
The life cycle of a JavaServer Faces page is similar to that of a JSP page. The client makes an HTTP
request for the page, and the server responds with the page translated to HTML. However, because of
the extra features that JavaServer Faces technology offers, the life cycle provides some additional
services to process a page.
A JavaServer Faces page is represented by a tree of UI components, called a view. When a client
makes a request for the page, the life cycle starts. During the life cycle, the JavaServer Faces
implementation must build the view while considering the state saved from the previous postback.
When the client performs a postback of the page, the JavaServer Faces implementation must perform
several tasks, such as validating the data input of components in the view and converting input data
to types specified on the server side. The JavaServer Faces implementation performs all these tasks
as a series of steps in the life cycle.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 19
Copyright 2009, Oracle. All rights reserved.
JSF Life Cycle: Initial Request
Restore/create
view.
Client/Browser
Render
response.
Apply
request
values.
Update
model.
Invoke
application.
Process
validation.
JSF Life Cycle: Initial Request
The life cycle handles both kinds of requestsinitial requests and postbacks. An initial request for a
page is when the user requests the page for the first time.
During the initial request, JSF creates a server-side component tree based on the components on the
page. It populates the tree with whatever values are appropriate at the time. Because this is an initial
request with no user input or actions to process, JSF executes only the restore view and render
response phases.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 20
Copyright 2009, Oracle. All rights reserved.
JSF Life Cycle: Postback
Restore/create
view.
Client/Browser
Render
response.
Apply
request
values.
Update
model.
Invoke
application.
Process
validation.
Life Cycle: Postback
A postback occurs when the user submits the form contained on a page that was previously loaded
into the browser as a result of executing an initial request. When the life cycle handles a postback, it
executes all the phases.
Apply request values: Components that hold a value, such as input fields, have their values applied
to their counterparts in the view tree. Events such as ValueChangeEvents (VCE) or ActionEvents
(AE) are queued for processing later at the end of this phase. A VCE means that a value has changed
for a specific UI component. An AE means that a button (or any UI component that is a source of an
action) was clicked.
Process validation: Validation and conversion logic is executed for each component (both
built-in validation and data conversion, or custom validation and conversion added onto the
components). If a validation error occurs, an error is reported, the life cycle halts, and the response is
rendered with validation error messages.
Update model: Any managed bean properties that are bound to UI components by using the Value
attribute are updated with the value of the component.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 21
Life Cycle: Postback (continued)
Invoke application: Queued ActionEvents are executed in this phase. For example, an action
method such as loginAction() is executed at this point.
Render response: Three things happen here1) a possible navigation is handled depending on the
outcome of the action method (if any), 2) the view tree renders itself to the client, and 3) the view
tree is saved for future requests.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 22
Copyright 2009, Oracle. All rights reserved.
Quiz
Backing beans are JSF-managed beans that are associated
with the UI components on a JSF page.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 23
Copyright 2009, Oracle. All rights reserved.
Using JSF Tag Libraries
JSF UI components are encapsulated in JSP
tag libraries:
Core: For application tasks,
such as validation, and data
type conversion
HTML: For rendering basic
HTML, such as input fields,
menus, tables, and buttons
Using JSF Tag Libraries
JDeveloper provides the standard JavaServer Faces (JSF) tag libraries for use in your JSF pages:
JSF Core tag library: Used with other components to perform core actions that do not depend
on a particular render kit
JSF HTML tag library: Used to represent HTML form controls and other basic HTML
elements. These controls display data or accept data from the user. This data is collected as part
of a form and is submitted to the server, usually when the user clicks a button.
To use any of the standard JavaServer Faces tags, you must include the taglib directives at the top
of each page containing the tags defined by the tag library. For example:
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
For a JSP document, the directives are different:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0
xmlns:h="http://java.sun.com/jsf/html
xmlns:f="http://java.sun.com/jsf/core">
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 24
Copyright 2009, Oracle. All rights reserved.
JSF Applications
A typical JSF application consists of:
One or more JSPs containing JSF components
A navigation model specified in the
faces-config.xml file
A set of managed beans that facilitate the UI logic of the
application
JSF Applications
Typically, a JSF application consists of a number of JSF pages connected by JSF navigation cases
that are defined in the faces-config.xml file. Each page probably uses a set of managed beans
to help facilitate page-specific UI application logic. It may also include other managed beans for
application-level methods, which are typically helper type methods that multiple pages may use.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 25
Copyright 2009, Oracle. All rights reserved.
JSF and JDeveloper 11g
JDeveloper provides many features for creating JSF
components:
JSF visual editing
JSF UI component
visual editing
Provides back-end
code generation
(double-click)
JSF Configuration Editor
for productive editing of faces-config.xml
JSF and JDeveloper 11g
JDeveloper is a feature-rich development environment for JSF. It provides visual editing for pages,
including drag-and-drop for JSF components. It also provides back-end code generation that creates
backing beans for you. It also keeps the backing beans in sync with components added to the page.
It also includes the JSF Configuration Editor that provides an easy way to see and modify any part of
the Faces configuration (managed beans, navigation cases, validators, converters, and so on).
When you create an application or page using JSF technology in JDeveloper, the necessary JSF tag
libraries and JAR files are automatically set up in the project properties. The faces-config.xml
file is created and the Faces Servlet and Faces Servlet Mapping definitions are automatically inserted
into a web.xml file.
In JDeveloper, you can develop applications with JSF technology when you:
Create a new application using a template, such as a Web application (JSF, EJB, or TopLink)
that uses the JSF technology scope
Create a new JSF Page Flow and Configuration file, or a JSF JSP file in an existing project
Add the JSF technology scope to an existing project in the project properties
Create a new project using an existing JSF application or .war file
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 26
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Diagram
JSF Navigation Diagram
JDeveloper includes a Visual Editor or diagrammer for the JSF navigation model, which you can also
edit directly in XML. The diagram in the slide depicts a series of rules, which are named events that
link pages (or views in JSF) together. If a command item, such as a button on the Main page, raises
an editProduct outcome, then the JSF framework acts as a page flow controller to forward (or
redirect, if required) the browser to the EditProduct page.
This is an example of where good tooling for JSF can make a real difference. Rendering the
navigation model as a diagram and enabling visual editing gives the developer both a productive way
of defining the application page flow and a visual document of the application page structure and
relationships.
If the application flow needs to changefor example, if a page needs to be addedthen the
relationships in this diagram can be redrawn, but the pages themselves do not have to be touched.
This is an implementation of the JSP Model 2 Architecture as pioneered by the Struts framework.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 27
Copyright 2009, Oracle. All rights reserved.
Adding to JSF with ADF Faces
Built on top of JSF APIs
Much larger component set:
over 100 types
More advanced and
interesting components
Partial-page rendering
Scrollable, sortable table
Rich feature set for customizing
applications
Uses Ajax, SVG, and
Flash
ADF model support
Runs on any JSF-compliant implementation
Adding to JSF with ADF Faces
Oracle ADF Faces is a rich set of user interface components based on the JavaServer Faces JSR.
Oracle ADF Faces uses the flexible JSF rendering architecture to combine the power of Ajax and JSF
to provide over 100 components with built-in functionalitysuch as data tables, hierarchical tables,
and color and date pickersthat can be customized and reused in your application.
Each component also offers complete customization, skinning, and support for internationalization
and accessibility. ADF Faces also provides a rich set of Flash- and SVG-enabled components that are
capable of rendering dynamic charts, graphs, gauges, and other graphics that provide real-time
updates. This built-in support for Ajax, SVG, and Flash enables developers to build rich UIs without
an extensive knowledge of the underlying technologies.
ADF Faces also simplifies the code necessary to connect application logic in existing business
services to UI components. Its components are JSR-227 compliant, enabling developers to easily
bind services to their UIs at design time.
ADF Faces components can be used in any IDE that supports JSF.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 28
Copyright 2009, Oracle. All rights reserved.
Using ADF Faces Layout Components
af:spacer
af:separator
af:panelSplitter
af:panelStretchLayo
ut
af:panelAccordion
af:panelFormLayout
af:panelTabbed
af:showDetail
af:panelGroupLayout
af:panelCollection
af:panelHeader
af:showDetailHeader
af:group
af:panelList
af:panelBox
af:panelBorderLayout
You can use the following components to achieve the desired
layout:
Using ADF Faces Layout Components
ADF Faces layout components include the following:
spacer, separator: To add blank space and divider lines
panelSplitter, panelStretchLayout: To enable automatic component stretching on
your pages
panelSplitter, panelAccordion: To create collapsible panes
panelFormLayout: To arrange items in columns or grids
panelTabbed: To create stacked tabs
showDetail: To hide and display groups of content
panelGroupLayout: To enable automatic scrollbars on your pages, and arrange items
horizontally or vertically
panelCollection: To add menus, toolbars, and status bars to data aggregation components
such as tables, trees, and tree tables
panelHeader, showDetailHeader: To create titled sections and subsections
group: To group semantically related components
panelList, panelBox: To create styled lists and content boxes
panelBorderLayout: To place items in fixed, peripheral areas around a central area
The following slides show how to use these components for various layout tasks.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 29
Copyright 2009, Oracle. All rights reserved.
Creating Resizable Panes
Panel Splitters
af:panelSplitter
Horizontal
orientation:
Vertical
orientation: Nested:
Creating Resizable Panes
When you have groups of unique content to present to users, consider using multiple panes separated
by adjustable splitters. When viewing the page in a client browser, users can change the size of panes
by dragging a splitter, and also choose to collapse or restore panes. When a pane is collapsed, its
contents are hidden; when a pane is restored, the contents are displayed.
The af:panelSplitter component enables you to organize contents into two panes separated
by an adjustable splitter. Clicking the arrow button on a splitter collapses or expands a pane (and its
contents) in the direction of the arrow. The value of the orientation attribute determines
whether the panes are horizontal (default) or vertical. The pane contents are specified in the facets
first and second. The slide shows a page divided into two horizontal panes (placed left to right),
and another page divided into two vertical panes (placed top to bottom). It also shows a nested
panelSplitter, created by a horizontal panelSplitter into the first facet of a vertical
panelSplitter.
The af:panelSplitter component uses geometry management to stretch its children
components at run time. This means when the user collapses one pane, the contents in the other pane
are explicitly resized to fill up the available space. If af:panelSplitter is the root component
for your page contents, you have to set the inlineStyle attribute on af:panelSplitter for
maximum stretching.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 30
Copyright 2009, Oracle. All rights reserved.
Creating Collapsible Panes
with the Panel Splitter Component
Attributes:
Both panes displayed, with
splitterPosition governing the
size of the first pane and splitter
arrow pointed toward the first pane
false false
false
true
true
collapsed
First pane hidden; second pane
stretches
false
Both panes displayed, with
splitterPosition governing the
size of the second pane and splitter
arrow pointed toward the second
pane
true
Second pane hidden; first pane
stretches
Behavior
true
positionedFromEnd
Creating Collapsible Panes with the Panel Splitter Component
Another feature of the panel splitter component is that users can collapse or restore its panes. When a
pane is collapsed, the pane contents are hidden; when a pane is restored, the contents are displayed.
The collapsed attribute on af:panelSplitter determines whether the splitter is in a
collapsed (hidden) state. By default, the collapsed attribute is false, which means both panes
are displayed. When the user clicks the arrow button on the splitter, collapsed is set to true and one
of the panes is hidden.
ADF Faces uses the collapsed and positionedFromEnd attributes to determine which pane
(that is, the first or second pane) to hide (collapse) when the user clicks the arrow button on the
splitter. When collapsed is true and positionedFromEnd is false, the first pane is
hidden and the second pane stretches to fill up the available space. When collapsed is true and
positionedFromEnd is true, the second pane is hidden instead. Visually, the user can know
which pane will be collapsed by looking at the direction of the arrow on the button. When the user
clicks the arrow button on the splitter, the pane collapses in the direction of the arrow. The
splitterPosition and collapsed attributes are persistablethat is, when the user moves
the splitter or collapses a pane, ADF Faces can implicitly persist the attribute value changes for the
component.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 31
Copyright 2009, Oracle. All rights reserved.
Creating Collapsible Panes
with the Panel Accordion
<af:panelAccordion>
<af:showDetailItem text="This is a pane"/>
<af:showDetailItem text="This is another pane"/>
</af:panelAccordion>
With default settings Characteristics of Panel
Accordion component:
Does not automatically
stretch it children
Panes cannot be resized at
run timeonly expand or
contract
Panes defined by
showDetailItem
Creating Collapsible Panes with the Panel Accordion Component
Another component that enables you to create collapsible panes is panel accordion. A series of
af:showDetailItem components inside af:panelAccordion make up the accordion panes,
with one af:showDetailItem component corresponding to one pane. The pane contents are the
children components inside each af:showDetailItem.
You can use more than one af:panelAccordion component on a page, typically in different
areas of the page, or nested. After adding the af:panelAccordion component, insert a series of
af:showDetailItem components to provide the panes by using one af:showDetailItem
for one pane. Then insert components into each af:showDetailItem to provide the pane
contents.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 32
Copyright 2009, Oracle. All rights reserved.
Panel Accordion Overflow
Automatic overflow icons
to display
content out of view
Panel Accordion Overflow
At run time, when available browser space is less than the space needed to display expanded pane
contents, ADF Faces automatically displays overflow icons that enable users to select and navigate to
those panes that are out of view. The slide shows overflow icons at the upper left (first example) and
at the lower right (second example). When the user clicks the overflow icon, ADF Faces displays the
overflow pop-up menu, as shown in the slide, for the user to select and navigate to a pane that is out
of view.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 33
Copyright 2009, Oracle. All rights reserved.
<af:showDetailItem
text="Browse Products"
inlineStyle="width:100%;
height:100%;" flex=1">
<af:showDetailItem
text="Selected Product"
inlineStyle="width:100%;
height:100%;" flex="2">
Setting Panel Accordion Properties
With discloseMany="true"
discloseNone="true"
Setting Panel Accordion Properties
The following properties govern the behavior of the panel accordion at run time:
discloseNone: Allow all panes to be collapsed at once (default is false)
discloseMany: Allow multiple panes to be expanded at once (default is false)
The following properties of showDetailItem affect the behavior of the accordion panes:
text: Specifies the text string to display as the title in the header of the container.
flex: Specifies a non-negative integer that determines how much space is distributed among
the af:showDetailItem components of one af:panelAccordion. By default, flex
is 0 (zero), that is, the pane contents of each af:showDetailItem are inflexible. To enable
flexible contents in a pane, specify a flex number larger than 0.
inflexibleHeight: Specifies the number of pixels a pane will use. Default is 100 pixels.
that is, if a pane has a flex value of 0 (zero), ADF Faces will use 100 pixels for that pane,
and then distribute the remaining space among the nonzero panes. If the contents of a pane
cannot fit within the af:panelAccordion container given the specified
inflexibleHeight value, ADF Faces automatically pushes out nearby contents into
overflow menus, as described previously.
Because neither of the above components automatically stretches its children, you may need to set
the width and height of any children of showDetailItem to 100%.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 34
Setting Panel Accordion Properties (continued)
The discloseMany attribute governs how many panes can be visible at once:
Set to true if you want users to be able to expand and see the contents of more than one pane
at the same time
By default, discloseMany is falsethat is, only one pane can be expanded at any one
time. For example, suppose there is one expanded pane A and one collapsed pane B when the
page is first loaded. If the user expands pane B, pane A will be collapsed because only one pane
can be expanded at any time.
The discloseNone attribute governs whether users can collapse all panes.
Set the discloseNone attribute to true to enable users to collapse all panes.
By default, discloseNone is falsethat is, one pane must remain expanded at any time.
You can add toolbars and toolbar buttons in the pane headers. To add toolbar buttons to a pane, insert
the af:toolbar component into the toolbar facet of the af:showDetailItem component
that defines that pane. Then insert the desired number of af:commandToolbarButton
components into the af:toolbar component. Although the toolbar facet is on
af:showDetailItem, it is the parent component af:panelAccordion that renders the
toolbar and its buttons.
To allow users to print the contents of a single pane, place the
af:showPrintablePageBehavior component (wrapped in af:commandButton) within
the af:showDetailItem whose pane contents you want users to be able to print.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 35
Copyright 2009, Oracle. All rights reserved.
Creating Titled Sections and Subsections
Panel header
component with
sections and
subsections:
af:panelHeader
Show detail header component with sections that expand or
collapse: af:showDetailHeader
Creating Titled Sections and Subsections
You may want to divide a page into sections and subsections, starting each section or subsection with
a header. The af:panelHeader component enables you to create sections and subsections with a
label and an icon at the top of each section or subsection header, as shown in the first example in the
slide.
To enable users to toggle the display of contents under each section or subsection header, use the
af:showDetailHeader component instead. This is similar to the af:panelHeader component,
except that it renders a toggle icon that lets users hide or display the section or subsection contents.
The second example in the slide shows a top section with its contents displayed, and a subsection
with its contents hidden. Partial page rendering (PPR), which is covered later in this lesson, is
automatically used to refresh a section of the page when the user selects to hide or show contents
under the header.
The disclosed attribute on af:showDetailHeader specifies whether to show or hide the
contents under its header. The default is falsethat is, the contents are hidden. When the user
clicks the toggle icon, an org.apache.myfaces.trinidad.event.DiscloserEvent is raised
to the server. If you want to perform special handling of this event, you can bind the components
disclosureListener attribute to a DisclosureListener method in a backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 36
Copyright 2009, Oracle. All rights reserved.
Grouping Related Components
Use af:group to:
Add multiple components to a facet
Group related
child components
<af:panelFormLayout>
<af:inputDate label="Pick a date"/>
<!-- first group -->
<af:group>
<af:selectManyCheckbox label=
"Select all that apply">
<af:selectItem label="Coffee" value="1"/>
//other select items
</af:selectManyCheckbox>
<af:inputText label="Special instructions"
rows="3"/>
</af:group>
<!-- Second group -->
<af:group>
<af:inputFile label="File to upload"/>
<af:inputText label="Enter passcode"/>
</af:group>
<af:inputText label="Comments" rows="3"/>
<af:spacer width="10" height="15"/>
<f:facet name="footer"/>
</af:panelFormLayout>
Grouping Semantically Related Components
The af:group component aggregates or groups together child components that are related
semantically. The af:group component does not provide any layout for its children. Used on its
own, the af:group component does not render anything; only the child components inside of
af:group render at run time.
You can use any number of af:group components to group related components together. For
example, you might want to group some of the input fields in a form layout created by
af:panelFormLayout, as shown in the example in the slide that groups two sets of child
components inside af:panelFormLayout.
When the af:group component is used as a child in a parent component that provides special
rendering for af:group children, then visible separators, such as bars or dotted lines, display
around the children of each af:group. For example, af:panelFormLayout and
af:toolbar support special rendering for af:group children. The example in the slide shows
how at run time the af:panelFormLayout component renders dotted separator lines before and
after the first and second af:group of children components. Children inside af:group are never
split across a column on a form.
The af:group component is especially useful when you need to group components under a
facet, because a facet may have only one child.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 37
Copyright 2009, Oracle. All rights reserved.
Arranging Items Around a Central Area
Arranging Items Around a Central Area
The af:panelBorderLayout component is a layout element for arranging components in
predefined, named areas around a center area. The center area is where direct children components of
af:panelBorderLayout render consecutively. In addition to the center area, the
af:panelBorderLayout component supports the following named areas, each of which is
defined by a facet bearing the name for the area:
top: Renders children above the center area
bottom: Renders children below the center area
start: Renders children at the left of the center area between the top and bottom facet
children, if the reading direction of the client browser is left-to-right. If the reading direction is
right-to-left, it renders children at the right of the center area.
end: Renders children at the right of the center area between the top and bottom facet
children, if the reading direction of the client browser is left-to-right. If the reading direction is
right-to-left, it renders children at the left of the center area.
left: Renders children at the left of the center area between top and bottom facet children.
If the reading direction is left-to-right, left has precedence over start if both left and
start facets are used. If the reading direction is right-to-left, left also has precedence over
end if both left and end facets are used.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 38
Arranging Items Around a Central Area (continued)
right: Renders children at the right of the center area between top and bottom facet
children. If the reading direction is left-to-right, right has precedence over end if both
right and end facets are used. If the reading direction is right-to-left, right also has
precedence over start if both right and start facets are used.
innerTop: Renders children above the center area, but below the top facet children
innerBottom: Renders children below the center area, but above the bottom facet children
innerLeft: Similar to left, but renders between innerTop and innerBottom, and
between left and the center area
innerRight: Similar to right, but renders between innerTop and innerBottom, and
between right and the center area
innerStart: Similar to innerLeft, if the reading direction is left-to-right; similar to
innerRight, if the reading direction is right-to-left
innerEnd: Similar to innerRight, if the reading direction is left-to-right; similar to
innerLeft, if the reading direction is right-to-left
Note: For BiDi support (right-to-left layout), Oracle Applications developers should not use the left
and right areas of af:panelBorderLayout. Start and end should be used instead of left and
right.
To add items in predefined areas using PanelBorderLayout:
1. Add the Panel Border Layout component to the JSF page.
2. To place content in the center area, insert the desired components inside
af:panelBorderLayout.
3. The children components are displayed consecutively in the order in which you inserted the
desired components. If you want some other type of layout for the children, wrap the
components inside af:panelGroupLayout.
4. To place the content in one of the named areas around the center area, do one of the following:
- If the facet is visible (for example, start or end), insert the desired components into
the facet, grouping multiple components because a facet can take only one child.
- If the facet is not visible, right-click af:panelBorderLayout, select Facets - Panel
Border Layout from the context menu, and choose a facet name from the list. Visible
facets are indicated by a check mark in front of the facet name. Insert the desired
components into the visible facet.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 39
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe the purpose of JavaServer Faces
Use JSF components
Explain the use of managed beans
Describe the life cycle of a JSF application
Explain the role of the JSF tag libraries
Describe how JDeveloper supports JSF
Create a JSF-based JSP in JDeveloper
Summary
JSF is a server-side component framework for Web applications that implements the MVC design
pattern.
JSF components have attributes, behaviors, and one or more renderers whose job it is to decide how
the component is displayed. The UI components may also be represented in managed beans, which
are Java objects that are managed in the faces-config.xml file. Managed beans provide a code
point for processing or UI manipulation. You can use Expression Language to bind UI components
and actions to managed beans.
The life cycle for the initial request of a JSF JSP includes creating a server-side tree based on the
components on the page, and then rendering the response. When the user submits a form on the page,
a postback occurs, in which values of UI components are applied to their counterparts in the server-
side tree, validation and conversion logic is executed for each component, the business model is
updated, action events are executed, and then finally the response is rendered, which may include
navigation to another page.
There are two basic tag libraries for defining JSF components: JSF Core for application tasks and JSF
HTML for rendering basic HTML. JDeveloper provides these tags from the Component Palette.
JDeveloper also provides visual editing of the JSF JSP and faces-config.xml file, which
includes the JSF Navigation Diagram.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 40
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers the following topics:
Creating a Managed Bean to support a page
Creating a basic JSF page
Adding layout components to the JSF page
Copyright 2009, Oracle. All rights reserved.
Planning Navigation and Page Flow
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Use a JavaServer Faces (JSF) Navigation diagram to plan
the pages of an application and the navigation between
them
Describe JSF Navigation
Describe the types of JSF Navigation cases
Create a backing bean for a JSF page
Objectives
In this lesson, you learn how to use JSF to control navigational and data flow within an
application. The JSF Navigation diagram provides a way to visually design navigation and flow,
handle interactions with business services, and determine which page to display. Additionally,
JSF components are mapped to managed beans, which control user actions on the components
themselves.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 3
Copyright 2009, Oracle. All rights reserved.
<body>
<form action="myNewPage.html">
<button type="button"/>
</form>
<a href="http://myNewPage.html">
Go To My New Page
</a>
</body>
Traditional Navigation
In traditional navigation, a button or hyperlink is used to
navigate to a specific page.
Traditional Navigation
This type of navigation is also referred to as the Model 1 type. In both cases, if the physical
location of the page is changed, you have to modify all the links and forms that use it.
JSF controls the pages using an XML file that contains all the navigation mechanisms.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 4
Copyright 2009, Oracle. All rights reserved.
What Is JSF Navigation?
JSF Navigation is defined through rules.
Rules use outcomes to determine which page is displayed
in a user interface (UI) event.
Rules can be defined as:
Static
Dynamic
They are defined in faces-config.xml.
What Is JSF Navigation?
JSF Navigation is a set of rules that define navigation from view to view. Generally, you define
one navigation rule per page. Each navigation rule may have several valid outcomes. For
example, a login page may have several outcomes: one for a successful login, and another for a
login failure. Both of these outcomes are defined in the navigation rule.
The rules can be defined as static or dynamic. Static rules are an explicit reference to an
outcome. A dynamic rule is a rule that is bound to a method that may return one of several
possible outcomes.
Navigation rule definitions are stored in the JSF configuration file (faces-config.xml).
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 5
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
myNewPage
firstPage.jsp myNewPage.jsp
success
firstPage
Button
JSF Navigation Rules
JSF Navigation: Example
In JavaServer Faces, navigation between application pages is not hard coded in the file, but is
defined by a set of rules. Navigation rules determine the next page that is to be displayed, when
a user clicks a navigation component, such as a button or a hyperlink.
A navigation rule defines the navigation from one page to one or more other pages.
Each navigation rule can have one or more cases, which define where a user can go from that
page. For example, if a page has links to several other pages in the application, you can create a
single navigation rule for that page and one navigation case for each link to the different pages.
The rule itself can define the navigation from:
A specific JSF page
All pages whose paths match a specified pattern, such as all the pages in one directory,
which is called a pattern-based rule
All pages in an application, which is called a global navigation rule
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 6
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Rules
Navigation rules are stored in faces-config.xml.
Navigation rules can be defined by using:
The faces-config console
The Pageflow diagrammer
The faces-config.xml file directly
JSF Navigation Rules
Navigation rule definitions are stored in the JSF configuration file (faces-config.xml).
You can define the rules directly in the configuration file, or you can use the JSF Navigation
Modeler and the JSF Configuration Editor in JDeveloper. Oracle recommends that you use
Navigation Modeler and Configuration Editor, because these tools:
Provide a GUI environment for modeling and editing the navigation between application
pages
Enable you to map out your application navigation by using a visual diagram of pages and
navigation links
Update the faces-config.xml file for you automatically
Use the navigation modeler to initially create navigation rules from specific pages to one or
more other pages in the application. Use the configuration editor to create global or pattern-
based rules for multiple pages, create default navigation cases, and edit navigation rules.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 7
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Rules
Example:
/login.jsp is the navigation rule with two cases.
login.jsp is managed by the login backing bean.
loginAction() is the method that returns success or
failure:
If the method returns
success, forward the user to
/successPage.jsp.
If the method returns
failure, forward the
user to /failurePage.jsp.
JSF Navigation Rules (continued)
In this example, there is one navigation rule with two cases. The outcome is returned from the
loginAction() method in the login backing bean. The method checks the values of the
username and password. If the combination is valid, the method returns an outcome of
success. If the combination is not valid, the method returns failure. The appropriate
navigation case is then used by JSF to display the correct page. The following is the XML:
<navigation-rule>
<from-view-id>login.jsp</from-view-id>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/successPage.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/failurePage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 8
Copyright 2009, Oracle. All rights reserved.
faces-config Console
faces-config Console
This console provides a visual way to edit all elements of faces-config.xml, as opposed to
a navigation model.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 9
Copyright 2009, Oracle. All rights reserved.
faces-config.xml

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/successPage.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/failurePage.jsp</to-view-id>
</navigation-case>
</navigation-rule>

faces-config.xml
You can use the action to further qualify the result of a particular outcome using a from-action
case. The following code shows how the from-action option is used:
<navigation-rule>
<from-view-id>login.jsp</from-view-id>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/successPage.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/failurePage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 10
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Modeler
You create a JSF Navigation Diagram by dragging elements
from the Component Palette. The faces-config.xml diagram is
automatically updated.
JSF Navigation Modeler
The JSF Navigation Modeler is the tool used for creating a navigation diagram. Notice in the
slide that the Component Palette automatically displays the JSF Navigation Modeler
components. You add components to the diagram by dragging them from the Component Palette
to the diagram.
When you first create a JSF Page Flow and Configuration file (faces-config.xml),
JDeveloper also creates a diagram file (faces.config.oxd_faces) to hold the diagram
details such as layout and annotations. JDeveloper always maintains this diagram file alongside
the faces-config.xml file, which holds all the settings needed by your application.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 11
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Diagram
With the JSF Navigation Diagrammer, you can visually design
your application from a birds eye view.
JSF Navigation Diagram
The JSF Navigation diagram is your workbench for:
Planning out the pages and the navigation between them for your JSF application
Creating new pages for your application
Defining the navigation rules and cases for navigating around the application pages
Including existing pages in your application flow by dragging them
Annotating the diagram with general notes and notes attached to individual elements
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 12
Copyright 2009, Oracle. All rights reserved.
Navigation Elements
<navigation-rule>
<from-view-id>
<navigation-case>
<navigation-rule>
<from-view-id>/Main.jspx</from-view-id>
<navigation-case>
<from-outcome>addProduct</from-outcome>
<to-view-id>/addProduct.jspx</to-view-id>
</navigation-case>
</navigation-rule>
<from-action>
<from-outcome>
<to-view-id>
Navigation Elements
A navigation rule consists of the following elements:
<navigation-rule>: The wrapper element for the navigation cases
<from-view-id>: Contains either the complete page identifier (the context-sensitive
relative path to the page) or a page identifier prefix ending with the asterisk (*) wildcard
character. If you use the wildcard character, the rule applies to all pages that match the
wildcard pattern. To make a global rule that applies to all pages, leave this element blank.
<navigation-case>: The wrapper element for each case in the navigation rule. Each
case defines the different navigation paths from the same page.
<from-action>: An optional element that limits the application of the rule only to
outcomes from the specified action method. The action method is specified as an
Expression Language (EL) binding expressionfor example,
#{backing_addProduct.cancelButton_action}. JDeveloper displays a list of
valid binding expressions for you to choose from.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 13
Navigation Elements (continued)
<from-outcome>: Contains an outcome value that is matched against values specified
in the action attribute of UI components. Later in the lesson, you see how the outcome
value is referenced in a UI component either explicitly or dynamically through an action
method return.
<to-view-id>: Contains the complete page identifier of the page to which the
navigation is routed when the rule is implemented
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 14
Copyright 2009, Oracle. All rights reserved.
Global Rules
Global rules apply to all pages in an application.
Examples: Help page, Home page, Contact page
Define <from-view-id> with an asterisk (*) wildcard.
Define <from-outcome> (help).
Define <to-view-id> (help.jsp).
Any page in the application that returns help displays
help.jsp.
Global Rules
Global rules are navigation rules that can be accessed from any page in the application. JSF does
not force you to define every possible event. If you have common navigation eventsfor
instance, Logoutyou can use wildcards in the <from-view-id> definition to specify that
any page matching this pattern can implement this outcome.
An example of a good use of a global rule is a Help page. Any page in the application can access
the Help page. You define a global rule by setting the <from-view-id> to a wildcard (*).
You can also define a global rule by completely omitting the <from-view-id> tag.
In the following example, any page in the path /faces/ that returns an outcome of help is
forwarded to help.jsp.
...
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>help</from-outcome>
<to-view-id>/menu/help.jsp</to-view-id>
</navigation-case>
...
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 15
Copyright 2009, Oracle. All rights reserved.
Pattern-Based Rules
Pattern-based rules are similar to global rules.
Include a pattern for the <from-view-id> element:
<from-view-id>/staffPages/*
This rule is used by all pages in the /staffPages path.
<navigation-rule>
<from-view-id>/staffPages/*</from-view-id>
<navigation-case>
<from-outcome>help</from-outcome>
<to-view-id>/menu/staffHelp.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Pattern-Based Rules
You can also define rules that apply to a specific set of pages, by including a path and wildcard
in the <from-view-id> tag. The rule includes all the same elements as a global navigation
case. In this example, all the pages in the /staffPages path navigate to staffHelp.jsp
when the outcome from the page is help. This technique is useful where several pages should
navigate to a single common outcome page, such as a Help page. Rather than adding multiple
navigation cases, you add a single global navigation rule to the common page.
<navigation-rule>
<from-view-id>/staffPages/*</from-view-id>
<navigation-case>
<from-outcome>help</from-outcome>
<to-view-id>/menu/staffHelp.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 16
Copyright 2009, Oracle. All rights reserved.
JSF: Example
Sample JSF login application:
JSF: Example
This is an example of a simple JSF page. The page has two input fields and a button. As
discussed in the following slides, the page has an associated managed bean that has access to the
values entered on the page. When the user clicks the Login button, JSF calls the associated
action, which is a method in the bean. This method tests the values and determines whether the
user is valid. If the login values are valid, the user is directed to a success page. Otherwise, the
user is directed to a failure page.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 17
Copyright 2009, Oracle. All rights reserved.
JSF: Example
A simple example of a JSF Login Application:
loginAction
login.jsp
Success
success.jsp
Failure
failure.jsp
JSF: Example (continued)
This is the JSF Case Navigation for this application. The simple case is that the user input values
are valid, so navigation proceeds to the success page. If the values are not valid, navigation is to
the failure page.
If the values that the user entered fail a JSF Validator, the user stays on the login page to change
the values.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 18
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
UI components and value binding to a managed bean:
login.jsp
<h:InputText value="#{Login.userId}"/>
<h:InputSecret value="#{Login.password}"/>
<h:commandButton action="#{Login.login}"/>
Login: A managed bean with the userId and
password fields and the login()method
Submit
JSF Navigation: Example
Both the fields use value binding to associate the values on the page with the managed bean. The
command button has an action associated with Login.login, which is a method in the bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 19
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
A command UI component bound to an action:
login.jsp
<h:commandButton action="#{Login.loginAction}"/>
Login: A managed bean (Login.java) with an action
method called loginAction()
Returns string: failure or success
JSF Navigation: Example (continued)
In the example, a UI component (commandButton) has been bound to a managed bean,
Login.java, which contains the loginAction() method.
At run time, the JSF default implementation reads the navigation rules in the faces-
config.xml file and calls the NavigationHandler class, which evaluates the rules and
determines which page to display.
When evaluating which navigation rules to execute, the navigation handler looks at:
The ID of the current page
The action method used to handle the link. In this case, it is loginAction().
The outcome string value of the action attribute, or the string returned by the action
method. In this example, it is either failure or success.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 20
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
public String loginAction() {
String userId =
(String)this.getUserId().getValue();
String password =
(String)this.getPassword().getValue();
if (userId.equalsIgnoreCase("gary") &
password.equalsIgnoreCase("test")) {
return "success"; }
return "failure";
}
JSF Navigation: Example (continued)
The slide shows the code for the loginAction() method. The method checks the value of
the user ID and password. If they match the defined values, the method returns success;
otherwise it returns failure. JSF then checks for an outcome that matches the return string and
displays the view associated with that outcome.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 21
Copyright 2009, Oracle. All rights reserved.
Using the JSF Configuration Editor
Using the JSF Configuration Editor
You use the Navigation Modeler to initially create navigation rules from specific pages to one or
more other pages in the application. You then use the Configuration Editor to create global or
pattern-based rules for multiple pages, create default navigation cases, and edit navigation rules.
You invoke the editor by clicking the Overview tab at the bottom of the diagram page in the
Visual Editor. If you click the second option, Navigation Rules, in the list on the top left, you
can see rules that have been defined through the diagram. You can also add new rules here.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 22
Copyright 2009, Oracle. All rights reserved.
Managed Beans
Managed beans can:
Store state
Execute a Java routine
Define a handler for event listeners
They have no-argument constructors.
Lazy initialization is performed by JavaServer Faces.
Access scope may be none, request, application, or
session.
Backing beans:
Are special types of managed beans
Contain getter and setter methods for UI components
Managed Beans
If you want to code your own update routine, you can place the code in a managed bean.
Managed beans are objects that are defined in a configuration file (faces-config.xml, by
default). They can be Plain Old Java Objects (POJO), lists, or maps. The classes that can be used
as managed beans have constructors with empty arguments. The managed-bean element in
the faces-config.xml file represents a JavaBean of a particular class, which is
dynamically instantiated at run time (by the default VariableResolver implementation), if
it is referenced as the first element of a value-binding expression, and if no corresponding bean
can be identified in any scope. In addition to the managed bean creation and the optional storing
into the specified scope, the nested managed-property element can be used to initialize the
contents of settable JavaBeans properties of the created instance.
Managed bean configuration in faces-config.xml:
<!ELEMENT managed-bean (description*, display-name*, icon*,
managed-bean name, managed-bean-class, managed-bean-scope,
(managed-property* | map-entries | list-entries))>
A special type of managed bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 23
Managed Beans (continued)
A managed-bean element must contain the following elements:
- managed-bean-name: Specifies the name that is used to refer to the
JavaBean throughout the application
- managed-bean-class: Contains the fully qualified class name for the
JavaBean
- managed-bean-scope: Defines the scope of the JavaBean. Some possible
values are application, session, request, or none.
A managed-bean element can optionally contain any number of descriptions,
display-name, icon, and managed-property/map-entries/list-
entries elements.
If the value of the managed-bean-scope element is something other than none, the
JavaBean created is stored in the corresponding object. For example, if the value is
session, the JavaBean is stored in the session object of a given user.
If you define the bean with a scope of none, the bean is instantiated each time it is
referenced. You can use a scope of none when a managed bean references another managed
bean; if the referenced bean is supposed to be created only when it is referenced, it should be
defined with a scope of none.
Uses of Managed Beans
Managed beans are typically used to:
Store state (for example, information about the authenticated user)
Execute Java routines (for example, by clicking a button)
Define handlers for event listeners
Creating Managed Beans
There are three ways to create managed beans:
You can create Java classes in a project and then configure them as managed beans.
You can create managed beans when binding a Command button.
When you create a new page, you are given the opportunity to automatically expose UI
components in a new managed bean. If you select this option, JDeveloper creates a
managed bean, and accessors are automatically added for all components that you add
to the page. This type of managed bean for the UI components on a page is called a
backing bean.
Backing Beans
Backing beans are a special type of managed beans used to contain getter and setter methods
for UI components.
If you choose to automatically expose UI components in a managed bean when you design a
JSF page, JDeveloper automatically synchronizes the components that you add or modify
with the backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 24
Copyright 2009, Oracle. All rights reserved.
Creating Managed Beans
Entry in faces-config.xml:
<managed-bean>
<managed-bean-name>productBrowsingBean</managed-bean-name>
<managed-bean-class>ui.backing.ProductBrowsingBean
</managed-bean-class>
<managed-bean-scope> session </managed-bean-scope>
</managed-bean>
Creating Managed Beans
You configure managed beans in the faces-config.xml file.
1. Double-click the faces-config.xml file in the Navigator.
2. Click the Overview tab to display the JSF Configuration Editor.
3. In the element list on the left, select Managed Beans.
4. Click the New button on the right to open the Create Managed Bean dialog box.
5. Provide the name and fully qualified class path for the bean. Select a scope, select the
Generate Java File check box, and click OK.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 25
Copyright 2009, Oracle. All rights reserved.
Managed Bean: Example
Definition:
Usage on a page:
Usage in code:
<managed-bean>
<managed-bean-name>userbean</managed-bean-name>
<managed-bean-class>com.oracle.sample.User</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<h:inputText value="#{userbean.name}"/>
Application app =
FacesContext.getCurrentInstance().getApplication();
ValueBinding bind = app.createValueBinding("#{userbean}");
User user = (User)bind.getValue(ctx);
Managed Bean
The definition of a bean is simple. You provide the following information:
An alias (userbean in the example)
The class to instantiate (com.oracle.sample.User in the example)
The lifespan (request in this example)
Then the usage of that managed bean is through Expression Language (EL).
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 26
Copyright 2009, Oracle. All rights reserved.
Setting Managed Bean Scope
Each managed bean has a scope:
Application
Session
Request
None
Setting Managed Bean Scope
Application: The bean is available for the duration of the Web application. This is helpful for
global beans such as Lightweight Directory Access Protocol (LDAP) directories.
Session: The bean is available to the client throughout the clients session.
Request: The bean is available from the time it is instantiated until a response is sent back to the
client. This is usually the life of the current page.
None: The bean is instantiated each time it is referenced. This is helpful if the bean is referenced
within another bean.
Managed properties are any properties of the bean that you would like populated with a value
when the bean is instantiated. The set() method for each declared property is run after the
bean is constructed. When you configure a managed property for a managed bean, you declare
the property name, its class type, and its default value. If the default is null, you use a <null-
value> element. The value can also be another bean referenced in a JSF EL expression. When
the parent bean is initialized, the nested bean declared in the value is also created and initialized.
When nesting a bean, you must ensure that it exists in the faces-config.xml file and that
the scopes are compatible.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 27
Copyright 2009, Oracle. All rights reserved.
Relationships Between Managed Beans
Managed beans can access other beans:
Yes Yes Yes Yes request
No Yes Yes Yes session
No No Yes Yes application
No No No Yes none
request session application none
Access beans in scope Beans in
scope
Relationships Between Managed Beans
The table in the slide shows which scopes of managed beans can access other managed beans
with the same or a different scope. Note that request is the only scope that can access
managed beans of any scope.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 28
Copyright 2009, Oracle. All rights reserved.
Managed Properties
Managed bean variables that are exposed through getter
and setter methods
Configured in faces-config.xml
Possible values:
Null
Literal string
Lists and maps
Value binding expression (EL)
<!ELEMENT managed-property (description*, display-
name*, icon*, property-name, property-class?,
(map-entries|null-value|value|list-entries))>
Managed Properties
Managed properties are bean variables that are exposed through setter and getter methods for
write and read access. All variables not explicitly set as managed properties retain the default
values upon bean instantiation.
The managed-property element, nested within the <managed-bean> element,
represents an individual property of a managed bean. A managed property calls the equivalent
setter method of the bean on bean initialization.
Managed properties must have a name and a value. The optional property class does not need to
be mentioned for simple types because JSF can figure it out. The optional description, display
name, and icon attributes are for tools to display the property and have no meaning for the JSF
application at run time.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 29
Copyright 2009, Oracle. All rights reserved.
Managed Properties: Examples
Literal string:
EL accessing a managed bean:
<managed-bean>
<managed-property>
<property-name>label</property-name>
<value>Hello World</value>
</managed-property>
<managed-bean>
<managed-property>
<property-name>label</property-name>
<value>#{UserInfo['firstname']}</value>
</managed-property>
Managed Properties: Examples
Expression Language (EL) can be used within the faces-config.xml file to initialize the
value of a managed property. EL can reference any object that is in the scope, including
previously defined managed beans.
Managed beans and managed bean properties can also be initialized as lists or maps, provided
that the bean or property type is a List or Map, or implements java.util.Map or
java.util.List.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 30
Copyright 2009, Oracle. All rights reserved.
Managed Properties: Examples
Populating a list:
Use <map-entries> to specify managed properties that are
of the Map type.
<managed-bean>

<managed-property>
<property-name>bookmarks</property-name>
<list-entries>
<value>http://otn.oracle.com/products/jev</value>
<value>http://otn.oracle.com/products/ias</value>
</list-entries>
</managed-property>

Managed Properties: Examples (continued)


Map entry example:
<managed-bean>
...
<managed-property>
<property-name>bookmarks</property-name>
<map-entries>
<map-entry>
<key>JDeveloper Home</key>
<value>http://otn.oracle.com/products/jdev</value>
</map-entry>
<map-entry>
<key>OracleAs Home</key>
<value>http://otn.oracle.com/products/ias</value>
<map-entry>
</map-entries>
</managed-property>
...
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 31
Copyright 2009, Oracle. All rights reserved.
Using the Managed Bean on the JSF Page
Access UI components and values

Getter for userId


Setter for userId

Login.java managed bean:

<h:outputText value="#{Login.userId.value}"
binding="#{SuccessPage.outputText1}"
id="outputText1"
/>
successPage.jsp:
Using the Managed Bean on the JSF Page
After a managed bean is defined with the relevant properties and methods, you use JSF EL
expressions (such as <h:outputText value="#{Login.userId.value}" in the
slide) to bind a UI component attribute to the appropriate property (or method) in the bean. In
addition to value and method binding, you can also bind the UI components instance to a bean
property by using the binding attribute.
In the example above, successPage.jsp includes an outputText field with the ID of
outputText1. It retrieves its value from the Login managed bean property userId. It is also
bound to the outputText1 property of the SuccessPage backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 32
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Use a JSF Navigation Diagram to plan the pages of an
application and the navigation between them
Describe JSF Navigation
Define types of JSF Navigation cases
Create a backing bean for a JSF page
Summary
JSF Navigation is a set of rules that define how users navigate from one view to another. The
rules use outcomes that may be static or dynamic. Navigation rules may be global to the
application as a whole, or may apply to a specific set of pages. You can use the JSF Navigation
Diagrammer to visually plan the pages of an application and to define the navigation paths
between them. This diagram is a Visual Editor for the faces-config.xml file for pages and
navigation rules.
Managed beans are also defined in faces-config.xml and can be configured in the JSF
Configuration Editor. Backing beans are a special type of managed beans to interact with the UI
components and the model. You can create a managed bean automatically when you create a
page. You can create managed beans by associating class files with a named managed bean in
the JSF Configuration Editor. Because managed beans can have scope, you can use them to store
information for the duration of the request, application, or session.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 33
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Using a JSF Navigation Diagram to model page flow in an
application
Creating the JSF pages of the application
Binding components to a managed bean

Вам также может понравиться