Beruflich Dokumente
Kultur Dokumente
Applications
Student Guide Volume 1
D17247GC10
Production 1.0
May 2004
D39456
Authors
Lynn Munsinger
Sunitha Patel
Technical Contributors
and Reviewers
Anna Atkinson
Scott Brewton
Kenneth Cooper
Craig Hollister
Taj-ul Islam
Istvan Kiss
Peter Laseau
Glenn Maslen
Monica Motley-Mosser
Nagavalli Pataballa
Holger Dindler-Rasmussen
Glenn Stokol
Vasiliy Strelnikov
Venkat Tallapragada
Publisher
S. Domingue
Oracle and all references to Oracle Products are trademarks or registered trademarks
of Oracle Corporation.
All other products or company names are used for identification purposes only, and
may be trademarks of their respective owners.
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 OverviewObjectives
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
Data Sources 2-32
Application Logging 2-33
J2EE Application Deployment to
Oracle Application Server 10g 2-34
iii
iv
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
5 Accessing the Database with Servlets
Objectives 5-2
Review of JDBC 5-3
Querying in JDBC 5-4
JDBC and Servlets 5-5
Synchronizing Shared Resources 5-6
Transaction Handling 5-7
Connection Pooling 5-9
Data Sources 5-10
Data Source Definition 5-11
data-sources.xml: Example 5-12
Using Data Sources 5-13
Summary 5-14
Practice 5-1: Overview 5-15
6 Using Advanced Techniques in Servlets
Objectives 6-2
Overview 6-3
HTTP Headers 6-4
Request Headers 6-5
Sending a Response 6-6
Response Headers 6-7
Setting Status Codes 6-8
Example 6-9
Sending Multimedia Content 6-10
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
vii
viii
ix
xi
xii
xiii
xiv
xv
xvi
Preface
Preface - 2
Profile
Before You Begin This Course
Before you begin this course, you should have the following qualifications:
Prerequisites
Preface - 3
Typographic Conventions
Typographic Conventions in Text
Convention
Element
Example
Bold
Bold italic
Brackets
Key names
Press [Enter].
Caps and
lowercase
Buttons,
check boxes,
triggers,
windows
Carets
Menu paths
Commas
Key sequences
Preface - 4
Convention
Object or Term
Example
Courier New,
case sensitive
Code output,
SQL and PL/SQL
code elements, Java
code elements,
directory names,
filenames,
passwords,
pathnames, URLs,
user input,
usernames
Initial cap
Graphics labels
(unless the term is a
proper noun)
Italic
Emphasized words
and phrases in print
publications, titles of
books and courses,
variables
Plus signs
Key combinations
Quotation
marks
Preface - 5
Introduction
Course Objectives
1-2
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 Objectives
1-3
Course Environment
1-4
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 Oracle10g database.
Course Overview
1-5
Course Overview
1-6
Course Overview
1-7
1-8
1-9
1-10
Employee entity
No
Process
log in
View
employees
process
Administrator?
Yes
Insert
employees
process
1-11
Summary
1-12
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.
J2EE Overview
Objectives
2-2
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.
2-3
J2EE Platform
2-4
Browser
JSP Page
Web clients
Web components
Application
Enterprise
Beans
EJB clients
EJB components
Client tier
Middle tier
EIS tier
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 Oracle10g.
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.
Oracle10g: Build J2EE Applications 2-4
2-5
2-6
J2EE Components
2-7
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.
J2EE Architecture
The J2EE architecture provides a component-based and platform-independent environment,
in which each component is assembled and deployed into its corresponding container. The
J2EE server provides services to handle transaction and state management, multithreading,
resource pooling, and other complex low-level details, in the form of these containers.
Because these underlying services are provided by the J2EE server, the developer can
concentrate on solving business problems.
J2EE components communicate with each other by using several APIs. The J2EE
architecture provides the following APIs to support remote procedure calls:
Java Naming and Directory Interface (JNDI): Provides naming and directory
functionality to applications written in Java
Remote Method Invocation (RMI): Enables you to create distributed Java
technologybased applications, in which the methods of remote Java objects can be
invoked from other Java virtual machines, possibly on different hosts
Java Database Connectivity (JDBC): Enables you to access any tabular data source
such as database, spreadsheets, or flat files from the Java programming language
Java Transaction API (JTA): Specifies standard Java interfaces between a
transaction manager and the parties involved in a distributed transaction system: the
resource manager, the application server, and the transactional applications
Java Messaging Services (JMS): Enables applications to create, send, receive, and
read messages by defining a common set of interfaces and associated semantics that
allow programs written in the Java programming language to communicate with other
messaging implementations
JavaMail: Provides a set of abstract classes that model a mail system. The API
provides a platform-independent and protocol-independent framework to build Java
technology-based mail and messaging applications.
JavaBeans Activation Framework (JAF): Provides standard services to determine
the type of an arbitrary piece of data, to encapsulate access to it, to discover the
operations that are available on it, and to instantiate the appropriate bean to perform
the said operations. For example, if a browser obtains a JPEG image, this framework
enables the browser to identify that stream of data as a JPEG image. Then the browser
can locate and instantiate an object that can manipulate or view that image.
Additionally, the JavaMail API uses the JAF API for data content handling.
Client-Tier Components
A Web browser:
Is used for a Web-based J2EE application
Downloads static or dynamic Web pages from Webtier components
Is a thin client
An application client:
2-10
Client-Tier Components
Web Browser Client
For a Web-based J2EE application, the users Web browser is the client component. The
Web browser downloads static or dynamic Web pages from the Web tier to a client
machine.
Dynamic Web pages are generated by servlets 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 users 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.
Oracle10g: Build J2EE Applications 2-10
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.
What Is a Servlet?
Servlet
Browser
Request
Process results
(access database)
Format results and produce
HTML
Success or failure
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 clients 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)
2-14
JSPs:
Combine HTML (or other markup) and Java
Are designed to separate content creation from
presentation logic
Are precompiled and converted to servlets at run
time
2-15
Business-Tier Components
Business-tier components:
Are EJBs
Handle business logic
Receive data from client programs
Retrieve data from database storage
Process the data and communicate with the
database and the client program
Can be invoked by the Web-tier components
2-16
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
2-17
2-18
J2EE Server
2-19
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.
2-21
J2EE Applications
2-22
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)
4. DD for J2EE application (.xml)
DD = XML Deployment
Descriptor
2-23
JARs
2-24
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.
WARs
welcome.jsp
2-25
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.
EJB JARs
2-26
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 applicationspecific XML files. This is recommended because it keeps the global and default
configuration files separate from the application-specific configuration files. The orionejb-jar.xml file is used by OC4J to deploy EJBs. Its use is discussed in detail later in
the course.
EARs
2-27
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 modulesHTML pages, JSPs, Servlets, EJBs, manifest files, and
XML configuration filesthat are needed to distribute an entire application. All these files
are contained in a single archive file with a standard organization.
2-28
OC4J Architecture
Oracle HTTP
Server
HTTP
JNDI
AJP
mod_oc4j
AJP13
Web
container
JMS
JDBC
JTA
Client
JAAS
ORMI
EJB
container
JCA
JavaMail
ORMI
JAF
EJB client
2-29
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.
Oracle10g: Build J2EE Applications 2-29
Web site
Web
Website
site
jazn.xml*
jazn-data.xml*
default-website.xml
data-sources.xml
rmi.xml
jms.xml
Oracle HTTP Server
configuration files
mod_oc4j.conf
2-30
<application name="lesson02"
path="../applications/lesson02.ear" />
2-31
Data Sources
2-32
Data Sources
Data sources are a portable method for creating JDBC connections. The datasources.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
2-33
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: 9.0.4.0.0 Started
04/02/25 01:04:36 practice02-login-webapp: LoginServlet: init
Step 2: Deploy
Step 2: Deploy
2-34
localhost
2-35
2-36
Code insight
Copyright 2004, Oracle. All rights reserved.
Design in visual
or code views
2-38
Modify values
in property
inspector
Copyright 2004, Oracle. All rights reserved.
Summary
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.
2-40
Practice 2-1
In this practice, you navigate to the Oracle Enterprise Manager console, modify the default
data source, and restart the OC4J server. Additionally, this practice gives you the
opportunity to view the files that OC4J uses to configure a J2EE application. You also
deploy an existing application by using Oracle Enterprise Manager.
1. Navigate to the Oracle Enterprise Manager console.
a. Open a browser and navigate to http://localhost:1810.
b. Enter the username ias_admin and the password welcome1.
c. Navigate to the home instance page by clicking the home link.
2. Create a data source reference.
a. Click the Administration tab and click the Data Sources link.
b. Click Create and enter these details:
Name: hrDS
Description: hr
Data Source Class: com.evermind.sql.DriverManagerDataSource
JDBC URL: The URL provided to you by your instructor
JDBC Driver: oracle.jdbc.driver.OracleDriver
In Datasource Username:
Username: oraxx (as provided to you by your instructor)
Use a cleartext password of oracle
In JNDI Locations:
Location: jdbc/hrCoreDS
Transactional location: jdbc/xa/hrXADS
EJB location: jdbc/hrDS
Leave all other fields blank or set to the default.
c. Click Create and restart OC4J when prompted.
3. Verify the change that you made to the data source.
a. Navigate to the oraas10g directory and locate the j2ee\home\config
directory.
b. Open data-sources.xml in WordPad. Note that the data source that you
added in step 2 is defined here.
c. You may also want to view application.xml, server.xml, and other
configuration files that are discussed in this lesson.
4. Deploy an existing J2EE application by using Oracle Enterprise Manager. The
application you deploy in this step is actually the application that you will build in
practice 17.
a. Click the applications tab from the OC4J home page and click Deploy EAR File.
b. Browse to the <JDEV_HOME>\jdev\mywork\practice02 directory and
select application1.ear.
c. Name the application practice02 and click Continue.
d. Modify the URL Mapping as /practice02 and click Next.
e. Enter jdbc/hrCoreDS for the JNDI location name and click Next.
Objectives
3-2
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
3-4
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.
Business-tier patterns
Business delegate
Transfer object
3-5
Presentation (View)
View
Controller
Model
3-6
The Model
3-7
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 faade. For example, a session faade 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 faade bean implements.
The View
3-8
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
3-9
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 users 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.
Controller
Selected
view
Model
Method
invocation
Return
result
Servlet
JSP
HTTP
request
Enterprise
JavaBeans
HTTP
response
Browser
3-10
3-11
Customer
Receive
order
status
Log in
Place
orders
Fill orders
Browse
products
Update
inventories
Administrator
Vendor
3-12
Summary
3-13
3-14
Practice 3-1
In this practice, you identify the MVC components for a sample application by using the
design patterns and architectures that are discussed in this lesson.
Using the sample flow diagram given in slide 12, decide how the processes are
implemented in the J2EE components. Match each process to its possible
implementation:
Log in
Receive
order
status
Place
orders
Browse
products
Fill orders
Update
inventories
Objectives
Objectives
This lesson explains the servlet technology architecture, and discusses the creation of a
servlet in JDeveloper.
Overview
Requests
Connects to
Servlet
Generates
Responds
Dynamic HTML
4-3
Overview
The basic concepts of servlets are straightforward. A Web browser invokes a URL, which
calls the servlet. The servlet then generates dynamic HTML, Extensible Markup Language
(XML), or other content. The dynamic text may have been generated by connecting to the
database. The following questions arise:
How can multiple clients be satisfied efficiently?
How can the programmers task be simplified, although the program remains powerful
enough to handle all situations?
This lesson discusses the answers to these questions.
Java application,
Servlet, JSP,
or HTML
Request
Servlet engine
Response
Client
Server
4-4
Request 2
Request 3
Server
Clients
4-5
Load
Initialize
init()
3
Execute
service()
4
Destroy
destroy()
4-6
HTTP Servlets
Client
4-7
Response
HTTP protocol
Servlet
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.
HttpServlet subclass
doGet()
Request
service()
Browser
Response
4-8
Servlet: Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimplestServlet extends
HttpServlet
{
public void doGet(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
4-9
Servlet: Example
The code in the slide shows the simplest form of a servlet. This servlet prints the plain text
Hello World when invoked.
4-10
4-11
4-12
Request methods
Return values
getServerName()
bighost
getServerPort()
80
getPathInfo()
/finance/servlet/Ledger/June.class
getServletPath()
/servlet/Ledger.June
getContextPath()
/finance
getRequestURI()
/finance/servlet/Ledger.June
4-13
setContentLength(
)
sendRedirect()
4-14
4-16
destroy():
Takes no arguments
Is invoked when the servlet is about to be unloaded
Is useful for releasing resources
4-18
Error Handling
ServletException:
Is generated to indicate a generic servlet problem
Is subclassed by UnavailableException to
indicate that a servlet is unavailable, either
temporarily or permanently
Is handled by the servlet engine in implementationdependent ways
4-19
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
4-20
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
4-21
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.
SingleThreadModel (continued)
The following table describes types of variables and attributes and whether they are thread
safe:
Variable/Attribute
Thread Safe?
Local variables
Thread safe
Instance variables
Class variables
Request attributes
Session attributes
Context attributes
JDeveloper Environment
4-23
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
4-24
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, Apaches default port is 80; OC4Js 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.
</web-app>
4-25
http://localhost:8989/<contextroot>/servlet/package1.HelloWorld
http://localhost:8989/<context-root>/helloworld
The virtual directory of /servlet comes from the J2EE Web server configuration. It is
included automatically when running a servlet that is mapped in the web.xml file. Note
that in OC4J, this mapping is set in the global-web-application.xml file.
Invoking a Servlet
4-26
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.
4-27
4-28
Deploying to OC4J
4-29
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.
Summary
4-30
4-31
Practice 4-1
The purpose of this practice is to create the login form for the J2EE application that you are
developing. You create and run an HTML form and an HTTP servlet. Run JDeveloper by
using the desktop shortcut. Open the practice04 workspace in the practice04 folder
and navigate to the login project.
1. Modify an HTML form for logging in to an application.
a. Expand the login project and the Web Content folder. Open the
login.html file in the code editor by double-clicking the file.
b. There are two text areas in this form (you can switch between the visual and code
views using the Design and Source tabs) . The text areas have labels but no
names. Complete the <input type="text" name=""> code to include a
name for both the text areas. These are the values that you pass to the request
object and, therefore, it is important to follow standard naming conventions so
that you can refer to the value later. You can perform this step by using the code
editor, or by selecting the text item box in the visual editor and modifying the
name property in the property inspector.
c. Modify the form so that the action tag points to firstservlet. You create
the servlet in the next step.
d. Optionally, modify the forms layout. Add a style sheet by selecting CSS from
the component palette dropdown list and then dragging a style sheet to the
.html file.
e. Save the login.html file.
2. Create a new HTTP servlet.
a. With the login project selected, Select File > New from the menu. Select the
Web Tier > Servlets category and then the HTTP Servlet item and click OK.
b. Click Next to dismiss the first page of the wizard.
c. Ensure that the package name is login and name the class FirstServlet.
d. Because you are sending a POST action from the form, select the doPost()
method in the Servlet Wizard, in addition to doGet(). This ensures that the
doPost() skeleton code is generated. Click Next.
e. Click Next to leave the servlet parameters empty for now.
f. The last step in creating a servlet is the mapping details. Select the check box to
specify a name for the servlet, and accept the default values.
g. Click Finish. You have created FirstServlet.java, a servlet with skeleton
code for the doGet() and doPost() methods.
h. Open the web.xml file in the code editor. Note that login.FirstServlet
is mapped to /firstservlet.
3. Modify the HTTP servlet to handle the login.
a. Add code to the doPost() method to retrieve the Customer Name parameter
from the request object. Remember that the value being passed is the
parameter that you specified in step 1.b, not Customer Name. Remove the
out.println statement containing "The servlet has received a POST"
b. Add code to the doPost() method to greet the customer by using his or her
name in the greeting. If the customer does not enter a name, the name is an
empty string. In this case, greet an anonymous user.
Hint: Use the skeleton code that is provided as a template, to properly format
your document by ensuring that the appropriate HTML tags are used.
Oracle10g: Build J2EE Applications 4-32
Practice 4-2
In this practice, you use the doGet() method to combine the login process completed in
Practice 4-1 into a single servlet. The servlet creates the login form and runs initially, rather
than login.html.
1. Create a servlet to handle the login process.
a. In the login project, create a new servlet as in step 2 of practice 4-1.
b. Select login as the package name and name the class LoginServlet.
c. Select the doGet() and doPost() methods in the Servlet Wizard. This
ensures that the skeleton codes of both the methods are generated as in
Practice 4-1.
d. Click Next to leave the servlet parameters empty.
e. This servlet contains an HTML form that references the doPost() method. As
before, the URL pattern for this servlet matches the virtual path in the action
tag of the doGet() method. Create a mapping for this servlet as
/loginservlet.
f. Click Finish and you have created LoginServlet.java, with skeleton code
for the doGet() and doPost() methods.
2. Modify the doPost() method.
a. Copy the doPost() method from FirstServlet.java and paste it into
the doPost() method of LoginServlet.java. This ensures that the login
process remains the same, whereas the URL being called to log in changes.
b. Right-click inside the code editor and select Make to compile
LoginServlet.java.
3. Modify the doGet() method to create the form that is used in login.html.
a. Create a variable to store the servlets Uniform Resource Identifier (URI) from
the request.getRequestURI() method.
b. Copy the contents of login.html and paste into the doGet() method of
LoginServlet.java, just below the line PrintWriter
out=response.getWriter();. Remove the out.println statement
containing "The servlet has received a GET"
c. Modify the HTML code so that it is wrapped in out.println statements. This
also involves eliminating quotes from the HTML and adding escape characters
where necessary. Specify the variable you created in step 3a for the value of the
action tag. For example, the first four lines of the statements should be:
out.println("<html>");
out.println("<head><title>Login to Order
Entry</title>");
out.println("<link rel=stylesheet
href=\"css/oracle.css\" media=\"screen\"/></head>");
out.println("<body>" + "<form method=\"post\" " +
"action=" + <yourservleturivariable> + ">"
d. Continue to concatenate statements and eliminate extraneous quotes until the
HTML is formatted properly in the servlet.
Practice 4-3
In this practice, you deploy the application that you built in the previous practices.
1. First, create a connection to your Oracle Application Server 10g instance.
a. Click the Connections tab in the Application Navigator. Right-click Application
Server and select New Application Server Connection.
b. Name the connection OracleAS10g and specify Oracle Application Server 10g
as the connection type. Click Next.
c. Provide welcome1 as the password for the ias_admin user and click Next.
d. Accept the default host name and port and specify the ORACLE_HOME directory
for the Oracle Application Server 10g install, E:\oraas10g, and click Next.
e. Click Next and in the following page, click Test Connection. When the status
message indicates success, click Finish.
2. Create a deployment profile for the application.
a. Right-click the login project and select New.
b. Select Deployment Profiles within the General category and create a WAR file
deployment profile for this project.
c. Name the deployment profile login and click OK.
d. Specify the J2EE Web Context Root as /practice04, accept all other default
settings, and click OK.
3. Deploy the application.
a. Right-click the deployment profile and deploy to the OracleAS10g connection
that you created in step 1.
b. When you see the text Deployment Finished in the message window, the
application is deployed.
c. Access the application by using the following URL:
http://localhost/practice04/loginservlet
Objectives
5-2
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
5-3
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 Serviceenabled 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
Querying in JDBC
Connect
Query
Process results
Close
5-4
import java.sql.*;
DriverManager.registerDriver()
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin
Statement stmt =
conn.createStatement ();
ResultSet rset =
stmt.executeQuery (
"select * from EMPLOYEES");
while (rset.next ())
System.out.println(
rset.getString (2));
rset.close();
stmt.close();
conn.close();
5-5
synchronized (ps) {
ps.clearParameters();
ps.setInt(1,3);
ps.setDouble(2, 3.14);
ps.executeUpdate();
}
5-6
Transaction Handling
5-7
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).
Oracle10g: Build J2EE Applications 5-7
Connection Pooling
5-9
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.
Data Sources
5-10
Application-specific data sources: Use the <datasources> tag in the application.xml file.
OC4J_HOME/applications
myapp
application.xml
Points to
data-sources.xml
5-11
data-sources.xml: Example
<data-source
class="com.evermind.sql.DriverManagerDataSource"
connection-driver="oracle.jdbc.driver.OracleDriver"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleDS"
ejb-location="jdbc/OracleDS"
min-connections="5"
max-connections="25"
username="oe"
password="oe"
url="jdbc:oracle:thin:@<host>:<port>:<SID>"
/>
5-12
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.
Oracle10g: Build J2EE Applications 5-12
5-13
Summary
5-14
5-15
Practice 5-1
The purpose of this practice is to create a servlet that interacts with a database by using
JDBC. The customer number and name provided in LoginServlet.java is validated in
the CUSTOMERS table of the database, and the customer is shown a list of his or her existing
orders. In JDeveloper, open the practice05.jws workspace.
1. Create the connection to use as the data source for the servlet.
a. Select File > New and select Connections from the General category.
b. Select Database connection and click OK.
c. Name the connection oe and specify an Oracle JDBC connection type.
d. The username is orann (as indicated by your instructor) and the password is
oracle. The password should be deployed at run time.
e. Enter the host, port, and SID as indicated by your instructor.
f. Test the connection and click Finish to close the wizard.
g. You are now able to look up this data source reference by using its <ejblocation> name, jdbc/oeDS.
2. Modify LoginServlet.java to include the new functionality.
a. Double-click the verifylogin project and navigate to the Libraries tab to add
the Oracle JDBC library to your project.
b. Open LoginServlet.java in the verifylogin project.
c. Import the javax.naming (for the resource lookup), javax.sql (for the
DataSource class), java.sql (for the Connection class), and
oracle.jdbc packages to the LoginServlet.
d. Create instance variables for the Connection (as conn), the DataSource
(as ds), and the PreparedStatement (as ps) objects.
e. In a try/catch block of the init() method, use the lookup method of the
Context class to retrieve the data source that you created in step 1.
f. Catch a NamingException if the name is not found.
g. In the try block, initialize the connection object. Catch a SQLException.
h. Also in the try block, create a PreparedStatement object from the
Connection object that is stored in the PreparedStatement object
declared in step 2.d. The query string should select all columns from the
ORDERS table for all orders with the CUSTOMER_ID equal to a bind variable
parameter.
i. Create the destroy() method to close the connection and prepared statement
objects that you created in a try/catch block. Catch a SQLException.
3. Create the functionality to validate the provided name and ID.
a. Create a new synchronized boolean method in the servlet to verify the customer
information. This method accepts the connection, the customer ID, and the
customer name as arguments, and throws a SQLException.
b. Create a method variable to initialize the customer ID.
c. Create an instance of the Statement object.
Note that you are appending the variables to the String object that you
declared in the first step, and formatting the data in a table.
g. Close your ResultSet object outside the while loop.
h. Return yourStringVariableName. Note that this represents a string of
HTML output, including a list of all the orders placed by a given customer.
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
6-2
Objectives
This lesson discusses additional topics in creating a servlet.
Overview
Request
getCookies()
getHeader()
Response
Client Web
browser
Servlet
setHeader()
addCookie()
Error handling
6-3
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
6-4
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
6-5
Accept
AcceptLanguage
Cookie
Referer
User-Agent
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-UnmodifiedSince
Pragma
Proxy-Authorization Range
Referer(misspelled
Upgrade
User-Agent
due to HTTP author
Via
Warning
error)
Oracle10g: Build J2EE Applications 6-5
Sending a Response
6-6
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
6-7
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
Location
Content-Encoding
Is used to encode the response body. Example values are xgzip and x-compress.
Cache-Control
Example:
int pageVersion =
Integer.parseInt(req.getParameter("pageVersion"));
if (pageVersion >= currentVersion){
response.setStatus(response.SC_NO_CONTENT);
}else{
//Send original page
}
6-8
Code
Default
Message
Meaning
SC_OK
200
OK
SC_NO_CONTENT
204
No Content
SC_MOVED_TEMPORARILY
302
Temporary
Move
Example
6-9
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.
6-10
finally
{
//clean up resources
if(g!=null) g.dispose();
if(frame!=null) frame.removeNotify();
}
}
}
Cookies
6-12
Cookies
The following table describes the methods that are available for use with cookies and their
purposes:
get/setMaxAge
get/setName
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
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.
Oracle10g: Build J2EE Applications 6-12
Setting Cookies
6-13
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
6-14
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.
6-15
ServletContext
6-17
ServletContext
The following table provides some of the methods of ServletContext and their uses:
Method
Purpose
getContext(String)
getMimeType(String)
getRequestDispatcher(String)
getServerInfo()
getServletContextName()
RequestDispatcher
6-18
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
6-19
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
6-20
Servlet Filters
Servlet filters are a new feature of the Servlet 2.3 API, and can be used to intercept and
modify a servlets 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
6-21
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
6-22
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
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.
Configuring Filters
6-24
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>
6-25
ServletContext Events
6-26
ServletContext Events
The following table describes the types of methods that are invoked for each type of
ServletContext event:
Events
Methods
ServletContext is
created or is shutting
down.
contextInitialized()or
contextDestroyed() methods of the
ServletContextListener class
attributeAdded(),
attributeRemoved(), or
attributeReplaced() methods of the
ServletContextAttributeListener
class
HttpSession Events
6-27
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
been activated or is
about to be destroyed.
sessionCreated() or
sessionDestroyed() methods of the
HttpSessionListener class
attributeAdded(),
attributeRemoved(), or
attributeReplaced() methods of the
HttpSessionAttributeListener
class
6-28
</servlet>
</web-app>
Note that the listener attribute must directly precede the servlet element in the
web.xml file.
Error Handling
6-29
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);
}
Summary
6-30
6-31
Practice 6-1
The purpose of this practice is to use cookies within multiple servlet instances. You modify
the LoginServlet.java file that you created in practice 5. This servlet uses a cookie to
store the users name and retrieve that value when the user accesses the servlet. Open the
practice06.jws workspace and navigate to the newlogin project. Open
LoginServlet.java in the code editor.
1. Add code to the doPost() method of LoginServlet.java servlet to create a
cookie.
a. Create a new Cookie object named LoginCookie. The cookie value will be
the variable that holds the custName value.
b. Set the cookies maximum age to two minutes.
c. Add the cookie to the response object to send it to the browser.
2. Retrieve the cookie from the browser. Add the following code to the doGet()
method of LoginServlet.java:
a. Create a variable to store the value of the cookie.
b. Use the getCookies() method to fetch the array of Cookie objects. Then,
verify whether the request returned any cookies.
c. If so, use iteration to loop through the array of cookies. For each iteration, test to
see if the cookies name is LoginCookie. If so, retrieve the cookie value into
the variable that you created in step 2.a. and break out of the loop.
d. Test whether the cookie was found. If not, display the form that is already created
in the doGet() method. If it is found, add code to welcome the user back to the
Order Entry application by using the value of the cookie for personalization.
e. Compile LoginServlet.java.
3. Test and run the application.
a. Run LoginServlet.java. You should see the form that was created in the
previous practice. Enter a valid name and ID in the fields (refer to practice 5 for
valid name and ID entries) and click Login.
b. You should see the orders displayed for the customer as in the previous practice.
However, the name is now stored as a cookie for two minutes.
c. Run LoginServlet.java the second time to test whether the cookie is being
correctly set. You should be welcomed back to the application.
d. To ensure that your cookie is expiring correctly, wait for two minutes and then
run LoginServlet.java. You should see the form as in step a.
Practice 6-2
The purpose of this practice is to redirect a user by sending a header to the response.
Suppose that the contract between your company and customer number 104 is currently
being reviewed, and as the developer, you have been instructed to temporarily block this
customer from entering the Order Entry application. You can do this by modifying the
servlet code to check for this customer and redirect him or her to an appropriate error
message. However, this would mean modifying the servlet itself. Therefore, to incorporate
this business rule, use a servlet filter.
1. Select File > New > Web Tier > Servlets and create a new Servlet Filter in the
newlogin project. Name the filter and the class LoginFilter, and ensure the
package name is newlogin. Map this filter to every servlet in the URL pattern.
2. Use the Properties class of the java.util package to create an instance
variable named blockUser.
a. Create an instance variable of type java.util.Properties. Note that you
will need to import this package.
b. Use blockUser.setProperty to define the business rule that you are
creating: the name property with a value of Sutherland.
c. Additionally, create an instance variable to store the value of
javax.servlet.ServletContext. Note that you must import this
package.
3. Modify the init() method.
a. Set the context for this method as
filterConfig.getServletContext(); and write to the context log
that the filter has been initialized. Use filterConfig.getFilterName()
to retrieve the name of the filter.
4. Modify the doFilter() method to check for the supplied customer name.
a. Loop through the enumeration returned from the keys() method of
blockUser and look for the String value of this variable. Use the
hasMoreElements() method of java.util.Enumeration to
increment in the loop.
b. Retrieve the custName parameter from the request object, and set it to a
temporary String variable.
c. Verify whether the value of the variable created in the previous step matches the
value that is retrieved from the enumeration.
d. If the values match, send an error message by using
javax.servlet.http.HttpServletResponse to the browser,
indicating that the service is unavailable. Additionally, include a message in the
error to indicate that the value specified has been temporarily rejected. Send this
error message text to the context log.
e. Finally, pass the doFilter() method down the filter chain.
5. Compile the filter and test by running LoginServlet, and by supplying a customer
number of 104 and a name of Sutherland. The filter should modify the response
so that a service_unavailable error is sent in the response.
Objectives
7-2
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 achieve this capability.
Overview
First request
Chris
Servlet
Second request
Chris
First request
Michelle
7-3
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
7-4
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).
Session Basics
7-5
Threading
Multithreaded model
Single-threaded model
Client 1
Servlet instance 1
Client 1
Servlet instance 2
Client 2
Client 2
Both clients using
unique sessions, but
sharing the same
servlet instance
7-6
URL Rewriting
URL rewriting:
Every URL that is accessed by the client is rewritten
so that it has the session ID.
Use the encodeURL() method to re-create the path
dynamically.
7-7
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
7-8
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
7-9
Session Objects
The table below describes the methods in the HttpSession class and their meanings:
getLastAccessedTime()
getId()
setAttribute(String name,
Object value)
getAttribute(String name)
isNew()
7-10
7-11
7-12
OC4J does not support the nonstandard and expensive method of encoding the session ID
into a URL.
Sessions last for 20 minutes by default. To change this, modify the web.xml file as
follows:
<session-config>
<session-timeout>5</session-timeout>
</session-config>
This changes the session timeout to five minutes. A value of 0 (zero) or less specifies that a
session never gets timed out.
7-14
7-15
Example:
public class EventObject
implements HttpSessionBindingListener {
public void valueBound(
HttpSessionBindingEvent event) {
// connect to the database using this client
sess = event.getSession()//which session?
// get values from this session object to
// identify client information
}
public void valueUnbound(
HttpSessionBindingEvent event) {
// release resources
}
}
7-16
7-17
Summary
7-18
7-19
Practice 7-1
In this practice, you create a shopping cart application to track a customers orders in the
Order Entry application. You create a link to the LoginServlet that displays the
products. Each product can then be added to a shopping cart by passing in the productID
and name of the selected product. You create a class to store the products that are selected
for each session, and display them by using a servlet. Open the practice07.jws
workspace and select orderproducts.
1. Create a servlet to display the products that are available for order.
a. Create a new servlet named ProductsServlet in the orderproducts
package. Generate a doGet() method for this servlet and use the default
mappings.
b. Import the javax.naming.*, javax.sql.*, java.sql.*, and
oracle.jdbc.* packages.
c. Create instance variables for the Connection (as conn) and DataSource
(as ds).
d. Create a new method in ProductsServlet.java to retrieve the
PRODUCT_ID, PRODUCT_NAME, and PRODUCT_DESCRIPTION from the
PRODUCTS view, ordering by the CATEGORY_ID. You must use coding similar
to that used in the init() and verifyCustomer() methods of
LoginServlet.java.
e. Loop through the result set and retrieve the values of the columns into variables.
f. Set the return value for this method by creating a table to store the variables that
are returned in step 1d in a table format. Include an href link at the end of each
row that points to showcartservlet, and allows the customer to add this
product to his or her shopping cart. You create this servlet later in the practice.
Close the result set object and return the variable name.
Hint: Include two parameters in the URL, using the variables you created in the
previous step:
<yourreturnvaluename> += "<tr><td>" + var1 + "</td><td>" +
var2 + "</td><td>" + "<a href=\"showcartservlet" +
"?param1=" + var1 + "¶m2=" + var2 + "\"/> + Add to
Shopping Cart" + "</a></td></tr><p>";
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 URLpattern 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.
Oracle10g: Build J2EE Applications 7-20
Objectives
8-2
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.
JavaServer Pages
Connects to
Request
JSP
Database
Client
Generates
Dynamic content
Response
8-3
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 programmers
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.
Servlets:
Are Java programs
with embedded
HTML
Generate dynamic
content
Do not separate
static and dynamic
content
8-4
JavaServer Pages:
Are HTML pages
with embedded Java
code or they can be
pure XML
Generate dynamic
content
Separate static and
dynamic content
Invoking JSPs
HTML
Invoke
JSP
Servlet
JSP
8-5
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.
8-6
...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Show Date
</title></head><body><h2>The current time
is:</h2><p>");
out.println(new java.util.Date());
out.println("</body></html>");
out.close();
}
...
8-7
However, if you split the HTML tags with different println statements, it is much easier
to revisit or debug the servlet.
8-8
First
time
OC4J
http://host/date.jsp
Yes
1
Create servlet
date.java
No
Compile servlet
date.class
8-9
8-10
Declarations
8-11
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
8-12
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
<% if (i<3)
out.print("i<3");
if (i==3)
out.print("i==3");
else
out.print("i>3");
%>
8-13
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
8-14
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
8-16
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"; %>
Example (continued)
<h3> Expressions </h3>
<%= i+1 %> <b> output </b> <%= i+1 %> <br>
<%= a + b %><b> output </b><%= a + b %>
<h3> Scriptlet </h3> <% if (i<3) <br>
out.print("i<3"); <br> if (i==3) <br>
out.print("i==3"); <br> else <br>
out.print("i>3"); %> <b> output </b> <% if
(i<3)out.print("i<3"); if (i==3)
out.print("i==3"); else out.print("i>3"); %> </body>
</html>
Directives
8-18
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
8-19
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>
page Directive
8-20
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.
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 clients request is not associated with a
session. The default value for a session attribute is true.
buffer: The buffer attribute can take a size in KB or the value none for the
amount of data that is to be buffered before the page is sent to the client. The default is
8 KB.
extends: The extends attribute is used to specify the class name that the
generated servlet class must extend.
info: This attribute is used to define a string that can be retrieved from the generated
servlet by using the getServletInfo() method.
iserrorPage: This attribute is used to specify whether or not the JSP is an error
page. If it is an error page, then the implicit variable exception is available. This
page can be invoked by another JSP when an unchecked run-time exception is thrown.
errorPage: This attribute defines the URL to another JSP, which is an error page
that is invoked when an unchecked run-time exception is thrown.
language: This attribute defines the scripting language that is to be used in JSP.
package lesson08;
import java.lang.*;
import java.util.*;
public class LuckyNumberBean {
private int luckyNum;
public LuckyNumberBean() {
luckyNum = (int) (1000 * Math.random());
}
public int getLuckyNum() {
return luckyNum;
}
public void setLuckyNum(int luckyNum) {
this.luckyNum = luckyNum;
}
}
8-22
8-23
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:include>
<jsp:forward>
<jsp:plugin>
<jsp:param>
<jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> tags are the
action tags that are used with JavaBeans. The code given in the slide is used to instantiate an
object of the LuckyNumberBean class, and bind it to the myBean variable. The
<jsp:useBean> tag hides the Java syntax and makes it easier to associate request
parameters with Java objects. You can also share the objects among multiple requests.
The attributes of the <jsp:useBean> tag are:
id: This attribute is used to specify a name for the object of the class.
scope: This attribute defines the scope of the object. You learn more about this
attribute in the following slide.
<jsp:include>: This tag includes a file (usually .html or .jsp) in a JSP at request
time.
<jsp:include page="{relativeURL | <%= expression %>}" />
<jsp:forward>: This tag is used to send a request to a file. A JSP file can use this tag to
forward the client request to an HTML file, a JSP file, or a servlet for processing.
For example:
<jsp:forward page="{ relativeURL | <%= expression %> } />
<jsp:plugin>: This tag downloads a Java plug-in to the client Web browser to
execute an applet or bean:
<jsp:plugin type=" bean| applet " code=" classFileName "
codebase="classFileDirectoryName" [ name=" instanceName "
][ archive="URIToArchive, ..." ][ align=" bottom |top|
middle|left| right" ][ height=" displayPixels " ]
[ width="displayPixels " ][ hspace=" leftRightPixels " ]
[ vspace=" topBottomPixels "][ jreversion="
JREVersionNumber | 1.1 " ] [ nspluginurl="URLToPlugin " ]
[ iepluginurl=" URLToPlugin "] >[ <jsp: params> [ <jsp:
param name=" parameterName " value=" parameterValue " />
]+ </ jsp: params> ][ <jsp: fallback> text message for
user </ jsp: fallback> ]</ jsp: plugin>
<jsp:param>: This tag is used with <jsp:plugin> to specify values for the applet
parameters.
Response
Request
Response
Forward
Page 1
Page 2
Page 3
page scope
page scope
page scope
request scope
request scope
session scope
8-25
page: This is the default value. The bean object is placed in the pageContext
object and the servlet code can access it by calling the getAttributes() method
on the predefined pageContext variable.
request: The bean object is placed in the ServletRequest object. Use the
request object to include the bean from any JSP that is processing the same request
(until the JSP sends a response to the client, or forwards the request to another file).
You can use the request object to access the bean.
session: The bean object is stored in the HttpSession object that is associated
with the client. It can be retrieved by using the getSession() method.
8-26
8-28
Traditional:
No root element
XML:
page directive
<%@ page %>
Declaration tag
<%!
%>
Expression tag
<%= expression %>
Scriptlet
<%
%>
8-29
/>
Declaration Tag
<jsp:declaration>
public void setCount(int i) { if(i < 10) count=i;}
</jsp:declaration>
Expression Tag
<jsp:expression> (user==null)? :user </jsp:expression>
The JSP action tags, such as <jsp:useBean>, <jsp:forward>, and so on, are XML
compatible.
Text Element
When a JSP container encounters the text element, <jsp:text>, it passes the contents to
the current JSP out object. The code <jsp:text> Hello World </jsp:text>
displays Hello World when you run the JSP document.
JSP XML View
In JSP1.2, the JSP document can be directly processed by a JSP container. The container
creates an XML version, called XML view, of the parsing result. This XML view is the
mapping of a JSP (either a traditional page or a JSP XML document) into an XML
document that describes it. The XML view can be used by validator classes to validate a
page.
8-31
8-32
8-33
Summary
8-34
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.
8-35
Practice 8-1
The purpose of this practice is to familiarize you with expressions and scriptlets that you
have learned in the lesson. You generate a simple HTML form that displays a text field and
a Submit button. Name this form Form.html. Develop a Charcounter.jsp file that
counts the occurrence of each character in a string. The HTML form should invoke the
Charcounter.jsp file when the string is entered in the text field, and the Submit button
is clicked. The JSP should obtain the string and count the occurrence of each character and
display the characters. Open the practice08.jws workspace and navigate to the
countchars project.
1. Generate the Charcounter.jsp file:
a. Right-click countchars and select New. Expand the Web Tier node under
Categories.
b. Select JavaServer Pages under Web Tier and select JSP Page from Items. Click
OK.
c. Enter Charcounter.jsp in the File Name field. Click OK. You see the JSP
file in the Web Content folder.
2. Edit the Charcounter.jsp file:
a. Select the CSS category from the Component Palette, and drag the Oracle style
sheet to the page.
b. Switch to the Source view and change the title to Character Counter.
c. Add code to declare the following variables (use the scriptlet tag):
- A string (inputString) to hold the input parameter
- A character array (inputArray) to hold the characters of the string
- An integer (len) to hold the length of input string
- An integer array (count) and a character array (c), both with sizes equal to
the length of the string
- An integer (lastpos)
- A Boolean variable (done) initialized to false
d. Add code to count the occurrences of each character in the string and display it.
Use the scriptlet tag to code the logic.
Note: You can implement the logic to count the occurrences of characters in
different ways. The solution provided for this practice is only one way of doing
it.
Practice 8-2
The purpose of this practice is to use JavaBeans in JSPs. You develop a JavaBean,
DiscountBean.java, which calculates equal discount on the total amount of purchase
and returns the new price. You also design a JSP, CallDiscountBean.jsp, which uses
the JavaBean. The total amount of purchase (original price) is passed with the URL to the
JSP. The JSP then invokes the bean method, which calculates the price after discount by
passing the price, and displays the price after discount. Navigate to the discountbean
project in practice08.jws.
1. Open DiscountBean.java in the code editor:
a. Add code to declare three instance variables: discount, price, and
priceAfterDiscount of double type. Initialize discount to 10.5.
b. Implement the set() method for price. Optionally, you can also implement
the get() method.
c. Implement the get() method for priceAfterDiscount. Write code to
calculate the price depending on the value of discount and return the new
price.
2. Open the CallDiscountBean.jsp file in the editor. Look for comments and
insert the tags as instructed, using either the design or source view:
a. Insert an expression to get the price from the URL.
b. Declare a string called price with the declaration tag and write a scriptlet to get
the value of parameter price from the URL and assign it to the string price.
c. Insert a useBean tag to instantiate the DiscountBean class.
d. Insert a JSP expression to display the price.
e. Insert the setProperty tag to set the value of price.
f. Insert the getProperty tag to get the price after discount.
3. Test and run the application:
a. Run CallDiscountBean.jsp: Right-click CallDiscountBean.jsp in
the System Navigator and select Run.
b. You see java.lang.NullPointerException because you have not
passed any parameter. Note the target URL for this JSP and append the following
to the URL in the browser to invoke the JSP:
?price=1000
4. Sample Input/Output:
a. Input: <target-url>?price=1000.
For example: http://localhost:8988/practice08discountbean-context-root/
CallDiscountBean.jsp?price=1000
b. Output:
USING A JAVABEAN TO CALCULATE PRICE AFTER DISCOUNT FOR
A PURCHASE OF $1000
price before discount: 1000$
price after discount: 895.0$
Practice 8-3
The purpose of this practice is to create a JSP that interacts with a database by using JDBC.
You design a JSP to display PRODUCT_NAME and LIST_PRICE from the
PRODUCT_INFORMATION table. The information about the products is displayed in the
form of a table. The Java class ProductInfo is responsible for retrieving the data from
the database and returning the productnames and listprice in the form of vectors.
This class contains get() methods to retrieve the vector. The product.jsp file invokes
the get() method to obtain the details and display them in the form of a table. Navigate to
the product project in practice08.jws.
Note: Use the oe database connection that you created in Practice 5-1.
1. Set up the project to use this connection (optional):
a. Right-click the web.xml file in product.jpr and select Properties.
b. Select Resource Environment References and click Add to add this connection to
the project as a data source.
c. Name the environment reference jdbc/oeDS and specify the type as
javax.sql.DataSource.
d. You are now able to look up this data source reference by using jdbc/oeDS.
2. To add the Oracle JDBC library to the project, double-click the product project and
navigate to the Libraries tab under the Development node. Add the Oracle JDBC
library to the Selected Libraries for the project.
3. Open ProductInfo.java in the code editor:
a. Import the java.sql, javax.sql, javax.naming, and java.util
packages.
b. Declare the following private variables:
Vector productnames and listprice
ResultSet rs and Statement st
c. Implement an establishConnection() method with no parameters, and
void as return type. This method should establish the JDBC connection to the oe
schema with the data source oeDS that you created in practice 5.
Start a try block. Create a Context object.
Look for the data source jdbc/oeDS and create an instance of data source, ds.
Create a connection object by invoking the getConnection()method on the
ds data source object. Create the statement object with this connection. Close the
try block. The operations can throw SQLException or
NamingException. Provide catch blocks for SQLException and
NamingException.
Objectives
9-2
Objectives
This lesson discusses the use of custom tags in JSPs.
Custom Tags
9-3
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.
9-4
9-5
<shortname>
<uri>
<info>
<tagclass>
9-6
<html>
<head>
<%@ taglib uri="webapp/taglib.tld"
prefix="mytags" %>
</head>
<body>
<h2>The following output is from the
HelloWorldTag:</h2>
<p>
<mytags:hellotag/>
</p>
</body>
</html>
9-7
9-8
9-9
9-10
9-11
9-12
9-13
9-14
9-15
Generic
<c:out>
<c:set>
<c:remove>
<c:catch>
<c:if>
<c:choose>
<c:when>
<c:otherwi
se>
<c:forEach
>
<c:forToke
ns>
<c:import>
<c:redirec
t>
<c:url>
<c:param>
Conditional
Iteration
URLrelated
9-18
Expression Language
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>
9-20
9-21
9-24
<sql:query>
<sql:update>
<sql:param> and
<sql:dateParam>
<sql:transaction>
9-25
<sql:query datasource="jdbc/oeCoreDS"
var="customers" maxRows="10">
SELECT * FROM customers
</sql:query>
<table>
<c:forEach var="row"
items="${customers.rowsByIndex}">
<tr><c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
9-26
<sql:update var="rows">
UPDATE customers SET account_mgr_id=147
WHERE account_mgr_id=149
</sql:update>
<c:out value="${rows}"/> Rows Updated.
9-27
sql: The command that you want to execute (This may also be included in the body
of the tag.)
var: A variable to store the number of rows that are affected by the update
Formatting Tags
9-28
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
9-29
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.
Internationalizing Strings
9-30
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 requests character encoding.
9-31
Purpose
value
Type
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
Timezone
Var
The name of the variable where the formatted date will be stored
page
9-33
9-34
JSTL in JDeveloper
9-35
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.
Summary
9-36
9-37
Practice 9-1
The purpose of this practice is to use the Core JSTL tags in a JSP. Open the
practice09.jws workspace in JDeveloper.
1. Create a form that asks a user to log in.
a. Select the JSTL project and create a new JSP. Name the JSP Login.jsp.
b. Select the HTML category from the Component Palette and create a form
containing a Submit button that submits to LoginSubmit.jsp.
c. Within the form, create two text input fields named username and password.
Hint: Use the Property Inspector to change the name attributes of the text fields.
d. Create labels for the username and password fields and, optionally, add a style
sheet to the page.
2. Use the Core JSTL tags to create a JSP that welcomes the user.
a. Create a new JSP named LoginSubmit.jsp in the JSTL project.
b. Select the JSTL Core category from the Component Palette. Drag the set tag
to the page and set the value property in the Property Inspector to the
username request parameter. Name the variable un.
c. Welcome the user by name using the <c:out> tag to return the value of the un
variable. If the name is null, welcome the default user as a guest.
d. Run Login.jsp to test.
3. Next, redirect the user to a URL depending on the username that the user has entered.
a. Create a c:choose block in LoginSubmit.jsp.
b. If the name supplied is Larry, redirect the user to http://www.oracle.com.
c. If the name supplied is Scott, redirect the user to http://java.sun.com.
d. Otherwise, advise the user that the username provided is incorrect. Create a URL
variable for Login.jsp and supply an href link to the user labeled Try
Again.
Hint: Create the tags by using the tag dialog that appears when you drag a tag to
the JSP from the Component Palette, then modify the generated code in the
source code editor.
e. Run Login.jsp to test.
Practice 9-2
The purpose of this practice is to use the SQL and Formatting JSTL tags in a JSP. You will
query the Products table and display the list price of the products according to a userselected format.
1. Create a JSP that converts currencies.
a. Create a new JSP in the JSTL project named Products.jsp. At the top of the
page, insert an HTML form and add the text Convert To:.
b. Create three option buttons with values GBP, Yen, and Dollar. The name of these
buttons should be Currency. Supply the labels of the option buttons as UK
Pounds, Yen, and US Dollars.
c. Create a Submit button and submit the form to this page.
Hint: Use the HTML tag library in the Component Palette for creating the form,
option buttons, and submit buttons. Set the value of the buttons in the Property
Inspector.
d. Beneath the form, use the JSTL SQL tags to select the PRODUCT_ID,
PRODUCT_NAME, and LIST_PRICE from the PRODUCTS table where a
LIST_PRICE exists. Select only the first 25 rows, using the defined
jdbc/oeDS data source, and name the return variable prodresult.
e. Create a 1 row by 3 column table.
f. Within the table, create a <c:forEach> tag to repeat a table row for each row
of prodresult returned. Name the returned row variable prodrow.
Hint: Create the <c:forEach> tag and then drag it between the <table>
and <tr> elements using the Structure Pane.
g. In the table, output the value of the PRODUCT_ID and PRODUCT_NAME using a
<c:out> tag.
h. Switch to the code editor and just before the third <td> element, create a JSTL
variable named Price for the returned LIST_PRICE.
2. Now create the functionality for converting the price to the specified currency.
a. Create conditional tags to test the Currency parameter for GBP or Yen and
create a <c:otherwise> tag for the Dollar.
b. Within the <c:when> tags, use the setLocale and formatNumber tags to
format the variable you created in step 1.h. Use en_GB as the Locale for Pounds,
and ja_JP as the Locale for Yen. Multiply the variable by the currency rate (for
example, .5437 and 106.034, respectively). Name the variable convertedPrice
and set the formatType attribute to currency.
c. Otherwise, the user must have selected dollars. Use a third formatNumber tag
to return the value of the Price variable to the convertedPrice variable.
d. Within the last table cell, output the value of the convertedPrice variable.
e. Run Products.jsp to test.
Communicating in J2EE
Objectives
10-2
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.
Overview of RMI
Remote Method Invocation (RMI) is a framework for
executing distributed objects in Java. RMI has the
following characteristics:
It uses RPC-like communication mechanisms.
It is designed for client applications to invoke
remote object methods, as easily as calling local
methods.
It comprises the following components:
10-3
Remote interface
Implementation class
Server application/class
Client application/class
Stub (proxy) and skeleton classes
Copyright 2004, Oracle. All rights reserved.
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 clients 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.
Oracle10g: Build J2EE Applications 10-3
10-4
J2EE server
Naming
1
3
Creation
4 Client
5
Interface
Marshaled data
Skeleton
Stub
Local call
Marshaled data
7
6
Interface
Network protocol
(Java RMI)
10-5
Server
object
10-7
10-9
Naming Service
10-10
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 beans 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).
Oracle10g: Build J2EE Applications 10-10
JNDI Terminology
JNDI client
Initial context
ormi://host/AppCtx
Namespace
Context
env
jdbc
Atomic
names
Sub-context
OracleDS oeCoreDS
ejb
Employee
Cart
Binding
Objects
java:comp/env/jdbc/OracleDS
10-11
Compound name
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
10-12
2. Form the URL for the bean home interface and call
the lookup() method to get the reference to the
local home interface object. Example:
DepartmentLocalHome home =
(DepartmentLocalHome) ic.lookup(
"java:comp/env/ejb/Dept");
10-13
10-14
INITIAL_CONTEXT_FACTORY
PROVIDER_URL
SECURITY_PRINCIPAL
SECURITY_CREDENTIAL
dedicated.rmicontext
Copyright 2004, Oracle. All rights reserved.
10-15
10-16
lookup() Method
10-17
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, applicationclient.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.
Oracle10g: Build J2EE Applications 10-17
Obtaining a Reference to a
Remote Resource
Use initial context with appropriate JNDI properties:
1. Set JNDI properties for application:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY
, ...);
2. Obtain the InitialContext:
Context ic = new InitialContext(env);
3. Obtain a reference to a resource by using
lookup():
Object obj = ic.lookup("Dept");
4. Cast the reference to the returned Object type:
DepartmentHome dh = (DepartmentHome)
PortableRemoteObject.narrow(obj,
DepartmentHome.class);
10-19
After the initial context is obtained by using the appropriate JNDI properties, you can invoke
the lookup() method to return a reference to an Object data type, as seen for local
resources. You then cast the remote reference to the appropriate type such as a remote home
interface or data source by using the PortableRemoteObject.narrow() method,
which is required for obtaining a remote reference from a client accessing over the RMIIIOP protocol.
If appropriate, the Object reference returned can be cast to a data source type by using the
javax.sql.DataSource class.
Oracle10g: Build J2EE Applications 10-19
10-20
10-21
Location: The URL that the application client code uses to look up objects on the server.
The ORMI default port number is 23891, which can be modified in the config/rmi.xml
file. Thus, set the URL in the jndi.properties in one of the following three ways:
java.naming.provider.url=ormi://<hostname>/<application-name> or
java.naming.provider.url=ormi://<hostname>:23891/<application-name>
or when running in the Oracle Application Server 10g server, hardcoding the port is not necessary
and you can use
java.naming.provider.url=opmn:ormi://<host>:<port>:<oc4jinstance>/
<application-name>
The slide shows how to use a Hashtable variable env. The property name and value
pairs are added to the Hashtable by calling the put() method. Property names are
specified by using constants defined in the javax.naming.Context class in the first
parameter of the put() method with its corresponding value specified in the second
argument.
PROVIDER_URL shows a typical example of a URL for a JNDI resource name. The
absence of the port number implies that the default ORMI port number of 23891 is assumed.
INITIAL_CONTEXT_FACTORY, as used by most client applications, is specified as
ApplicationClientInitialContextFactory.
SECURITY_PRINCIPAL and SECURITY_CREDENTIALS indicate the username and
password of the client requesting the initial context. The Hashtable variable env is then
passed as a parameter to the InitialContext constructor.
Oracle10g: Build J2EE Applications 10-23
10-24
10-25
Environment variables are defined in the <enventry> section of the deployment descriptor (DD).
One entry for each variable; case-sensitive
Types can be the following classes: String, Integer,
Boolean, Double, Byte, Short, Long, or Float
<env-entry>
Deployment Descriptor
<env-entry-name>minBalance</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>500</env-entry-value>
</env-entry>
InitialContext ic = new InitialContext();
Client
The data types specified in the <env-entry-type> element can be one of the following
Java classes: String, Integer, Boolean, Double, Byte, Short, Long, or Float.
The client accesses the environment variables through the InitialContext, as follows:
InitialContext ic = new InitialContext();
Integer min = (Integer)ic.lookup("java:comp/env/minBalance");
To retrieve the environment variable values, prefix each environment element with the base
location of java:comp/env/, at which the container stores the environment variable.
Oracle10g: Build J2EE Applications 10-26
<env-entry>
<env-entry-name>minBalance</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>500</env-entry-value>
</env-entry>
<env-entry-mapping
OC4J DD
name="minBalance">300
</env-entry-mapping>
10-27
10-28
10-29
Specify the actual JNDI name of the bean in the <ejb-ref-name> element:
<ejb-ref>
<ejb-ref-name>Employee</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>businesstier.EmployeeHome</home>
<remote>businesstier.Employee/remote>
</ejb-ref>
Oracle10g: Build J2EE Applications 10-29
The <ejb-link> element provides the mapping of the logical name used in a JNDI
lookup request to the target bean.
Provide a logical name in the <ejb-ref-name> element, which is mapped to the actual
name with a <ejb-ref-mapping> element:
<ejb-ref>
<ejb-ref-name>ejb/MyEmployee</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>businesstier.EmployeeHome</home>
<remote>businesstier.Employee/remote>
</ejb-ref>
This reference alone is incomplete without mapping the logical name to the actual bean
name. The mapping can be achieved by using either the <ejb-link> element in the same
deployment descriptor, as shown in the example before this, or by specifying the mapping of
the logical name to the actual name in the applications OC4J-specific deployment descriptor
as follows:
<ejb-ref-mapping
name="ejb/MyEmployee"
location="Employee"/>
10-31
JNDI Name
Summary
10-33
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.
10-34
Practice 10-1
The aim of this practice is to write the code to perform JNDI lookup of an EJB and data
source object. To formulate an appropriate JNDI lookup request, you need to know only the
name of the EJB and how to call a method, which is similar to calling a method by using an
object reference in any Java application.
In JDeveloper, open the workspace practice10ske.jws in the practice10ske
directory and expand the usingjndi.jpr project. The project contains a HelloWorld
stateless session EJB and its deployment descriptor.
1. Enable the HelloWorldLocal.jsp application to invoke the greeting()
method of the HelloWorld session bean. The JSP and the session bean execute in
the same embedded OC4J container.
a. Open the HelloWorldLocal.jsp file and in the first scriptlet create an
initial context object and assign it to a Context variable called context.
b. Which package name is required in the import statement to compile this line of
code?
c. Now modify the string parameter value in the context.lookup() method to
be the name of the EJB.
Hint: Open the ejb-jar.xml file for the EJB and find the <ejb-name>
element.
d. Save your changes, compile the JSP, and correct any syntax errors.
e. Expand the usingjndi.impl package, and right-click the HelloWorld
node to run the HelloWorld EJB component in the embedded OC4J container.
f. Run HelloWorldLocal.jsp and observe the results in the generated HTML
page. The HTML page should contain the following text: Result from the
HelloWorld greeting() method is: Hello World (from Stateless Session
EJB).
2. Create a stand-alone Java class, with a main() method to invoke the
HelloWorldEJB in the embedded OC4J container.
a. Right-click the usingjndi project, select New, and then click Simple Files and
create a new Java class called HelloWorldClient, making sure that the
Generate Main Method check box is selected.
b. In the default constructor, copy the code from the scriptlet of the
HelloWorldLocal.jsp into the body of a try block, with Exception
class being caught in the catch block.
Hint: Make sure that you import the javax.naming package and any others
that may be required in your class, and call the exception object
printStackTrace() method in the catch block.
c. In the last line of the try block, enter the following code to print the return
value of the greetings() method of the EJB:
System.out.println(helloWorld.greetings());
Objectives
11-2
Objectives
This lesson introduces Enterprise JavaBeans and how to create them in Oracle JDeveloper
10g.
11-3
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).
11-4
Types of EJBs
11-5
EJB Type
Purpose
Session Beans
Entity Beans
Message-Driven Beans
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.
Session Beans
Session beans invoke methods for a single client.
There are two types of session beans:
Stateless Session Beans (SLSBs)
Conversation that spans a single method call
Single request business processes that do not
maintain client-specific state
11-7
EJB container
SFSBs
Client 1
Client 1
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 callers 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
Entity beans represent a business object in the
database. They are:
Sharable across multiple clients
Uniquely identifiable through a primary key
Persistentthe state survives an EJB server crash
There are two types of persistence in entity EJBs:
Container-managed persistence (CMP) beans:
The state of the bean is maintained by the
container.
The bean developer specifies the persistent fields.
11-9
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.
Oracle10g: Build J2EE Applications 11-9
Message-Driven Beans
EJB container
Clients
Pool of MDBs
11-10
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 Architecture
EJB server
EJB container
Home/local
home
interface
Home/
local home
object
EJB client
Remote/
local
interface
Deployment
descriptor
11-11
EJB
Class
Remote/
local
object
Database
Enterprise Services
Naming, Transaction, Security,
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 clients 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.
Oracle10g: Build J2EE Applications 11-11
EJB Server
11-12
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
home/local
home
object
Remote/
local
interface
remote/
local
object
Client
11-13
EJB
class
Container
generated
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 beanthat 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.
11-14
Life-cycle management
Bean instance pooling
Client state management
Database connection pooling
Declarative transaction management
Security
Persistence
EJB Client
An EJB client is a stand-alone application, servlet,
JSP, or another EJB that accesses the bean.
It can be a:
Local client:
Resides within the same Java virtual machine (JVM)
as the bean
Passes arguments by reference to the bean
Interacts with the EJB through methods defined in
the local interface
Remote client:
Is location independent
Passes arguments by value to the bean
Interacts with the EJB through methods defined in
the remote interface
11-16
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.
Oracle10g: Build J2EE Applications 11-16
Interfaces:
Remote interface/Local interface
Home interface/Local home interface
Classes:
Bean class
Primary key class (entity beans)
11-17
Remote interface:
Extends the javax.ejb.EJBObject interface that
extends the java.rmi.Remote interface
Describes the client view of an EJB
Declares the business methods that are accessible
to remote clients
EJB object:
Is a container-generated implementation of a
remote interface
Is a reference object that a client receives
Delegates the method calls to a bean class after
doing some infrastructure work
11-18
Home interface:
Extends the javax.ejb.EJBHome interface that
extends the java.rmi.Remote interface
Contains the life-cycle methods for creating,
removing, and locating the instances of a bean
class
Contains home methods
Are accessed by remote clients
Home object:
Is a container-generated implementation of the
home interface
Uses callback methods on a bean class to perform
its functions
11-19
Local interface:
Extends the javax.ejb.EJBLocalObject interface
Declares the business methods of the bean that are
accessible by a local client
Improves performance because the bean resides in
the same JVM, and parameters are passed by
reference
11-20
11-21
Deployment
descriptor
Developers
responsibility
Component deployers
responsibility
Jar
command/
tool
EJB
JAR
Deployment
tools/
commands
JNDI
11-22
ejb-jar.xml File
<ejb-jar>
<enterprise-beans>
<session>|<entity>|<message-driven>
<description>Say Hello</description>
<display-name>HelloWorld</display-name>
<ejb-name>HelloWorld</ejb-name>
<home>lesson11.HelloWorldHome</home>
<remote>lesson11.HelloWorld</remote>
<ejb-class>lesson11.impl.HelloWorldBean</ejb-class>
</session>|</entity>|</message-driven>
</enterprise-beans>
<assembly-descriptor>
<security-role> </security-role>
<method-permission> </method-permission>
<container-transaction> </container-transaction>
</assembly-descriptor>
</ejb-jar>
11-23
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 <messagedriven> 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.
Oracle10g: Build J2EE Applications 11-23
orion-ejb-jar.xml File
Oracle Application Server 10g uses the orion-ejbjar.xml file for deployment. This file:
11-24
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.
11-25
11-26
11-27
ejb-jar.xml: The deployment descriptor for this EJB module, based on the
parameters you gave when using the wizard
MySessionEJB: The EJB module containing all the components of the bean
- MySessionEJB.java: Contains the skeleton code for the remote interface
- MySessionEJBBean.java: Contains the skeleton code for the class,
including ejbCreate(), ejbRemove(), and so on
- MySessionEJBHome.java: Contains the skeleton code for the home
interface
11-28
11-29
Summary
11-30
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
Oracle10g: Build J2EE Applications 11-30
11-31
Practice 11-1
The purpose of this practice is to reinforce the concepts of EJBs by creating a simple session
bean in JDeveloper, testing it, and deploying it.
1. Create a new EJB.
a. Navigate to the EJB project in the practice11ske.jws workspace. Rightclick the EJB project and select New.
b. From the Business Tier category, select Enterprise JavaBeans and select Session
Bean from the items list.
c. Select EJB 2.0 to create a session bean that complies with the 2.0 specification.
d. Accept the defaults for the name, session, and transaction types, and click Next.
e. Accept the defaults for the bean class and source directory, and click Next.
f. Accept the default to include the remote interfaces for the bean.
g. Click Finish to generate the EJB.
2. Add a field to the EJB that you have created.
a. Right-click the bean class that is generated for you and select "Go to Bean
Class."
b. Click the Class tab to open the class editor.
c. Click the Fields tab and add a String field named hello to the EJB.
d. Accept all the other field defaults and click OK.
e. Click the Source tab to view the code that is generated for you.
f. Select the bean in the System Navigator and double click the remote interface in
the Structure Pane.
g. Create a declaration in the remote interface for the setHello() and
getHello() methods. These methods should throw a
java.rmi.RemoteException exception.
3. Test the EJB.
a. Right-click the session bean that you created and choose Run. This starts the
embedded OC4J server and deploys the EJB. After the message Oracle
Application Server Containers for J2EE 10g initialized appears, the bean is
running and you can access it with a client.
b. Right-click your session bean and select New Sample Java Client.
c. In the Sample EJB Java Client Details dialog box, select the option to connect to
the embedded OC4J server and click OK.
d. A new client file is created for you. View the code in the editor to see how the
client accesses the EJB that you created in step 1.
e. Uncomment the setHello() method and set the value to any String value.
f. Call getHello() and print it to the console.
Objectives
12-2
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.
Session Beans
A session bean:
Implements business processes
Is short-lived and has the lifetime of a clients
session
Does not survive server, machine, or network
crashes
Is not saved in permanent storage
Implements the javax.ejb.SessionBean
interface
12-3
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 clients session. When
there is a request for a session bean, the container instantiates the session bean and
associates one instance of this bean to the client. The EJB container uses management
methods for creating and destroying session beans.
Session beans are transient because they do not survive a server crash or a network failure.
If, after a crash, you instantiate a bean that had previously existed, 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
12-5
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.
Oracle10g: Build J2EE Applications 12-5
12-7
12-9
Does not
exist
Container invokes
class.newInstance,
setSessionContext(sessCtx),
and ejbCreate().
Container invokes
ejbRemove() .
Ready
12-11
12-12
12-14
12-15
12-17
12-18
Deployment Descriptor
12-19
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
clients 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.
Oracle10g: Build J2EE Applications 12-19
Client Application
To access methods on the bean instance, an EJB
client must perform the following operations:
Obtain access to the naming service (Java Naming
and Directory Interface [JNDI]) where the beans
home interface is published
Authenticate itself with the naming service
interface
Obtain a reference to the beans home interface
from the naming service by using the beans URL
Invoke the create() method on the home
interface
Invoke business methods
12-20
Client Application
An EJB client cannot access an EJB method directly. It must obtain a bean reference by
using the create() method of a beans home interface, and then invoke the business
methods on the bean reference that have been obtained.
To use the create() method of a beans 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.
12-21
12-23
Does not
exist
setSessionContext(sessCtx),
and ejbCreate()
Container invokes
ejbRemove()
ejbPassivate()
Passivated
instances
Ready
ejbActivate()
12-25
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface StatefulejbHome extends
EJBHome
{
Statefulejb create(int x) throws
RemoteException, CreateException;
}
12-26
12-27
Note that for all instances, the value variable is 0 and then incremented to 1, unlike in
stateless session beans.
Oracle10g: Build J2EE Applications 12-27
Summary
12-28
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.
12-29
Practice 12-1
The purpose of this practice is to create a stateless session bean that validates the entry made
for the customer card number. The bean should contain a business method that takes the
customer card number in the form of a string and validates the card. Note that this practice
does not validate the card number against the database. A card number can be alphanumeric.
A card is valid if:
The length of the number is nine characters.
It starts with AN, BN, CN, or LN
The last character is A
The rest of the characters are numbers and not letters
The workspace for this practice is practice12oneske.jws. Open the
validatecard project. This project contains the necessary skeleton files for this
practice.
1. Expand the validatecard node, select the ValidateCard EJB, and doubleclick ValidateCard.java in the Structure Pane to open it in the code editor. This
is the remote interface.
a. Import the java.rmi package.
b. Declare a method called validate(), which takes a string as parameter and
returns a string. This method should throw a RemoteException exception.
2. Add code to the bean class. Open ValidateCardBean.java in the code editor.
Implement the validate()method that is declared in the remote interface. This
method should verify that the card is valid. The conditions for the validity of the card
are given above.
3. Generate a sample Java client. Right-click the ValidateCard bean in the navigator
and select New Sample Java Client. Select Connect to OC4J Embedded in JDeveloper
if you are testing your EJB with the embedded OC4J, otherwise select Connect to
Remote Application Server. Click OK.
4. Invoke the validate()business method from the client application
ValidateCardClient.java:
Add code to the try block of the main()method to invoke the validate()
method. Invoke the method twice: once with a valid card number and once with an
invalid card number.
5. Test and run the application:
a. Right-click ValidateCard bean and select Make (optional).
b. Right-click ValidateCard bean and select Run.
c. Right-click the client application and select Run.
Note: This is only a sample input/output. The error messages may be different
depending on your implementation.
Practice 12-2
The purpose of this practice is to create a stateless session bean that interacts with the
database by using JDBC. So far you have used the oe schema for the practices. In this
practice, you create a connection to the hr schema and create the data source reference to it.
The bean should contain a business method that takes the employee_id and retrieves
first_name, last_name, email, and department_name from the EMPLOYEES
table and the DEPARTMENTS table. The business method returns an instance of
EmployeeDetails class. This instance has variables to hold the first name, last name, email, and department name of the employee.
Note: The EMPLOYEES table has many fields, some of them are first_name,
last_name, and email. However, the EMPLOYEES table does not contain the
department_name. The DEPARTMENTS table has department_name, and the
common field in both the EMPLOYEES and DEPARTMENTS table is department_id.
Therefore, you can join the two tables to obtain the department_name. For the
description of each of these tables, refer to Appendix B.
The workspace for this practice is practice12twoske.jws. Open the
employeedetails project and expand the employeedetails node. The Employee
bean contains the skeleton files that are required to implement the session bean.
1. Create the connection to use as the data source for the session bean:
a. In the Connection Navigator, right-click Database and select New Database
Connection. You see the Connection Wizard. Click Next.
b. Provide hr for Connection Name and select Oracle (JDBC) as Connection Type.
Click Next.
c. Provide the username and password as oraxx/oracle (as provided by your
instructor). Click Next.
d. Specify the Host Name, JDBC port, and SID, as indicated by your instructor.
Click Next.
e. Test the connection by clicking the Test Connection button. Click Finish.
2. Edit the EmployeeDetails.java file in the code editor:
a. Import java.io package.
b. Declare four string variables: fname, lname, email, and deptname.
c. Provide a constructor that takes parameters to initialize all four instance
variables.
d. Override the toString() method to provide a string representation of the
object.
3. Modify the remote interface:
a. Navigate to Employee.java and open it in the code editor.
b. Import the java.rmi package.
c. Declare a getDetails() method that takes an integer as argument and returns
an EmployeeDetails object. This method should throw the
RemoteException exception.