Professional Documents
Culture Documents
Applications
D17247GC11
Edition 1.1
June 2005
D18757
Authors Copyright © 2005, Oracle. All rights reserved.
Publisher All other products or company names are used for identification purposes only, and
may be trademarks of their respective owners.
Joseph Fernandez
Contents
Preface
1 Introduction
Course Objectives 1-2
Course Environment 1-4
Course Overview 1-5
About the Course Applications 1-8
Order Entry Schema 1-9
Human Resources (HR) Schema 1-10
HR Application Flow Diagram 1-11
Summary 1-12
2 J2EE Overview
Objectives 2-2
Java 2, Enterprise Edition Platform 2-3
J2EE Platform 2-4
Benefits of the J2EE Platform 2-5
J2EE Components 2-7
J2EE 1.3 Components 2-8
J2EE Architecture 2-9
Client-Tier Components 2-10
J2EE Web-Tier Components 2-11
What Is a Servlet? 2-13
What Is a JavaServer Page (JSP)? 2-14
Web-Tier Components: Summary 2-15
Business-Tier Components 2-16
Enterprise JavaBeans (EJB) 2-17
J2EE Communication APIs 2-18
J2EE Server 2-19
Oracle Application Server 10g Containers for J2EE (OC4J) 2-21
J2EE Applications 2-22
Packaging J2EE Application Components 2-23
JARs 2-24
WARs 2-25
EJB JARs 2-26
EARs 2-27
EAR File Structure for a J2EE Application: Example 2-28
OC4J Architecture 2-29
OC4J Server Configuration Files 2-30
Relation of Configuration Files 2-31
iii
Data Sources 2-32
Application Logging 2-33
J2EE Application Deployment to Oracle Application Server 10g 2-34
Oracle Enterprise Manager 2-35
JDeveloper and J2EE 2-36
Oracle JDeveloper 10g Environment 2-37
Oracle JDeveloper 10g Visual Design Tools 2-38
Summary 2-39
Practice 2-1: Overview 2-40
iv
Handling Input: The Servlet 4-17
Initialization and Destruction 4-18
Error Handling 4-19
Debugging a Servlet 4-20
SingleThreadModel 4-21
JDeveloper Environment 4-23
Servlet Mapping 4-24
Servlet Mapping in JDeveloper 4-25
Invoking a Servlet 4-26
Specifying J2EE Web Module Settings 4-27
Creating a Connection to Oracle Application Server 10g 4-28
Deploying to OC4J 4-29
Summary 4-30
Practices 4-1, 4-2, and 4-3: Overview 4-31
v
Cookies 6-12
Setting Cookies 6-13
Retrieving Cookies 6-14
About State Preservation 6-15
State Preservation: Example 6-16
ServletContext 6-17
RequestDispatcher 6-18
RequestDispatcher: Example 6-19
Servlet Filters 6-20
Using Filters 6-21
doFilter() Method 6-22
Using Filters 6-23
Configuring Filters 6-24
Application Lifecycle Events 6-25
ServletContext Events 6-26
HttpSession Events 6-27
Example of an Event Listener 6-28
Error Handling 6-29
Summary 6-30
Practices 6-1 and 6-2: Overview 6-31
vi
Invoking JSPs 8-5
The Date JSP 8-6
The Date Servlet 8-7
Automated JSP Features 8-8
JSP Life Cycle 8-9
Basic JSP Elements 8-10
Declarations 8-11
Expressions 8-12
Scriptlets 8-13
Implicit Objects 8-14
Example 8-16
Directives 8-18
include: Example 8-19
page Directive 8-20
JSP and JavaBeans 8-22
Using JavaBeans with JSP 8-23
scope Attribute of <jsp:useBean> Tag 8-25
Accessing and Setting Bean Property 8-26
JSP XML Document 8-28
Traditional Syntax Versus XML Syntax 8-29
JDeveloper and JSPs 8-31
Creating JSPs Visually 8-32
JSP Tag Insight 8-33
Summary 8-34
Practices 8-1, 8-2, and 8-3: Overview 8-35
vii
Expression Language 9-19
Using Iteration Tags 9-20
Using the URL Tags 9-21
XML Tag Library 9-23
SQL Tag Library 9-24
Accessing a Database with SQL Tags 9-25
Querying Using SQL Tags 9-26
Inserting, Updating, and Deleting Data 9-27
Formatting Tags 9-28
Internationalization Concepts 9-29
Internationalizing Strings 9-30
Formatting Numbers and Dates 9-31
Transforming XML Documents 9-34
JSTL in JDeveloper 9-35
Summary 9-36
Practice 9-1: Overview 9-37
10 Communicating in J2EE
Objectives 10-2
Overview of RMI 10-3
Role of RMI in J2EE 10-4
Communication in a J2EE Environment 10-5
How Clients Locate a Distributed Component 10-7
Java Naming and Directory Interface (JNDI) 10-8
J2EE Container and JNDI Interface 10-9
Naming Service 10-10
JNDI Terminology 10-11
Main JNDI Class and Interface
Accessing an Object in JNDI Namespace 10-13
Getting the JNDI InitialContext 10-14
Initial Context Factories 10-16
lookup() Method 10-17
Obtaining a Reference to a Local Resource 10-18
Obtaining a Reference to a Remote Resource 10-19
Setting JNDI Environment Properties 10-20
Using RMI over HTTP Tunneling 10-24
Using Environment References with JNDI 10-25
Configuring Environment Variables 10-26
Specifying an EJB Reference 10-28
Configuring EJB References 10-29
viii
Configuring Data Source References 10-31
Summary 10-33
Practice 10-1: Overview 10-34
ix
The Session Bean Class 12-15
The Session Bean Class: Business Methods 12-17
Bean Class for the Stateless Session Bean 12-18
Deployment Descriptor 12-19
Client Application 12-20
Client Application for Stateless Session Beans 12-21
Life Cycle of a Stateful Session Bean 12-25
Home Interface for Stateful Session Bean 12-26
Client Application for Stateful Session Bean 12-27
Summary 12-28
Practices 12-1 and 12-2: Overview 12-29
x
Features of CMP Entity Beans 14-5
Implementing Methods in CMP Beans and BMP Beans 14-7
Developing a CMP Entity Bean 14-9
CMP Bean: Example 14-10
Bean Class of a CMP EJB: CMP Fields 14-11
Remote Interface: Departments 14-12
Home Interface: DepartmentsHome 14-13
Bean Class: DepartmentsBean 14-14
Deployment Descriptor ejb-jar.xml 14-17
Mapping CMP Fields to Database Table Columns 14-21
Default Mapping of CMP Fields to Database Table Columns 14-22
Explicit Mapping of CMP Fields to Database Table Columns 14-23
Client for Departments Bean 14-25
Summary 14-28
Practice 14-1: Overview
xi
Using JDeveloper to Create CMR Beans 15-31
Summary 15-32
Practice 15: Overview
xii
Passing Arguments to the EJB Method 17-7
Creating an EJB Reference 17-8
Creating Local Clients for EJBs 17-9
ejb-local-ref Element 17-10
EJB Tags 17-11
useHome Tag 17-12
useBean Tag 17-13
createBean Tag 17-14
iterate Tag 17-15
Using the EJB Tags 17-16
Deploying an Application: Web Tier 17-17
Deploying an Application: EJB Tier 17-18
Deploying an Application: EAR File 17-19
Deploying from Oracle Enterprise Manager 17-20
Summary 17-21
Practice 17-1 and 17-2: Overview 17-22
xiii
Utilizing External Web Services from JDeveloper 18-34
Summary 18-35
Practice 18-1: Overview 18-36
xiv
Client Authentication 20-21
EJB Client Authentication with the jndi.properties file 20-22
EJB Client Authentication with a Hashtable 20-23
Setting Access Control with JDeveloper 20-24
Creating Web Application Security Roles 20-25
Web Application Login Authentication 20-26
Web Application Authorization 20-27
Creating EJB Security Roles 20-28
Setting Method Permissions 20-29
Method Access in EJB Deployment Descriptors 20-30
Creating a Mapping for the Logical Roles 20-31
Mapping JAZN Identities to a Logical Role 20-32
Mapping Results in orion-ejb-jar.xml 20-34
Accessing the EJB with New Permissions 20-35
Summary 20-36
Practice 20-1: Overview 20-37
xv
Single-Phase Commit 21-27
Data Source Revisited 21-28
Default data-sources.xml 21-29
Emulated Versus Nonemulated Data Sources 21-30
Retrieve Connection to Data Source 21-31
Global Transaction Resource Request Flow 21-33
Resource Request Flow 21-34
Enlisting Database Resources 21-36
Summary 21-38
Practice 21-1: Overview 21-39
xvi
Preface
Preface - 2
Profile
Preface - 3
Typographic Conventions
Bold italic Glossary terms (if there is a The algorithm inserts the new key.
glossary)
Preface - 4
Typographic Conventions (continued)
Quotation Lesson and chapter This subject is covered in Unit II, Lesson 3, “Working with
marks titles in cross Objects.”
references, interface
elements with long Select the “Include a reusable module component” and
names that have only click Finish.
initial caps
Use the “WHERE clause of query” property.
Preface - 5
Preface - 6
Introduction
Course Objectives
Many businesses rely on the Internet and Web applications for their daily business. Oracle
provides several tools that you can use to easily develop and deploy these applications. The
purpose of this course is to teach you how to develop applications by using the J2EE
components. These components include servlets, JSP, and EJB. Additionally, you should be
able to create applications that adhere to the MVC architecture, which provides easily
maintainable components.
Course Environment
In this course, you will use the Oracle JDeveloper 10g integrated design tool to develop
J2EE components. These components will be deployed to the Oracle Application Server 10g
Containers for J2EE (OC4J) server. The OC4J server is provided within JDeveloper, and is
also contained in a full installation of Oracle Application Server 10g. You will deploy
applications to both locations. Additionally, components will access the Oracle database
10g.
ORDER_ITEMS_ORDER_ID_FK INVENTORIES_PRODUCT_ID_FK
ORDER_ITEMS_PRODUCT_ID_FK INVENTORIES_WAREHOUSES_FK
ORDERS_CUSTOMER_ID_FK
EMP_DEPT_FK
DEPT_LOC_FK
DEPT_MGR_FK
*
JHIST_DEPT_FK
JHIST_JOB_FK
COUNTR_REG_FK
LOC_C_ID_FK
Employee entity
No
View
Process Administrator?
employees
log in
process
Yes
Insert
employees
process
Summary
In this course, you learn how to create J2EE applications by using servlets, JSP, EJB, and
Web services. You learn how to design and develop J2EE applications by using Oracle
JDeveloper 10g, and make decisions about when to use the various J2EE components.
Additionally, the applications that you create are deployed to Oracle Application Server 10g.
Objectives
This lesson discusses each of the components of the J2EE architecture and examines its
purpose in a J2EE application. J2EE applications are deployed to a J2EE server such as
Oracle Application Server 10g. This lesson also describes the configuration and structure of
Oracle Application Server 10g Containers for J2EE.
Servlet
Enterprise
Application Beans
EIS tier
EJB clients EJB components
J2EE Platform
J2EE defines a platform for developing, deploying, and executing applications in a
multitiered, distributed application model. That is, the application logic of a J2EE
application can be divided into components based on their functions and distributed to the
appropriate tier on the multitiered architecture.
The slide shows a standard multitiered J2EE application model where the application logic
is distributed into the following tiers:
• Client-tier components, such as a Web browser, run on the client machine.
• Presentation logic is built with Web-tier components such as JavaServer Pages (JSP)
and Java servlets that run on the J2EE server.
• Server-side business logic is distributed as business-tier components that run on the
J2EE server. Enterprise JavaBeans (EJB) and the J2EE framework Business
Components for Java (BC4J) 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 10g.
The J2EE application components are developed in Java programming language. When the
J2EE platform is used, the J2EE components are assembled into a J2EE application, verified
according to the J2EE specification, and deployed to the J2EE server. The deployed
applications are run and managed by the J2EE server.
J2EE Components
There are several types of J2EE components. This course focuses on the most widely used
components, those of the Web and the business tier. These components are reusable, that 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.
• A Web browser:
– Is used for a Web-based J2EE application
– Downloads static or dynamic Web pages from Web-
tier components
– Is a thin client
• An application client:
– Is used for a non-browser-based J2EE application
– Executes on the client machine
– Can contain a graphical or command-line interface
– Is a thick client
– Accesses business-tier components or a servlet on
the Web tier
Client-Tier Components
Web Browser Client
For a Web-based J2EE application, the user’s 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 and JSPs from the Web tier. JSPs 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 Java Virtual
Machine (JVM) in the Web browser. An applet may require a Java plug-in and a security
file to successfully execute in the user’s Web browser.
Web-based clients are typically thin clients, which 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 J2EE
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 10g: Build J2EE Applications 2-10
J2EE Web-Tier Components
Web-Tier Components
J2EE 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.
Some advantages of using Web components are listed below:
• The HTML interface that is generated by a Web component is lightweight when
compared with the applets that require heavyweight downloads to the clients at run
time. Also, 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 client’s request for Web pages are served, can pass
through most firewalls.
Browser Servlet
Response
What Is a Servlet?
A servlet is a Java program that runs on a server, such as Oracle Application Server 10g, and
produces dynamic pages typically in response to client requests. The pages are then sent
back to the client’s Web browser. Typically, the output format for servlets 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 database through
JDBC, 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
next slide.
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
• Provides presentation-centric method of
developing servlets
Business-tier components:
• Are EJBs
• Handle business logic
• Receive data from client programs
• Retrieve data from database storage
• Process the data and communicate with the
database and the client program
• Can be invoked by the Web-tier components
Business-Tier Components
EJBs 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 system, 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 might invoke the business-tier components where the business
logic is handled. For example, a servlet might invoke an enterprise bean to insert new
customer details and return any processed data back to the client.
Enterprise JavaBeans:
• Are server-side components written in Java
• Contain the business logic of an enterprise
application
• Are hosted in EJB containers
• Are based on Remote Method Invocation (RMI)
communication
• Are platform independent
• Provide remote services for clients
• Can be exposed as Web services
• Use JDBC to connect to a database
J2EE Server
The J2EE server is the run-time portion of a J2EE product. A J2EE server provides EJB and
Web containers. The Web-tier and business-tier components can themselves be clients for
the other J2EE application components.
An advantage of the J2EE standard is that all the container providers must abide by the same
J2EE standards. This is much easier for developers because the application assembly is the
same in any J2EE-compliant environment.
The J2EE server provides system-level services to the J2EE application components:
• J2EE naming services provide the J2EE application components with access to the
Java Naming and Directory Interface (JNDI) lookup services. 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.
J2EE Applications
J2EE applications are server-side applications that contain standard components such as
servlets, JSPs, and EJBs. Applications are deployed in the form of modules that package all
necessary code for deployment to a J2EE server such as Oracle Application Server 10g.
Modules are archive files in a standard format, specified by the J2EE architecture.
1. ejb.jar
Bean class, Home and Remote
interfaces, other supported files, DD
2. webtier.war
Java servlets, JSP files, HTML, GIF files,
DD (references to EJBs)
J2EEapplication.ear
3. J2EEappClient.jar
J2EE application client (Java class),
DD (references to EJBs)
JARs
A standard JAR file has the following structure:
|-------META-INF
| -------manifest.mf
|-------Java classes
Typically, JAR files are used to hold groups of related Java packages (such as JDBC or
Swing). To simplify deployment or make operational access more efficient, you may want to
include them in EJB-JAR files, WAR files, or EAR files.
web.xml
Contain servlet code and
classes JavaBeans not in standard
JAR files
lib Contains required classes
that are packaged in
index.html standard JAR files
welcome.jsp
WARs
Each WAR file is created with the Web application and its XML files, which are structured
as follows:
|-------WEB-INF
| |-------web.xml
| |-------classes
| |-------Servlet classes (may be included inside packages)
| |-------lib
|-------index.html
|-------JSPs
Note that a WAR file may contain both HTML and JSPs, as well as many other supporting
files.
myEJB
META-INF
ejb-jar.xml
Contain the class files
for the EJBs, usually
EJB Classes
in a package directory
Remote, Home and structure
Bean classes
EJB JARs
Each EJB file is created with the EJB application classes and XML files, which are
structured as follows:
|-------META-INF
| |-------ejb-jar.xml
| |-------orion-ejb-jar.xml
|
|-------EJB classes
J2EE specifications recommend the use of an application directory to locate all application-
specific XML files. This is recommended because it keeps the global and default
configuration files separate from the application-specific configuration files. The
orion-ejb-jar.xml file is used by OC4J to deploy EJBs. Its use is discussed in detail
later in the course.
EARs
As J2EE applications became larger and more complex, there was a need to simplify
distribution. The J2EE specification addresses this issue. Organizations can use EAR files to
package all the client modules—HTML pages, JSPs, Servlets, EJBs, manifest files, and
XML configuration files—that are needed to distribute an entire application. All these files
are contained in a single archive file with a standard organization.
JTA
Client
JAAS
EJB JCA
ORMI
container JavaMail
ORMI
JAF
OC4J Architecture
OC4J implements the J2EE infrastructure. The OC4J Web container and the OC4J EJB
container use the J2EE virtual machine.
The J2EE containers perform services for applications, such as providing access to the APIs
and life-cycle management.
When Oracle HTTP Server receives a request, such as
http://myserver.com/j2ee/HelloWorldServlet, from the URL, it determines
the modules that are configured to handle this request, based on the mapping in the
configuration file (httpd.conf or mod_oc4j.conf).
In this case, Oracle HTTP Server resolves that mod_oc4j is responsible for this request,
because the /j2ee virtual path is mapped to the OC4J server. mod_oc4j then contacts a
specified OC4J instance by using Apache JServ Protocol (AJP). AJP is faster than HTTP,
through the use of binary formats and efficient processing of message headers.
Oracle Remote Method Invocation (ORMI) is the protocol through which EJB clients access
EJBs that are deployed to the container. This and the other APIs shown in the slide are
discussed in detail later in the course.
Additionally, HTTP is available directly to the OC4J process for development purposes.
mod_oc4j.conf
Data Sources
Data sources are a portable method for creating JDBC connections. The data-
sources.xml file is preinstalled with a default data source named OracleDS. However,
you can also add your own customized data source definitions. The default data source from
data-sources.xml is listed below:
<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleXADS"
ejb-location="jdbc/OracleDS"
connection-driver="oracle.jdbc.driver.OracleDriver"
username="scott" password="tiger"
url="jdbc:oracle:thin:@localhost:5521:oracle"
inactivity-timeout="30"
/>
Application Logging
In Oracle Application Server 10g, you can use the OC4J application.xml
configuration file to specify that a log file be created. The path attribute is relative to the
location of the application.xml file. The resulting log file is useful for debugging
applications during development, as well as tracing run-time errors. An example of the
output generated in a log file is as follows:
04/02/25 01:04:35 Started
04/02/25 01:04:36 practice02-login-webapp: JDevOJSP: init
04/02/25 01:04:36 practice02-login-webapp: 10.1.2.0.0 Started
04/02/25 01:04:36 practice02-login-webapp: LoginServlet: init
localhost
JDeveloper provides:
• Integrated development, deployment, and testing
support for Web-tier and business-tier
components
• A J2EE framework for rapid development
– Application Development Framework (ADF)
business components
– Data tags
• Integration with Struts
• UML modeling
• Visual editors for Web clients JDeveloper
• Easy deployment to Oracle Application Server 10g
Wizards for
JSPs,
servlets, and
EJBs
Error
checking
for HTML
and JSP
EAR, WAR
deployment
to J2EE
server
Code insight
Modify values
in property
Design in visual inspector
or code views
Summary
J2EE components include servlets, JSPs, and EJBs. These components are divided into
functions of business and presentation logic. J2EE applications can be built by using Oracle
JDeveloper 10g and deployed by using JDeveloper, Oracle Enterprise Manager Application
Server Control, or other tools.
Objectives
This lesson deals with the design of J2EE applications. After working for several years with
the object-oriented (OO) programming concepts, developers found that the best applications
follow similar patterns. This lesson discusses these patterns and also the principles of
developing an application that adheres to best practices.
J2EE Issues
Developers are often directed toward J2EE as a complete, effective solution, where
scalability and portability are handled automatically, without the need for good design
patterns. Thus, many J2EE applications are built to use the latest functionality, without
solving the needs of the enterprise. For example, there is a great debate in the J2EE
community about the use of Enterprise JavaBeans (EJB). EJBs solve some problems, but
can add unnecessary complexity to an application that does not require them. The following
guidelines can help you determine when to use EJBs:
• When you are developing for a distributed architecture, and developers are
knowledgeable in the use of EJBs, use EJB to manage business objects and their life
cycle and invocation.
• If the application is designed to develop scalable, robust applications, and the
developers have little knowledge of EJBs, then you must use Web applications that do
not use EJBs.
View Controller
Model
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 as 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 façade. For example, a session façade 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 façade bean implements.
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 might 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 next slide), and the resultant data would be displayed in the
view.
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. In the example on the
previous page, the controller would accept the user’s query parameters and pass 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 could change, without affecting the
navigation and functionality of the application. A developer would simply change either the
model or the view, respectively.
Selected Method
view invocation
Return
result
JSP Servlet Enterprise
JavaBeans
HTTP HTTP
request response
Browser
Receive
Customer order Administrator
status
Place
Log in Fill orders
orders
Browse Update
products inventories
Vendor
Receive
b. An EJB that maintains the orders
order in each customer’s shopping cart
status
Objectives
This lesson explains the servlet technology architecture, and discusses the creation of a
servlet in JDeveloper.
Requests Connects to
Generates
Responds to
Dynamic HTML
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 programmer’s task be simplified, although the program remains powerful
enough to handle all situations?
This lesson discusses the answers to these questions.
Client
Server
Request 1
Request 2
Request 3
Clients Server
1 2 3
4
Destroy
destroy()
Response
Client HTTP protocol 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.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimplestServlet extends
HttpServlet
{
public void doGet(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Servlet: Example
The code in the slide shows the simplest form of a servlet. This servlet prints the plain text
“Hello World” when invoked.
sendRedirect() Sets the Location header and sets the status code to 302.
Status codes are discussed in detail later in the course.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
response.setContentType ("text/html");
PrintWriter out = response.getWriter();
out.println ("<html>");
out.println ("<body>");
out.println ("Hello World!");
out.println ("</body></html>");
}
}
• ServletException:
– Is generated to indicate a generic servlet problem
– Is subclassed by UnavailableException to
indicate that a servlet is unavailable, either
temporarily or permanently
– Is handled by the servlet engine in implementation-
dependent ways
• IOException: Is generated if there is an input or
output error while processing the request
Error Handling
The doXxx() methods throw both the ServletException and the IOException.
The init() method throws the ServletEception. 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>
Debugging a Servlet
Servlets can be debugged in JDeveloper by setting breakpoints in the code (by clicking the
line number that you want to set) 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 J2EE components that are running in a
different JVM. The detailed steps to do this are located in the online help of JDeveloper, in
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.
SingleThreadModel
Normally, the servlet engine creates a new thread for each request. If the servlet implements
the SingleThreadModel interface, then there will never be more than one request
accessing a single instance of the servlet. In this case, the developer need not synchronize
access to fields and other shared data, such as instance variables. The
SingleThreadModel interface is a solution for low-volume servlets that handle
unsynchronized data and cannot be accessed simultaneously by requests, such as when
creating a userID.
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.
Servlet Mapping
The example servlet shown earlier shows how JDeveloper invokes a servlet. Servlet
mapping refers to the process by which a servlet is invoked. This is application server–
dependent, but in general you can map a servlet:
• To any URL that begins with a certain directory name. In this case, all class files under
the directory are treated as servlets.
• By using the direct or mapped URLs:
http://host:port/<context-root>/servlet/<package>.<servlet>
http://host:port/<context-root>/servlet/<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, Apache’s default port is 80; OC4J’s default
port is 8888)
The context root is the mapping for the J2EE Web module. This is created by default in
JDeveloper as: <Workspacename>-<ProjectName>-context-root and can be changed
in the http-web-site.xml configuration file.
Invoking a Servlet
This slide shows an example of how a servlet can be invoked in JDeveloper. When the
servlet is run, the J2EE 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 demos-lesson04-context-root.
Deploying to OC4J
After the connection is created, deploying to OC4J is simple. Right-click the deployment
profile and select Deploy to <yourappserverconnection>.
Note: If you use Oracle Enterprise Manager to deploy an application, then you can still use
the deployment profile to create the application WAR or EAR file.
Objectives
This lesson focuses on accessing the database by using Java Database Connectivity (JDBC)
from a servlet. This method is recommended when J2EE applications do not use EJBs or
when the functionality of the servlet is not complex. Note that JSPs can also access a
database in a similar manner to that of servlets. JSPs are discussed later in the course.
Review of JDBC
The java.sql package contains a set of interfaces that specify the JDBC API. This
package is a core part of Java and is supported by JDeveloper. Database vendors implement
these interfaces in different ways, but the JDBC API itself is standard. Oracle provides four
drivers: a thin-client driver, an Oracle Call Interface driver for the middle tier, a Java
Transaction Service–enabled driver for applications that span multiple databases, and a
server-based driver in the Oracle database.
By using JDBC, you can write code that:
• Connects to one or more data servers
• Obtains metadata from the data server
• Executes any SQL statement
• Obtains a ResultSet object so that you can navigate through query results
import java.sql.*;
Connect DriverManager.registerDriver(…)
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin …
Query Statement stmt =
conn.createStatement ();
ResultSet rset =
stmt.executeQuery (
Process results "select * from EMPLOYEES");
while (rset.next ())
System.out.println(
rset.getString (2));
Close rset.close();
stmt.close();
conn.close();
Transaction Handling
If your application has transactional elements, such as committed updates, then the strategy
of having a preestablished connection to a database is a problem. This is because the handle
to this Connection object is available to multiple threads corresponding to multiple client
invocations. The slide shows four possible solutions.
• Create a new Connection object every time a servlet is invoked, and close the
connection every time. In general, this solution is acceptable only in a few cases, such
as in debugging situations. Connection Pooling for this option is discussed later in this
lesson.
• Create a Connection object in the init() method, but serialize the use of this
object by using the synchronized keyword. If there are few concurrent client
accesses to the Web server, then this may be an acceptable solution.
• Implement the SingleThreadModel interface. When a servlet implements this
interface, the servlet engine is alerted not to allow multiple threads for the doGet()
method in this servlet object. If multiple requests are made at the same time to the Web
server, the servlet engine instantiates a new servlet object. The servlet engine is free to
spawn multiple instances beforehand. Therefore, this solution is acceptable if there is
an expected limit to the number of concurrent accesses to this servlet (for example, the
number of students in a class).
Connection Pooling
The most elegant solution is to implement connection pooling, in which a pool of
(preinstantiated) Connection objects are awarded to different requests. When a client is
finished with the request, it is returned to the connection pool. This solution resembles the
SingleThreadModel solution with prespawned connections, except that the amount of
connection pool objects that are instantiated is dynamic and controlled by a program (which
can be adaptive).
Connection pools have a low-water mark (the minimum number of Connection objects
that must always be present, whether in use or not) and a high-water mark (maximum
number of active connections). They are useful only if connections are created relatively
frequently and released soon after use.
OC4J_HOME/applications
myapp
application.xml
Points to
data-sources.xml
<data-source
class="com.evermind.sql.DriverManagerDataSource"
connection-driver="oracle.jdbc.driver.OracleDriver"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleDS"
ejb-location="jdbc/OracleDS"
min-connections="5"
max-connections="25"
username="oe"
password="oe"
url="jdbc:oracle:thin:@<host>:<port>:<SID>"
/>
data-sources.xml: Example
In the example, the attributes of the data-source tag are defined as follows:
• class defines the DataSource class that is to be used.
• connection-driver defines the JDBC driver for this data source.
• name is used to identify this data source. The default is the value of location.
• location defines the logical name for the data source. It returns a DataSource
class as specified in the class attribute.
• xa-location is a mandatory attribute if ejb-location is present. This defines
the logical name for the XA-enabled data source.
• ejb-location is the logical name for the entity bean data source. This is the JNDI
name that should be used for looking up data sources for any J2EE component.
• min-connections controls the minimum size of the connection pool. The default
value is zero.
• max-connections controls the maximum size of the connection pool.
• url indicates the JDBC connection URL, and optionally the username and password.
OC4J provides a wrapper for DataSource objects that returns an appropriate
DataSource object for the requested data source location.
Note that the pooled-location tag defines the JNDI location of a pooled-connection
data source.
Oracle 10g: Build J2EE Applications 5-12
Using Data Sources
101 Welles
102 Pacino
103 Taylor
104 Sutherland
105 MacGraw
106 Hannah
107 Cruise
108 Mason
109 Cage
116 Martin
117 Edwards
118 Mahoney
119 Hasan
120 Higgins
121 Sen
122 Daltrey
123 Brown
Objectives
This lesson discusses additional topics in creating a servlet.
Request
getCookies()
getHeader()
Response
Client Web Servlet
setHeader()
browser
addCookie()
Error handling
Overview
The request and response objects provide methods for sending and retrieving data such as
parameters (as seen in the lesson titled “Creating the Web Tier: Servlets”), cookies for
obtaining state information, and headers for setting status codes and redirecting the user.
This lesson covers the use of these methods, as well as the techniques for handling errors.
HTTP Headers
The HTTP request and response headers manipulate the HTTP connection between the
browser and the server. For example, in the previous lessons, setContentType was used
to set the content type header for the browser. Note that because headers can change the
content of the response, they need to be set before the output is generated.
Request Headers
Retrieving the value of request headers is helpful for designing servlets that cater to browser
preferences. For instance, if a servlet is written to produce content in more than one
language, request.getHeader("Accept-Language") could be used to verify a
standard language code (en-us, da, and so on). Thus, the response could be modified
according to the browser settings, without having to ask the user for a form value or other
parameter. The following is a complete list of request headers:
Accept Accept-Charset Accept-Encoding
Accept-Language Authorization Cache-Control
Connection Content-Length Content-Type
Cookie Expect From
Host If-Match If-Modified-Since
If-None-Match If-Range If-Unmodified-
Since
Pragma Proxy-Authorization Range
Referer(misspelled Upgrade User-Agent
due to HTTP author Via Warning
error)
Sending a Response
A servlet must also send data back to the browser. There are three aspects to this, as shown
in this slide. These aspects are explained in detail in the following slides.
Response Headers
The following table shows some standard HTTP response headers. Common headers have
shortcut methods, such as setContentType, setContentLength, addCookie, and
sendRedirect.
Header Usage
Example
The slide shows an example of a servlet sending HTTP headers back to the client. For the
purpose of this example, the browser sends a request to www.oracle.com. The servlet
receiving this request dispatches the browser to a new site for the purposes of load
balancing.
The first servlet generates a random site that is capable of serving the same request. In this
example, it is www233.oracle.com.
• It sets the status code to SC_MOVED_TEMPORARILY.
• It supplies the new location by sending the Location HTTP header.
Cookies
The following table describes the methods that are available for use with cookies and their
purposes:
get/setMaxAge This method controls the cookie expiration time in seconds. The
default value is negative, which indicates that the cookie will last only
until the user closes the browser. Setting the value to zero (0) instructs
the browser to delete the cookie.
get/setName This method gets or sets the name of the cookie.
get/setPath This method gets or sets the path to which the cookie applies. Default
is to return the cookie only to the URLs that are in or below the
directory containing the page that sent the cookie.
get/setValue getValue() looks up the value that is associated with the cookie.
setValue() specifies the value.
get/setDomain This method controls the domain for which the cookie is applied. The
browser will only return cookies to the exact host name that sent them.
Use setDomain() to return cookies to other hosts within the same
domain.
Setting Cookies
The Cookie constructor takes two strings: name and value. Note that if a user has a
browser that does not support cookies, or if the user has disabled cookies in his or her
browser, then you need to use URL rewriting, hidden form fields or session tracking to keep
track of visitors to your site. These topics are covered in a later lesson. Additionally, because
cookies are not encrypted when sent, retrieved, or stored, they should not be used for
sensitive information such as passwords.
Retrieving Cookies
The code in the slide shows how to read the cookie object from the browser. To use the
cookie object rather than just read the value, use the getCookie() method.
ServletContext
The following table provides some of the methods of ServletContext and their uses:
Method Purpose
getContext(String) Returns the ServletContext object for the specified
URL
getMimeType(String) Returns the MIME type of the specified file as
determined by the configuration of the servlet
container, or as specified in the web.xml file
getRequestDispatcher(String) Returns a RequestDispatcher object that acts as a
wrapper for the resource located at the given path.
RequestDispatcher is used to forward or include
the request or response.
getServerInfo() Returns the name and version of the servlet container
getServletContextName() Returns the name of the corresponding Web application
as specified in the deployment descriptor for this Web
application by the display-name element
RequestDispatcher
You have seen that a user can be redirected to another resource by using
sendRedirect(). However, this does not automatically preserve the request data.
Instead, you can use the RequestDispatcher interface, passing in the URL for the new
resource. Use the forward() method of RequestDispatcher to completely transfer
control to the associated URL.
For example, if a user accesses a login form of an application and does not have an account,
the request could be forwarded to an application page for the user to complete. The
include() method is used to get an output of the content of the associated URL, after
which control is returned to the servlet. Note that for both the forward() and
include() methods, POST requests cannot be forwarded to static HTML pages, because
forwarded requests use the same request method as the original request. This can be avoided
by renaming the HTML document to a .jsp extension that can handle the POST request.
JavaServer Pages (JSP) is covered in detail later in this course.
RequestDispatcher: Example
By using the StateServlet example seen in the section “State Preservation: Example”
earlier in this lesson, assume that the user does not enter a name in the HTML field. You
may then want to display an HTML form with details about appropriate values. To forward
to a static HTML page, use a RequestDispatcher. The slide shows how
RequestDispatcher is obtained by calling the getRequestDispatcher()
method of ServletContext. The RequestDispatcher can then forward or include
the content to a static HTML page, a JSP, or to another servlet.
Servlet Filters
Servlet filters are a new feature of the Servlet 2.3 API, and can be used to intercept and
modify a servlet’s response. They can be configured to be invoked when one or many
servlets are called. This enables the programmer to modify production servlet functions
without changing existing code. Note that filters work with servlets and JSPs, but are not
servlets themselves, because they do not actually create a response. Instead, they pass the
response to the calling servlet. Filters can be used for several reasons, including
authenticating user identity, tracking users of an application, and compressing data.
JDeveloper contains wizards for creating filters.
Using Filters
You must implement the javax.servlet.Filter interface and define the
init(FilterConfig), destroy(), and doFilter() methods to use a filter. The
init() method is called once to initialize the filter. Pass the FilterConfig object to
init() to pass the initialization parameters. The doFilter() method is then called for
each request that is specified to use the filter. This method is responsible for actions such as
examining request and response headers and customizing the response as necessary.
FilterChain can be used to call multiple filters in succession. If there are no filters
defined or if the current filter is the last filter in the chain, then the target servlet is called.
The server calls the destroy() method to discontinue the use of the filter.
doFilter() Method
Use the doFilter() method to modify the request headers, the response, and to
optionally invoke the next filter in the filter chain. The request and response objects are
wrapped in the filter class by implementing HttpServletRequest or
HttpServletResponse. The next entity (a filter or a servlet) is invoked by calling the
doFilter() method on the FilterChain object, passing in the request and response
that it was called with, or wrapped versions that it may have created. The filters are called in
the same order that they are listed in the web.xml file. Note that if the current filter is the
last filter in the filter chain, then the filter invokes the servlet that called the filter.
Using Filters
In this example, the Filter interface is implemented, and the init(), doFilter(),
and destroy() methods are created to display a message when the filter is initialized. Just
before passing the request and response objects, a “Hello from Filter” message will be
displayed in the console.
<filter>
<filter-name>HelloFilter</filter-name>
<filter-class>filterpackage.HelloFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<servlet-name>StateServlet</servlet-name>
</filter-mapping>
Configuring Filters
The web.xml file is used to configure a filter for use. In the example given in the slide, the
filter class, HelloFilter, intercepts the request when StateServlet is accessed. A
filter can also be configured to run whenever any request (static or dynamic) is made to the
Web application:
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Initialization parameters can be specified for a filter by using the <init-params>
element.
ServletContext Events
The following table describes the types of methods that are invoked for each type of
ServletContext event:
Events Methods
ServletContext is contextInitialized()or
created or is shutting contextDestroyed() methods of the
down. ServletContextListener class
An attribute has been attributeAdded(),
added, removed, or attributeRemoved(), or
replaced. attributeReplaced() methods of the
ServletContextAttributeListener
class
HttpSession Events
Sessions are a way to maintain a continuous connection within a Web application, and are
covered in depth later in the course. For now, just note that the following methods are
available for tracking session events:
Events Methods
An HttpSession has sessionCreated() or
been activated or is sessionDestroyed() methods of the
about to be destroyed. HttpSessionListener class
An attribute has been attributeAdded(),
added, removed, or attributeRemoved(), or
replaced. attributeReplaced() methods of the
HttpSessionAttributeListener
class
Error Handling
As in any program, error handling is very important in a servlet. For example, errors can
occur if:
• The client sends malformed data to the servlet
• A resource made available by the operating system becomes unavailable or corrupt
When an error occurs, you should limit the damage to the server and inform the Web
browser appropriately. The following example illustrates how you could manipulate the
response status line in a servlet, by using the previously referenced StateServlet:
String name = request.getParameter("firstName");
if ((name.equals("") {
reportError (response, "Missing Name Parameter");
return; }
private void reportError(HttpServletResponse response,
String errmessage) throws IOException {
response.sendError (response.SC_NOT_FOUND, errmessage);
}
Objectives
Although the HTTP protocol is stateless, servlets allow your application to “remember”
previous visitors and the data that they have created in the past. This lesson shows you how
to use this capability.
First request
Chris
Servlet
Second request
Chris
First request
Michelle
Overview
The standard HTTP server is stateless, and cannot distinguish whether two requests come
from the same client. You may want to know if the same client has accessed your servlet
before. This question is more complex than it may seem:
• If Chris accesses your servlet from a Netscape browser and an Internet Explorer
browser at the same time, then should the servlet consider the two requests to be from
the same client?
• If Michelle accesses your servlet today, and again a month later from the same
browser, then should the servlet consider the two requests to originate from the same
client? Assume that the browser has not been shut down in this period.
Session Basics
Two requests originating from the same browser within a short period of time are considered
to be from the same client. When considering sessions, think about the shopping cart
scenario of many online applications. Requests from different browsers are considered to be
from different clients (as in the previous slide, with requests coming from Chris and
Michelle).
Client 1
• URL rewriting:
– Every URL that is accessed by the client is rewritten
so that it has the session ID.
– Use the encodeURL() method to re-create the path
dynamically.
• URL rewriting is used when a client turns off
cookie support in the browser.
URL Rewriting
Use response.encodeURL() when sending a URL from your site to the client. The
browser header information can then be retrieved by using the request object. If you are
using sendRedirect, then a corresponding method called encodeRedirectURL
exists for this purpose. For instance:
String originalURL = someURL;
String encodedURL = response.encodeRedirectURL(originalURL);
Response.sendRedirect(encodedURL);
HttpSession
The HttpSession class is an interface. The object is obtained by using the
getSession() method in the HttpServletRequest object. This is done by
extracting a userID 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 will
return 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(session.getId());
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute(session.getId(), cart); }
Session Objects
The table below describes the methods in the HttpSession class and their meanings:
Example:
public class EventObject
implements HttpSessionBindingListener {
public void valueBound(
HttpSessionBindingEvent event) {
// connect to the database using this client
sess = event.getSession()//which session?
// get values from this session object to
// identify client information
}
public void valueUnbound(
HttpSessionBindingEvent event) {
// release resources
}
}
g. Modify the doGet() method to call the method that you have created in a
try/catch block. Make sure to create table headings for the product name and
description.
2. Create a link from LoginServlet to ProductsServlet.
a. Below the code for displaying orders for a customer (in the doPost() method),
insert an href link to point to the ProductsServlet. You can use the URL-
pattern mapping name that is generated for you, described in the web.xml file.
Note that the cookie functionality created in the last practice has been removed to
prevent any confusion.
3. Create a ShoppingCart class to store the selected products in a Hashtable.
a. Create a new class file by selecting Java Class from the Simple Files category
(within the General category). Name the class ShoppingCart and click OK to
accept the default package and attributes.
b. Import the java.util.* package because you will be using a Hashtable
from that package.
Oracle 10g: Build J2EE Applications 7-20
Practice 7-1 (continued)
c. Declare two instance variables in the class definition: items and
numberOfItems. Declare items as a Hashtable and numberOfItems
as type int, initializing to null and zero, respectively.
d. In the class constructor, initialize items as a new Hashtable object.
e. Create a method named add(). This method should return void and pass in two
arguments, prodid and name, both strings.
f. Add code to this method to store the prodid and name arguments in the
Hashtable object that you created in step 3d, and increment the
numberOfItems variable.
g. Create a second method named getNumberOfItems(). This method should
return numberOfItems.
h. Create a third method named getItems(). This method should return an
enumeration of elements in the items hashtable.
i. Compile ShoppingCart.java.
4. The next step is to create a servlet to display the products in the user’s shopping cart.
a. Create a new servlet and name it ShowCartServlet. Change the package
name to orderproducts and create servlet mappings as in previous practices.
b. Add code to the doGet() method to create a new session object if one does not
already exist.
c. Next, retrieve the user’s shopping cart as cart from the session object. Use the
getId() method of the session to find the unique identifier of the session.
d. If the user does not have an existing shopping cart, create a new one by passing
in the session’s unique identifier and cart object.
e. Create two variables to retrieve the prodid and name parameters from the
request object.
f. Add these values to the cart object by calling the add() method of the
ShoppingCart class and passing in the prodid and name arguments.
g. Create an int variable to retrieve the number of items that are ordered from the
ShoppingCart class.
h. Add HTML to display the number of items in the user’s shopping cart, and create
a table to display the elements in the cart. Note that the getItems() method
returns a java.util.Enumeration of items in the Hashtable. You need
to import this package. Use the hasMoreElements() method to verify items
in the getItems() method. Remove the skeleton HTML code.
i. Compile ShowCartServlet.java.
5. Save and compile the project, and test the application by running
LoginServlet.java.
Objectives
This lesson discusses JavaServer Pages (JSP). You learn how to differentiate between
servlets and JSPs. You learn about the life cycle of a JSP, and also the various elements in a
JSP. You should be able to develop simple JSPs with declarations, expressions, and
scriptlets, and learn how to use JavaBeans with JSP. You also learn how Oracle JDeveloper
10g can be used to develop JSPs.
Request Connects to
JSP
Database
Client
Generates
Dynamic content
Response EJB
JavaServer Pages
The idea behind servlets and JavaServer Pages technology is to separate the presentation
logic and business logic and, therefore, have thin clients. JSPs are based on Java servlet
technology and are an extension of servlets. JSPs can generate dynamic content just like
servlets; 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 JSP builds on servlets, the focus of JSP is on improving the programmer’s
productivity. JSP leverages the benefits of component technologies and, therefore, simplifies
the task of the programmer.
The graphic in the slide shows that a client invokes a JSP with a URL. Note that JSPs
function by using the request/response model, like servlets. 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 it to the client.
HTML
Invoke
JSP
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.
In the URL:
- host is the name/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
You invoke a JSP directly with the URL if a home page or login page is designed with
JSP. You can also use it for testing purposes.
• 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.
...
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();
}
...
J2EE container
Yes
OC4J First
1
time
Create servlet
http://host/date.jsp
No date.java
Compile servlet
date.class
3
Servlet life cycle
Declarations
As the name indicates, the JSP declarations are used to declare the methods or variables.
This is inserted into the main body of the servlet class outside the _jspService method.
The example in the slide shows how to declare an integer variable and string variables.
Observe that these variables are declared as well as initialized in the declaration. It is
mandatory to terminate a declaration with a semicolon before closing it with %>. Note that
declaring a variable does not write anything to the output.
The variables declared in this manner are static by default. As previously discussed, the JSP
file is translated and compiled into a servlet class. When multiple clients request the same
servlet, multiple threads are created to handle the requests. However, they operate on the
same instance of the servlet if the servlet does not implement SingleThreadModel.
Each thread calls the service method of the same instance, and this instance has a single
variable. Therefore, any changes made to the variable by one thread are reflected in the
other threads. This is as good as modifying a static variable.
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. 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 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(new java.util.Date());
out.print("Hello" + " World");
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 for scriptlet. You can alternatively write the code shown below:
<%if (i<3) %>
i<3
<%if (i==3) %>
i==3
<%else %>
i>3
In this code, whatever is not enclosed within the scriplet 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
being used. The following slide discusses this variable.
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.
Example
You have learned about declarations, expressions, and scriptlets. This slide shows the result
of putting them all 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> <%! private int i=3; %>
<%! private int i=3; %> <br>
<b> Declare Strings a and b </b><%! private String a="Hello",
b=" World"; %>
<%! private String a="Hello", b=" World"; %>
<h3> Expressions </h3>
<%= i+1 %> <b> output </b>
<%= i+1 %> <br><%= a + b %>
<b> output </b>
<%= a + b %>
Directives
JSP directives contain messages to the JSP container. They are used to set global values. All
the directives have the scope of the JSP that contains the directives.
The page directive: The page directive is used to define 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.
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 is included 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 <%@
include file=" " %> tag </b>
<br><%@ include file="includefile.html" %>
</body> ...
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,” then 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 client’s 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.
package lesson08;
import java.lang.*;
import java.util.*;
public class LuckyNumberBean {
private int luckyNum;
public LuckyNumberBean() {
luckyNum = (int) (1000 * Math.random());
}
public int getLuckyNum() {
return luckyNum;
}
public void setLuckyNum(int luckyNum) {
this.luckyNum = luckyNum;
}
}
Request
Response
Forward
session scope
Traditional: XML:
• No root element • <jsp:root> is the root
element
• page directive • <jsp:directive.
<%@ page %> page />
• Declaration tag • <jsp:declaration>
<%! %> </jsp:declaration>
• Expression tag • <jsp:expression>
<%= expression %> </jsp:expression>
• Scriptlet • <jsp:scriptlet>
<% %> </jsp:scriptlet>
Summary
In this lesson, you should have learned about the various elements of a JSP. You should also
have learned how to use Oracle JDeveloper 10g to build JSPs.
Objectives
This lesson discusses the use of custom tags in JSPs.
Custom Tags
Custom tags are a feature of JSP 1.1 and later versions. Custom tags enable you to create
your own tags for use in JSP applications. Tags provide encapsulation of complex behaviors
much like JavaBeans, but they can also manipulate JSP content. This is useful because JSPs
can often have a large amount of scriptlet code to maintain, and can eventually lose their
reusability. Custom tags are useful because they have simpler syntax than scriptlets and are
reusable. Therefore, they can be developed by Java programmers and used in JSPs by Web
application developers using XML syntax.
Similar to HTML tags, there are custom tags without a body:
<tagName attribute1="value1" attribute2="value2" />
There are also tags that have matching end tags and, therefore, include a body:
<tagName attribute1="value1" attribute2="value2" >
…tag body…
</tagName>
Note that both types of tags may have attributes to customize the behavior of the tags.
<taglib>
<taglib-uri>/webapp/mytaglib</taglib-uri>
<taglib-location>/WEB-INF/taglib.tld</taglib-location>
</taglib>
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class HelloWorldTag extends TagSupport {
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("Hello from Custom Tag!!!");
}
catch(IOException io) {
System.out.println("Error in TagMessage: " + io);
}
return(SKIP_BODY);
}
public int doEndTag() {
return (SKIP_PAGE);
}
}
<html>
<head>
<%@ taglib uri="webapp/taglib.tld"
prefix="mytags" %>
</head>
<body>
<h2>The following output is from the
HelloWorldTag:</h2>
<p>
<mytags:hellotag/>
</p>
</body>
</html>
Expression Language
Expression Language (EL) is an alternative to expressions. EL uses a dollar sign and braces
to create an expression. There are several benefits of using ${expr} over <%=expr%>:
1. If the value of the expression is null, it evaluates to an empty string. This is most
beneficial for eliminating null pointer exceptions when users do not enter parameter
values correctly.
2. Object properties, collection elements, and JavaBean properties are easy to reference
by using the dot notation.
3. Several implicit objects are available for easy access to JSP objects, including:
pageContext pageScope
requestScope sessionScope
applicationScope param
paramValues header
headerValues cookie
<table>
<tr>
<c:forEach var="allparams" items="${param}" >
<c:out value="${allparams.key}" />
</c:forEach><tr>
<table>
<sql:query datasource="jdbc/oeCoreDS"
var="customers" maxRows="10">
SELECT * FROM customers
</sql:query>
<table>
<c:forEach var="row"
items="${customers.rowsByIndex}">
<tr><c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
Formatting Tags
The “i18N tags,” or “formatting tags” as they are more informally known, are used to
specify that various data elements in a JSP page, such as numbers, dates, and times, be
formatted and parsed in a locale-sensitive manner. The format tags in JSTL use either
java.util.ResourceBundle or java.util.Locale to format data.
There are several tags in the Format library, including:
• <fmt:formatNumber>: Formats a numeric value to the specified number,
currency, or percentage, or to a specified locale
• <fmt:parseNumber>: Parses the specified number, currency, or percentage that
are formatted in a customized manner
• <fmt:formatDate>: Formats a date and time to the specified or locale-sensitive
arrangement
• <fmt:parseDate>: Parses the specified date or time that were formatted in a
customized manner
• <fmt:setTimeZone>: Creates a variable containing the specified time zone
• <fmt:parseTimeZone>: Parses the specified time zone
Internationalization Concepts
A locale is a geographical or a political region. It is defined by a two-letter language code
and a two-letter country code, such as “en-US.”
A resource bundle is a set of paired messages and keys. The key specifies the name of the
message, and the message is the text. A resource bundle is used by referring to a basename.
The basename identifies a set of paired messages and keys based on the type of message.
For instance a “login” basename could contain two resource bundles for the “welcome” key:
“Hello” for English and “Bonjour” for French.
<fmt:bundle basename="login">
<fmt:message key="Hello" />
</fmt:bundle>
Internationalizing Strings
To look up a message in a resource bundle, specify the key attribute in the
<fmt:message> tag. This uses the current locale to display the message from the
appropriate resource bundle. Additionally, a <fmt:param> tag is available for supplying
parameters in the body of a <fmt:message> tag.
Alternatively, specify the basename to use with the <fmt:bundle> tag, as shown in the
slide. The “login” basename will look for the “Hello” key and display the string using the
current locale set in the browser. However, a locale can be specified for an application by
using <fmt:setLocale>. For example:
<fmt:setLocale value="en_US" />
To retrieve the URL parameters from a browser that does not specify an encoding of the
standard ISO-8859-1, use the <fmt:requestEncoding> tag. This tag accepts a value
attribute to set the request’s character encoding.
<fmt:formatNumber type="percent"
value=".547" pattern="#.###" />
Attribute Purpose
value The date or time to be formatted
Type Specifies whether the time, date, or both portions of the provided
date value are to be formatted
Datesytle The formatting style for dates, provided in the syntax defined in the
java.text.DateFormat class
Timestyle The formatting style for times, provided in the syntax defined in the
java.text.DateFormat class
Pattern A custom format for dates and times
Timezone A String or java.util.TimeZone in which to format the
provided time
Var The name of the variable where the formatted date will be stored
page The scope of the variable
JSTL in JDeveloper
In JDeveloper 10g, you do not need to add JSTL to the component palette. Rather, the four
JSTL libraries are included and can be accessed by selecting JSTL Core, JSTL FMT (the
internationalization tags), JSTL SQL, or JSTL XML from the Component Palette drop-down
list. Drag a tag to either the Design or the Source editor to add it to the JSP.
Objectives
This lesson describes the architecture and the APIs that are used for some communication
techniques in J2EE environments and examines their usage from client applications.
JNDI names are influenced by the configuration of various elements in the environment,
such as variables, EJB references, and data sources. In a J2EE environment, these elements
are specified in application deployment descriptors or property files.
Introduction to RMI
An RMI client application uses a standard remote procedure call (RPC) mechanism to
communicate with remote objects. The mechanism involves the use of stubs and skeletons.
RMI applications comprise a client that communicates with a remote server object via a
user-defined remote interface. The server object is instantiated from the implementation
class in the context of a server application.
A stub acts as the client’s representative for the remote object, often called a proxy. The
client invokes a method on the local stub that in turn executes the appropriate method call on
the remote object. An RMI stub class implements the same remote interface that is used by
the remote object. The remote object may have a skeleton class. The skeleton manages the
dispatching of a client call (via the client stub) to the actual remote implementation object.
In JDK 1.2 and later, an additional stub protocol is introduced that eliminates the need for
skeletons, and generic code carries out the tasks that are performed by skeletons in JDK1.1.
Stubs and skeletons are generated by running the rmic compiler on the compiled
implementation class. For example:
rmic RMIClassImpl
The rmic command produces two class files: RMIClassImpl_Stub.class for the
stub and RMIClassImpl_Skel.class for the skeleton.
J2EE server
1 Naming
3 Creation
4 Client 2
5
Interface Marshaled data
Stub Skeleton
Marshaled data
6
Local call 7
Interface
Network protocol
(Java RMI) Server
object
What is JNDI?
• JNDI is a standard API that provides access to the
directory and naming functionality.
• The JNDI Service Provider Interface (SPI)
implementation provides the mapping between the
naming servers and the JNDI APIs.
JNDI API
Client
JNDI SPI
Naming Service
An Object Naming Service is the principal mechanism for objects or clients to locate other
objects on the network. Names are humanly recognizable values that identify an object. The
naming service enables the creation and mapping of these names to object references.
A name-to-object association is called name binding. In the case of EJBs, the server
performs the binding of the bean’s home interface in the JNDI namespace.
Naming services can be used for literally mapping any type of object or resource with names
such as files, database objects, remote objects, and so on. EJB specifications require that the
bean home interfaces be published and made available to the clients through JNDI.
It is the responsibility of the server and container provider that the beans deployed in the
server are made available to different clients through a JNDI service.
A directory service usually has a hierarchical structure of data, and you use the naming
service to create logical names and map them to the naming server. For example, the
directory service of a file system contains a hierarchical structure of folders, subfolders, and
the files in the folders.
Examples of naming services are RMI registry, LDAP, and CORBA Naming Service (COS
Naming).
Context Namespace
env
Sub-context
jdbc ejb
Atomic
OracleDS oeCoreDS Employee Cart
names
Binding
Objects
JNDI Terminology
Namespace: The set of all names in the naming server. The names in the namespace must
be unique. For example, in a directory structure, each file and subdirectory in a particular
level have unique names.
Initial context: The root directory object in the namespace that refers to the starting point of
the name hierarchy from which a client can start navigation. The client obtains this root
directory by creating a new InitialContext object. Relative to the initial context, a
client can look up another object using its compound name.
Compound name: Formed by concatenating the names of each context object along the
hierarchical path to the target atomic name for an object published in the JNDI namespace.
The slide shows env, jdbc, and ejb as context objects, where jdbc and ejb are
subcontexts below env.
Atomic name: A unique indivisible part of a name, such as env, jdbc, and OracleDS
Binding: The process of associating an object with a name in the naming and directory
service
URL: A composite name spanning more than one context or namespace, which is used to
uniquely identify an object in a composite namespace
lookup() Method
After the client obtains the InitialContext, it should obtain a reference to the required
resource by using the lookup() method on InitialContext. The client uses the
lookup() method by passing the URL with the object name as the parameter. This
generally depends on how the resources are mapped in the naming server. Generally, the
URL to look up a local resource (in the same container) is of the following format:
java:comp/env/subContext/resourceName.
For example, the client looks up an EJB called Dept under the subcontext ejb with the
URL java:comp/env/ejb/Dept. Here, java:comp/env is the initial context, and
ejb/Dept can be the actual name of the EJB as specified in either the <ejb-name> or
the <ejb-ref-name> element of the deployment descriptor where the bean is defined. It
can also be the logical name of the bean, which is defined in the <ejb-ref-name>
element under the <ejb-ref> section in the files ejb-jar.xml, application-
client.xml, or web.xml for an EJB, an application, or a servlet or JSP client,
respectively.
In another example, a client looking up a data source called oeCoreDS may use the URL
java:comp/env/jdbc/oeCoreDS. Here, jdbc is the subcontext name and
oeCoreDS is the resource name.
Note: The initial context for a local object always uses the URL prefix java:comp/env.
<env-entry-mapping OC4J DD
name="minBalance">300
</env-entry-mapping>
Summary
The slide summarizes the key points covered in this lesson. RMI is not specified as a part of
the J2EE specification. However, RMI mechanisms and java.rmi interfaces and classes
are used by J2EE components. The RMI communications architecture is used as the basis
for communication between J2EE client and server components such as Enterprise
JavaBeans. The JNDI services provided by J2EE-compliant implementations provide a
standard way for clients to locate, look up, and communicate with distributed objects in a
J2EE environment.
Objectives
This lesson introduces Enterprise JavaBeans and how to create them in Oracle JDeveloper
10g.
Enterprise JavaBeans
EJBs have the following features:
• EJBs reduce the burden on the developer, because the details of transaction support,
security, remote object access, and many other complicated and error-prone issues are
provided transparently to the developer by the EJB server and container.
• EJBs support a standard set of interfaces.
• EJBs consist of methods that encapsulate business logic. For example, an EJB may
have business logic that contains a method to update the customer data in a database. A
variety of remote and local clients can invoke this method.
• The container vendor provides the services that are required to make EJBs work.
Because all vendors support the same standard set of EJB interfaces, any EJB should
be able to execute in any EJB container. This complies with the “write once, run
anywhere” concept of Java. Oracle provides an EJB container in Oracle Application
Server 10g Containers for J2EE (OC4J).
Types of EJBs
Session Bean
A session bean implements one or more business tasks. A session bean can contain methods
that query and update data in a relational table. Session beans are often used to implement
services. For example, an application developer can implement one or several session beans
that retrieve and update inventory data in a database.
Entity Bean
An entity bean is a complex business entity. An entity bean models a business entity or
multiple actions within a business process. Entity beans are often used to facilitate the
business services that involve data and computations on that data. For example, an
application developer might implement an entity bean to retrieve and perform computation
on items in a purchase order. Your entity bean can manage multiple, dependent, and
persistent objects while performing its necessary tasks. An entity bean is an object that
manages persistent data, performs complex business logic, potentially uses several
dependent Java objects, and can be uniquely identified by a primary key.
Client 2 Client 2
Session Beans
Session beans represent verbs in the business process such as “process order.” Session beans
are classified based on the maintenance of the conversation state:
• Stateless session beans: Stateless session beans do not have an internal state. They do
not keep track of the information that is passed from one method call to another. Thus,
each invocation of a stateless business method is independent of its previous
invocation; for example, calculating taxes or shipping charges. When a method to
calculate taxes is invoked with a certain taxable value, the tax value is calculated and
returned to the calling method, without the necessity to store the caller’s internal state
for future invocation. Because they do not maintain state, these beans are simple to
manage for the container. When the client requests a stateless bean instance, it may
receive an instance from the pool of stateless session bean instances that are
maintained by the container. Because stateless session beans can be shared, the
container can maintain a lesser number of instances to serve a large number of clients.
Entity Beans
An entity bean represents persistent data from the database. For example, an entity bean can
represent a row in a customer table, or an employee record in an employee table.
Entity beans are sharable across multiple clients. For example, an employee entity bean can
be used by various clients to calculate the annual salary of an employee or to update the
employee address.
Each entity bean instance is uniquely identified through its primary key.
An EJB server crash can result in the rollback of a transaction but does not destroy the entity
bean because the entity bean is a representation of permanent data from the database. The
same entity bean can be restored by reading from the persistent storage.
Specific fields of the entity bean object can be made persistent. Thus, based on their
persistence mechanisms, entity beans can be classified as follows:
• Container-managed persistence (CMP) beans: The container reads the information
of the persistent fields from the deployment descriptor and automatically manages the
persistence. The bean developer does not need to code the persistent logic because the
container performs all the functions that are necessary to save, load, and locate the
persistent data.
• Bean-managed persistence (BMP) beans: The bean developer must write the logic to
save, load, and locate the persistent data of the entity bean by using a persistence API
such as JDBC.
Oracle 10g: Build J2EE Applications 11-9
Message-Driven Beans
Pool of MDBs
Message-Driven Beans
Message-driven beans provide an easier method to implement asynchronous communication
than by using straight Java Message Service (JMS). MDBs were created to receive
asynchronous JMS messages from JMS queues or topics. The container handles most of the
setup processes required for JMS queues and topics. It sends all messages to the interested
MDB. The container invokes a bean from the queue or topic to handle each incoming
message from the queue or topic. No object invokes an MDB directly: all invocation for an
MDB comes from the container. After the container invokes the MDB, it can invoke other
EJBs or Java objects to continue the request. MDBs are responsible for coordinating tasks
that involve other session or entity beans.
An MDB is similar to a stateless session bean because it does not save conversational state
and is used for handling multiple incoming requests. However, instead of handling direct
requests from a client, MDBs handle requests that are placed in a queue. The diagram in the
slide demonstrates this by showing how clients place requests on a queue. The container
takes the requests from the queue and gives the request to an MDB in its pool.
EJB server
EJB container
Home/local Home/
home local home
interface object
EJB
EJB client Class
Remote/ Remote/
local local
interface object Database
Enterprise Services
Deployment
Naming, Transaction, Security,
descriptor
Messaging
EJB Architecture
The diagram in the slide shows the major components (classes, interfaces, and services) in
the EJB architecture. A basic EJB architecture consists of the following major components:
• The EJB server provides the server-side framework and services to the components.
• An EJB container isolates the beans from the specifics of the server, hosts the beans,
and maintains their life cycles. They also provide services such as naming (Java
Naming and Directory Interface [JNDI]), security, and transaction (Java Transaction
Service [JTS]) control.
• The EJB classes are beans themselves. They are the business components of the
application, and contain the implementation of the business and life-cycle methods.
• Home/local home interfaces and home/local home objects are object factories. Using
them, the client can create, get a reference to, or destroy instances of beans.
• Remote/local interface and remote/local objects mediate a client’s request to access
business methods on the EJBs. The remote/local interface is generally referred to as
the component interface. The component interface defines the services that the bean
provides to the client program.
• EJB clients are the applications that access the business methods of the EJB through
the EJB container.
• The deployment descriptor is an XML file that describes how the EJB should be
installed (deployed) into the server/container.
EJB Server
The EJB server provides a deployment platform and an organized environment to support
the execution of applications that are developed by using EJBs and other related
components. It provides services to the containers, which in turn provide services to the
bean. The EJB server manages and coordinates the allocation of resources to the
applications.
The EJB server makes EJB containers that are running within the server visible to the
outside world. The server provides JNDI-accessible naming services, secure socket layer
(SSL) support, transaction management services, and so on. All the bean home objects that
are hosted by the containers in the server are published in this server-provided naming
service. The clients look for the home interface by using the JNDI service.
The EJB server is responsible for communicating with the network, handling protocol
issues, and providing a place for the EJBs to execute.
EJBs are based conceptually on the Java Remote Method Invocation (RMI) model. For
example, remote object access and parameter passing for EJBs follow the RMI specification.
The EJB specification does not prescribe the transport protocol. The Oracle Application
Server 10g EJB server uses ORMI for its transport protocol.
EJB Container
The EJB container supplies the run-time environment for a deployed EJB. Containers ensure
that the EJBs are deployed properly and present an interface between the bean and the
server. All the service requests that the bean makes from its infrastructure are directed to the
container, which in turn delegates them to the server. A container manages the entire life
cycle of the bean—that is, its creation, destruction, passivation, and activation. The
container also manages remote access to the bean, security, transaction, distribution, and
other infrastructure issues. It performs all these functions with the help of the server. The
container generates the home object and remote object.
The EJB container also provides a naming context for the object. A particular class of an
enterprise bean is assigned to one EJB container. When a client application invokes a remote
method on an enterprise bean, the container verifies the invocation to ensure that the
persistence, transactions, and security are applied properly to every operation that a client
performs on the bean.
• Life-cycle management
• Bean instance pooling
• Client state management
• Database connection pooling
• Declarative transaction management
• Security
• Persistence
EJB Client
An EJB client is the application that accesses the bean. Although it does not necessarily
reside on the client tier, a client can be a stand-alone application, JSP, servlet, or another
EJB.
The client accesses the methods on the bean class through the EJB container. The container
generates a proxy for the bean, called the remote or local object. The client obtains reference
to this object through the home interface. When the client invokes a business method on the
bean, the remote or local object receives the request, delegates it to the corresponding bean
instance, and returns the results to the client.
Because a local client must run in the same JVM as the EJB, there is less overhead in
looking up the bean instance. The client accesses the methods of an EJB through the local
home and local interfaces of the bean. The client passes arguments to the bean by passing
the location of the argument to the bean.
A remote client accesses the methods of an EJB through the home and remote interfaces of
the bean. The client may reside in a different JVM or on a different machine than the EJB.
However, there is overhead involved in looking up the bean instance to access the bean
methods. Additionally, the client passes arguments to the bean methods by value. That is, an
argument in a remote call is a copy of an object. The bean processes the argument at the
copied location. The disadvantage in this method is that if the size of the argument is large,
there can be considerable overhead in copying the argument to a different location.
• Interfaces:
– Remote interface/Local interface
– Home interface/Local home interface
• Classes:
– Bean class
– Primary key class (entity beans)
• Remote interface:
– Extends the javax.ejb.EJBObject interface that
extends the java.rmi.Remote interface
– Describes the client view of an EJB
– Declares the business methods that are accessible
to remote clients
• EJB object:
– Is a container-generated implementation of a
remote interface
– Is a reference object that a client receives
– Delegates the method calls to a bean class after
doing some infrastructure work
• The remote interface and remote object are used
by session and entity beans.
Copyright © 2005, Oracle. All rights reserved.
• Home interface:
– Extends the javax.ejb.EJBHome interface that
extends the java.rmi.Remote interface
– Contains the life-cycle methods for creating,
removing, and locating the instances of a bean
class
– Contains home methods
– Are accessed by remote clients
• Home object:
– Is a container-generated implementation of the
home interface
– Uses callback methods on a bean class to perform
its functions
• Local interface:
– Extends the javax.ejb.EJBLocalObject interface
– Declares the business methods of the bean that are
accessible by a local client
– Improves performance because the bean resides in
the same JVM, and parameters are passed by
reference
• Local home interface:
– Extends the javax.ejb.EJBLocalHome interface
– Defines the life-cycle methods that are accessible
by local clients
• These interfaces are used by session and entity
beans.
• They enable relationships between entity beans.
Copyright © 2005, Oracle. All rights reserved.
Jar Deployment
Deployment EJB
command/ tools/
descriptor JAR
tool commands
JNDI
ejb-jar.xml File
The code in the slide shows major elements of an EJB deployment descriptor.
The tag <ejb-jar> indicates the beginning of the document. (The version and Document
Type Definition (DTD) for this XML file should be included before the beginning tag.) The
body of the deployment descriptor is enclosed within the <ejb-jar> and </ejb-jar>
tags.
Between the <enterprise-beans> and </enterprise-beans> tags, you declare
the details for the beans that are contained in this JAR file. The information described within
these tags contains the type of the bean, the names of the home and remote interfaces, and
the bean class. The details of the session beans are described with a <session> element,
those of entity beans with an <entity> element, and those of MDBs with a <message-
driven> element. Additionally, elements that are specific to individual EJB types are
contained within the bean descriptor. For example, a session bean should have a
<session-type> element, and an entity bean should have a <primary-key> element.
In the <assembly-descriptor> section, the security roles that are used to access the
beans and transaction attributes for the application are defined. Note that all the beans within
this JAR file share security and transactional declarations.
The details of the above elements are discussed in detail later in the course.
orion-ejb-jar.xml File
The orion-ejb-jar.xml file is the deployment descriptor for EJBs that are deployed to
Oracle Application Server 10g. It is used for customizing and specifying the dependencies of
the beans on the environment, such as resources and security, relationships between beans,
lists of parameters for controlling pooling, session timeout, interoperability, and concurrency
modes. The orion-ejb-jar.xml file is processed by OC4J at deployment. Note that
the ejb-jar.xml file is used for all J2EE containers. The orion-ejb-jar.xml is
specifically used by the OC4J server for EJB configuration within the OC4J container. Other
vendors have their own deployment descriptors, many of which can be created in
JDeveloper, although orion-ejb-jar.xml is created by default.
Summary
There are three types of EJBs:
• Session beans: Process business logic. They can access data from the database by
using direct JDBC calls, or by using an entity bean.
• Entity beans: Represent data in the database and also the methods to manipulate that
data. Each row of the data in a data object is represented by one entity bean.
• Message-driven beans: Are developed to enable asynchronous messaging with JMS
The EJB architecture contains:
• A server and container that are responsible for managing the life cycle of the EJBs and
for providing the system services. Deployment tools such as JDeveloper are used to
publish the beans on the EJB server.
• A client application that invokes methods on the bean
• A home interface that contains methods to create, find, and get metadata from the EJB
• A remote interface that describes the methods that a client application can invoke on
the EJB
• The bean class itself that contains the methods to process business logic
• Deployment descriptors that contain the properties of the bean that are used by the
container during the deployment process
Objectives
This lesson introduces session beans and different types of session beans. You learn the
difference between stateless session beans and stateful session beans. You develop a
stateless session bean and a client application to invoke the stateless session bean.
A session bean:
• Implements business processes
• Is short-lived and has the lifetime of a client’s
session
• Does not survive server, machine, or network
crashes
• Is not saved in permanent storage
• Implements the javax.ejb.SessionBean
interface
Session Beans
You have learned about the different interfaces and the bean class that constitute Enterprise
JavaBeans (EJB). You have also learned that there are three types of enterprise beans:
session beans, entity beans, and message-driven beans (MDB). You now learn about session
beans.
A session bean implements one or more business processes. A session bean can perform any
business process. For example, it can retrieve and update inventory data in a database. Note
that the session bean can retrieve or update the data but it does not represent the persistent
data. That is, a session bean is not directly associated with a row of a table.
Session beans are short-lived. Their life cycles are dependent on the client’s 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, then the state of the
previous instance is not restored. However, stateful session beans can survive crashes if they
are clustered.
javax.ejb.SessionBean Interface
Callback methods: A session enterprise bean class must implement the SessionBean
interface. This interface defines the methods that the container calls on the bean at various
stages to manage the bean life cycle and state. These methods are called callback methods.
The bean class must implement all the methods that are defined in the SessionBean
interface, or at least provide empty implementations. The client never directly accesses these
methods.
setSessionContext(SessionContext ctx): Enterprise beans are assigned a
context object when they are first created. Session beans are assigned a SessionContext
object. The beans save this context object for later processing. A bean uses its session
context to interact with the container regarding the security and transaction management.
The setSessionContext(SessionContext ctx)method takes this session
context as its parameter and is invoked in the beginning of the life cycle of a bean. This
method is invoked each time a session bean is created. The container calls
setSessionContext()on the bean instance when the client calls create()on the
home interface. Beans that manage their own transactions can use the session context to get
the transaction context. Session beans have session contexts that the container maintains and
makes available to the beans. The bean can use the methods in the session context to make
callback requests to the container.
Does not
exist
Ready
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatelessejbHome extends
EJBHome
{
Statelessejb create() throws RemoteException,
CreateException;
}
import javax.ejb.EJBObject;
import java.rmi.*;
Deployment Descriptor
The code in the slide is an example of a deployment descriptor written in Extensible Markup
Language (XML) for the stateless session bean StatelessejbBean.
The <ejb-jar> tag is the root element that is defined for a deployment descriptor. The
body of the deployment descriptor is enclosed within the <ejb-jar> and </ejb-jar>
tags.
Between the <enterprise-beans> and </enterprise-beans> tags, you declare
the definition of the beans that are contained in this JAR file. In the above example, the code
between the <session> and </session> tags indicates that the JAR file contains a
session bean. Within these tags, there are tags for:
• Optional description of the bean.
• Mandatory logical name of the bean that is used by the container while diverting the
client’s method calls to the appropriate bean on the server (Statelessejb).
• Mandatory home interface, remote interface, and bean class names.
• Mandatory session-type indicating that the bean is a stateless session bean. If the
bean is a stateful bean, then the session-type is stateful.
• Mandatory transaction-type (applicable only to session beans), indicating
whether the transaction is managed by the container or by the bean.
Client Application
An EJB client cannot access an EJB method directly. It must obtain a bean reference by
using the create() method of a bean’s home interface, and then invoke the business
methods on the bean reference that have been obtained.
To use the create() method of a bean’s home interface, the client must first obtain the
reference to the home interface of the bean. When a bean is deployed in a server or
container, the server or container publishes the home interface of the bean in a publicly
available JNDI service. The create() method creates an instance of the bean in the server
and returns its reference to the client. The clients can obtain the reference to the bean home
interface by looking for it in the JNDI.
JNDI consists of several published objects that are arranged in a hierarchical manner. You
must know the URL of the object that you want to locate.
...
// Invoke the business methods with each of the
// instances created to observe the state of each
// instance
for (int i=0;i<3;i++)
{
System.out.println("Value before increment for
object" + i + " "+ obj[i].getValue());
System.out.println( "Calling incrementValue with
object" + i+" " +obj[i].incrementValue());
System.out.println("Calling getValue with
object" + i+" " +obj[i].getValue()+"\n");
}
for (int i=0;i<3;i++)
{ obj[i].remove(); }
...
Does not
exist
ejbPassivate()
Ready Passivated
instances
ejbActivate()
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatefulejbHome extends
EJBHome
{
Statefulejb create(int x) throws
RemoteException, CreateException;
}
...
Statefulejb obj[]= new Statefulejb[3];
for (int i=0;i<3;i++)
{ obj[i]= StatefulejbHome.create(0); }
for (int i=0;i<3;i++)
{
System.out.println("Value before increment for
object" + i + " "+ obj[i].getValue());
System.out.println( "Calling incrementValue with
object" + i+" " +obj[i].incrementValue());
System.out.println("Calling getValue with
object" + i+" " +obj[i].getValue()+"\n");
}
for (int i=0;i<3;i++)
{ obj[i].remove(); }
...
Summary
In this lesson, you should have learned about session beans and the types of session beans.
You should have also learned to develop a stateless session bean and invoke it with a client
application.
Entity EJBs
Objectives
This lesson introduces the concept of entity beans and the different types of entity beans.
You learn about the different components of an entity bean and the differences between
entity beans and session beans.
Entity Beans
Entity beans are objects that can be stored permanently. They represent data stored in the
database in the form of objects. Each object can represent a row in a table, and each field of
the table can be a variable of the object.
Why Data Should Be in the Form of Objects
Data in the form of objects is easier to handle and manage. Related data can be grouped
together. For example, all data related to a particular employee (employee ID, first name,
last name, and so on) can be grouped together in an object. You can also provide methods to
retrieve or manipulate the information that is associated with an object.
To summarize, entity beans are objects just like session bean objects. However, they
represent persistent data in the database. Entity beans are generally represented by nouns
such as names, departments, bank accounts, addresses, phone numbers, and so on.
int x
String s
float f
int y
double d
• ejbLoad()loads the
data from the
persistent storage to
the bean.
• ejbStore()saves the
data from the bean
instance to the
persistent storage.
• BMP beans:
– Contain code for managing data persistence
– Provide flexibility for bean developers to manage
state
– Are complicated to program
• CMP beans:
– Do not contain code for managing persistence
because the container manages the persistence
– Use abstract persistence schema and define the
data retrieval/manipulation logic in the deployment
descriptor
– Are easier to program and contain lesser code
An entity bean:
• Can have one or more finder methods in home
interface
• Must have a findByPrimaryKey(primarykey)
method
• Has finder methods that:
– Find row or rows in the database table
– Contain parameters that locate the requested entity
object
– Return entity bean’s component interface reference
or collection of objects of component interface type
– Must throw FinderException
– Must throw RemoteException in a remote home
interface
– Have find as a prefix in their names
• Primary key:
– Uniquely identifies each bean instance
– Is used to find or remove an entity bean
– Can be of any legal value type in RMI-IIOP
• The primary key class:
– Should implement java.io.Serializable
– Can have a single primary key (a single field) to
identify the entity bean
– Can have composite keys (multiple fields) to
identify the entity bean
javax.ejb.EntityBean Interface
The slide shows the definition of the EntityBean interface. This interface contains
callback methods that are used during the life cycle of an entity bean.
After the entity bean is created through the ejbCreate() method, the data is inserted into
the database and is ready to be accessed by the client. When a client requests information,
the data must be retrieved from the database and stored into the database when there is data
manipulation such as update or delete of the entity bean. The container manages these
activities by using the callback methods that are described in the slide.
You have already learned that the ejbLoad()and ejbStore() methods are used to
transfer data between persistent storage and the bean instance. These are the callback
methods that are used for saving state during passivation and for loading state during
activation. The ejbActivate() and ejbPassivate() methods are called by the
container before and after an entity bean is swapped out and into the temporary storage.
The container invokes the ejbRemove() method when the client invokes the remove()
method. For a BMP bean, you must remove the data from the database that is associated
with the bean within this method. For a CMP bean, this method is automatically
implemented by the container.
Pooled
ejbCreate()
ejbPostCreate() ejbActivate() ejbPassivate() ejbRemove()
Clients invoke
business methods
Deployment Descriptor
The two main elements in the deployment descriptor of an entity bean are <enterprise-
beans> and <assembly-descriptor>.
The <enterprise-beans> element contains the details of the bean class, primary key
class, and interfaces. This element contains a subelement called <entity>, which
indicates that the enterprise bean being described is an entity bean.
The <assembly-descriptor> element contains information about the security roles,
methods that are accessible for different roles on different beans, and so on. It is the bean
assembler’s responsibility to define these roles and responsibilities.
The slide shows the elements in a deployment descriptor. <ejb-jar> is the root element
of the descriptor. Note the various tags in <entity>. The <home>, <remote>, and
<ejb-class> tags provide information about the elements of the entity bean. The
<persistence-type> tag is used to specify whether the bean is a BMP bean or a CMP
bean. <prim-key-class> contains the name of the primary class, which is used to
uniquely identify the entity bean.
...
<assembly-descriptor>
<security-role>
<description>Public</description>
<role-name>PUBLIC</role-name>
</security-role>
<method-permission>
<description>Public methods</description>
<role-name>PUBLIC</role-name>
<method>
<ejb-name>...</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
</assembly-descriptor>
</ejb-jar>
Summary
In this lesson, you should have learned about entity beans and different types of entity beans.
You have seen the differences between session beans and entity beans, and should now be
able to decide when to use entity beans. You should also have learned about the various
components that build an entity bean and the life cycle of the entity bean.
ejbStore() Releases the resources held by the entity bean and saves
the bean state to the underlying storage. The bean instance
is put into a generic instance pool.
Objectives
You have learned about different types of entity beans in the lesson titled “Managing
Persistent Data in the Business Tier.” This lesson provides an overview of BMP beans and
discusses CMP beans in detail. You learn to develop a CMP bean, deploy the bean, and
invoke the methods on the bean with a client application.
ejbFind()
ejbcreate()
ejbLoad()
ejbStore()
setXXX() and
getXXX() abstract
...
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Departments extends EJBObject
{
// set and get methods for CMP fields
Long getDepartment_id() throws RemoteException;
void setDepartment_id(Long newDepartment_id)
throws RemoteException;
String getDepartment_name()throws
RemoteException;
void setDepartment_name(String
newDepartment_name) throws RemoteException;
...
}
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
public interface DepartmentsHome extends EJBHome
{
Departments create() throws RemoteException,
CreateException;
Departments findByPrimaryKey(Long primaryKey) throws
RemoteException, FinderException;
Collection findAll() throws RemoteException,
FinderException;
Departments create(Long department_id, String
department_name) throws RemoteException,
CreateException;
}
...
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
public abstract class DepartmentsBean implements
EntityBean
{ private EntityContext context;
public void setEntityContext(EntityContext
ctx)
{
context = ctx;
}
public void unsetEntityContext()
{
context = null;
}
public abstract Long getDepartment_id();
public abstract void setDepartment_id(Long
newDepartment_id);
...
...
public Long ejbCreate()
{ return null; }
public void ejbPostCreate()
{ }
public Long ejbCreate(Long department_id,
String department_name)
{
setDepartment_id(department_id);
setDepartment_name(department_name);
return department_id;
}
public void ejbPostCreate(Long department_id,
String department_name)
{ }
...
...
public void ejbActivate()
{ }
public void ejbLoad()
{ }
public void ejbPassivate()
{ }
public void ejbRemove()
{ }
public void ejbStore()
{ }
}
<cmp-field>
<field-name>department_id</field-name>
</cmp-field>
<cmp-field>
<field-name>department_name</field-name>
</cmp-field>
<cmp-field>
<field-name>manager_id</field-name>
</cmp-field>
<cmp-field>
<field-name>location_id</field-name>
</cmp-field>
<primkey-field>department_id</primkey-field>
</entity>
</enterprise-beans>
</ejb-jar>
<enterprise-beans>
<entity-deployment name="Departments"
data-source="jdbc/hrDS" table="DEPARTMENTS">
<primkey-mapping>
<cmp-field-mapping name="department_id“
persistence-name="DEPARTMENT_ID"
persistence-type="NUMBER(4)"/>
</primkey-mapping>
<cmp-field-mapping name="department_id“
persistence-name="DEPARTMENT_ID"
persistence-type="NUMBER(4)"/>
<cmp-field-mapping name="department_name“
persistence-name="DEPARTMENT_NAME“
persistence-type="VARCHAR2(30)"/>
...
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
...
public class DepartmentsClient
{
public static void main(String [] args)
{
DepartmentsClient departmentsClient =
new DepartmentsClient();
try
{
Context context = getInitialContext();
DepartmentsHome departmentsHome =
(DepartmentsHome)PortableRemoteObject.narrow
(context.lookup("Departments"), DepartmentsHome.class);
Departments departments;
...
Summary
In this lesson, you should have learned that:
• The bean provider furnishes the logic to manage the persistence in case of BMP entity
beans
• The container provides the persistence logic in CMP entity beans
You should have also learned how to develop a CMP bean and how to invoke the bean
methods from a client application.