D57568 Viejito PDF
D57568 Viejito PDF
D57568 Viejito PDF
</web-app>
Servlet Mapping in JDeveloper
The web.xml file is primarily used to map a servlet to a virtual directory and name it. This
standard Java EE file is created automatically when a servlet is created in JDeveloper, and the
appropriate XML tags are included in the file. To modify the file, right-click the web.xml file
and select Properties from the context menu. In the above example, the servlet named
LoginServlet is mapped to a virtual directory of /loginservlet. Therefore, this servlet
can be accessed with the following URL:
http://localhost:<port>/<context-root>/loginservlet
The virtual directory of /loginservlet comes from the Java EE Web server configuration.
It is included automatically when running a servlet that is mapped in the web.xml file.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 25
Copyright 2009, Oracle. All rights reserved.
Invoking a Servlet
Invoking a Servlet
This slide shows an example of how a servlet can be invoked in JDeveloper. When the servlet is
run, the Java EE server installed with JDeveloper is started, the mapping is retrieved from the
web.xml file, and the resulting servlet is displayed from the default browser.
Note: The context root of this application is servlets-context-root.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 26
Copyright 2009, Oracle. All rights reserved.
Specifying Java EE Web Module Settings
Specifying Java EE Web Module Settings
The slide shows the Java EE Web module settings for a project in JDeveloper. This is accessed
by right-clicking the project and selecting Project Properties. The slide shows the default
settings for the lesson04Demo project, which can be changed as necessary.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 27
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe the servlet life cycle
Develop and run a servlet in JDeveloper
Map a servlet in a Java EE server
Collect information from a client
Respond to the client
Handle errors in a servlet
Summary
In this lesson, you have examined the role of servlets in the client tier of an application. You
have also seen how a servlet manages the request and response from a client, each request
running independent threads. You have explored the servlet life cycle and how a servlet is
initialized, executed, and destroyed. An HTTP servlet provides doPost() and doGet()
methods supporting HTML POST and GET methods. You can invoke servlet methods directly in
the URL, within any HTML page or a Java Server Page, or from another servlet. Finally, you
have seen how a servlet maps to a client to access the servlet methods.
Oracle Fusion Middleware 11g: Build Java EE Applications 4 - 28
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices cover the following topics:
Developing a simple servlet application in JDeveloper 11g
Testing the servlet in a Web browser
Modifying an HTML form to access the servlet
Modifying the servlet application to extract the user
credentials, connect to a database table, and validate the
user
Practice: Overview
The aim of the practices for this lesson is to develop a servlet application. You learn to develop a
simple servlet application by using the Oracle JDeveloper 11g integrated development
environment, and execute it from a Web browser. Later, you modify a login HTML form that
accepts a username and password, and makes a call to the servlet application. The servlet
application extracts the user credentials from the HTML form and validates it against a database
table.
Copyright 2009, Oracle. All rights reserved.
Developing a Web Application Using
JavaServer Pages
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Describe the relationship between JavaServer
Pages (JSP) and servlets
List implicit objects on JSP pages
Describe the semantics of JSP tags
Create a JSP segment
Explain the use of JSP tag files
Run and debug a JSP-based application
Objectives
The JavaServer Pages (JSP) specification is closely related to the servlet specification. It enables
you to create Web applications in a more productive manner. This lesson covers in detail JSPs
and their role in the Model-View-Controller (MVC) framework. JDeveloper provides a complete
environment for the creation, editing, and debugging of JSP pages. You learn how to use these
features in JDeveloper to simplify the development of JSP pages.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 3
Copyright 2009, Oracle. All rights reserved.
JavaServer Pages
Generates
Dynamic content
JSP
Connects to
EJB
Client
Request
Database
Response
JavaServer Pages
The idea behind servlets and JSP technology is to separate the presentation logic and business
logic and, therefore, to have thin clients. JSPs are based on Java servlet technology and are an
extension of servlets. JSPs can generate dynamic content just as servlets can. However, a JSP
has its own advantages.
The advantage of the JSP model is that Web designers need not be familiar with the Java
programming language to create JSPs. Programmers can provide JavaBeans and custom tags to
Web designers who are familiar with HTML. In this model, there are well-defined job roles for
Web page designers and application programmers.
Given that JSPs are built on servlet technology, the focus is on improving the programmers
productivity. JSP leverage the benefits of component technologies and, therefore, simplify the
task of the programmer.
The graphic in the slide shows that a client invokes a JSP with a URL. Note that, like servlets,
JSPs function by using the request-response model. Depending on the request from the client,
the JSP connects to a database or calls an Enterprise JavaBean (EJB), which in turn can connect
to a database. The JSP then creates dynamic content by using the output from the database or an
EJB, and returns the content to the client.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 4
Copyright 2009, Oracle. All rights reserved.
Comparing Servlets and JSPs
Servlets:
Are Java programs with
embedded HTML code
Generate dynamic content
Do not separate static and
dynamic content
JSPs:
Are HTML pages
with embedded Java code or
pure XML
Generate dynamic content
Separate static and dynamic
content
Comparing Servlets and JSPs
A JSP is an HTML page with embedded Java code. JSPs can also be pure Extensible Markup
Language (XML). A JSP takes an HTML page, adds a few tags, and automatically generates
dynamic content. A servlet also generates dynamic content, but it is not an HTML page. A
servlet is a Java program with embedded HTML code. Because a servlet is a Java program, the
programmer must take care of the syntax and semantics while developing a servlet. The servlet
must be compiled before it is executed.
Though you must know Java programming language and the API well before you can develop a
servlet, you need not be an expert in Java to develop a JSP. A Web page designer can develop a
JSP because JSPs mainly contain HTML/XML tags and additional JSP tags containing the Java
code.
In servlets, most of the Java code is written in the service method. However, in JSPs, the Java
code is embedded in JSP tags. This enables separation of the static and dynamic content in JSP.
All the static content is in the HTML tags, and the dynamic content (Java code) is in the JSP
tags.
Because a servlet is a Java program, the .class file must be created before it can be invoked.
A JSP is automatically compiled into a servlet when it is invoked for the first time. You need not
explicitly compile the source. However, if you use integrated development environment (IDE) to
develop JSPs, the JSPs are automatically compiled when you run them.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 5
Copyright 2009, Oracle. All rights reserved.
Invoking JSPs
HTML
JSP
Invoke
Servlet
JSP
Invoking JSPs
You can invoke a JSP in different ways, depending on the needs of your application:
Invoking a JSP with a URL: You can invoke a JSP directly with the URL
http://host:port/context-root/main.jsp, where:
- host is the name or IP address of the machine where JSP is running
- port is the port number on which the server is running
- context-root is the name with which the document is mapped to a client
- main.jsp is the name of the JSP file
Invoking a JSP from an HTML page, a servlet, or a JSP: In a practical scenario, the first
page is designed as a controller servlet, which invokes a JSP depending on user inputs.
You can also invoke a JSP from another JSP.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 6
Copyright 2009, Oracle. All rights reserved.
Date.jsp
<%@ page contentType="text/html;charset=WINDOWS-1252"%>
<html> <head>
<meta http-equiv="Content-Type" content="text/html;
charset=WINDOWS-1252">
<title> Show Date </title>
</head>
<body>
<h2> The current time is: </h2>
<p> <%= new java.util.Date() %> </p>
</body>
</html>
Date.jsp
The slide shows the JSP code for displaying the current time and date, and the result of invoking
the JSP. Note that the code mainly contains HTML tags. The Java code that is highlighted in the
slide displays the date and time dynamically. The content in the HTML tags form the static part
of this page.
JSPs are primarily component centric and not page centric. The page-centric model is easy to
learn and enables rapid development. However, users eventually realized that this is not the way
to build large, scalable Web applications. The logic that is written for scripted environments is
locked inside pages. Presentation logic is mixed with business and data logic, making
application maintenance difficult because programmers attempted to modify the look-and-feel of
an application without breaking the tightly coupled business logic. As Web application
complexity increased, the limitations of the page-centric model became obvious.
At the same time that users were looking for better ways to build Web applications, components
were being actively developed in the client and server world. Java and Windows application
developers were using JavaBeans and ActiveX, respectively.
JSPs are primarily a component-centric platform. Components can be shared across JSPs, and
both non-Java developers and Java developers can use them.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 7
Copyright 2009, Oracle. All rights reserved.
Date Servlet
...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Show Date
</title></head><body><h2>The current time
is:</h2><p>");
out.println(new java.util.Date());
out.println("</body></html>");
out.close();
}
...
Date Servlet
The previous slide talked about Date.jsp. Consider writing a servlet instead of JSP to display
the date. The code in the slide shows the doGet() method of the date servlet. Note that all the
HTML tags (highlighted in the slide) and their data are passed to the println() method as a
java.lang.String. This is a simple servlet that displays the date, but still includes many
println statements. It is too cumbersome to design a complex page, which includes both
static and dynamic content.
Note that a single println statement can replace all the println statements in the servlet:
out.println("<html><head><title>Show
Date</title></head><body><h2>The current time is:</h2><p>"+
new java.util.Date()+ "</body></html>");
However, if you split the HTML tags with different println statements, it is much easier to
revisit or debug the servlet.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 8
Copyright 2009, Oracle. All rights reserved.
Automated JSP Features
A JSP is automatically converted into a servlet the first
time it is invoked:
Java source files are generated.
Java class files are generated.
The Java Just-In-Time compiler can be used.
A JSP can contain extensible components:
Tags: Libraries such as custom-developed tags
JavaBeans (Beans are reused and their properties are
automatically introspected.)
Automated JSP Features
Unlike servlets, you need not compile JSPs. When you invoke a JSP for the first time, the JSP is
automatically converted into a servlet. The dynamic content (Java code) in the JSP is inserted in
the _jspService() method of the servlet and the static content remains untouched.
Therefore, the first time a JSP is invoked, your response time is likely to be slow. With
subsequent requests, however, you obtain the full benefits of the servlet technology.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 9
Copyright 2009, Oracle. All rights reserved.
JSP Life Cycle
http://host/date.jsp
Java EE
container
Create servlet
date.java.
Compile servlet
date.class.
1
Servlet life cycle
First
time
Yes
2
3
No
WebLogic
Server
JSP Life Cycle
When the Web server receives a request, the server deciphers the request to determine whether
the request is for a JSP. The JSP engine verifies whether the corresponding servlet class exists.
If the servlet does not exist, this is the first time the JSP has been requested. Thus, the JSP life
cycle is traversed as follows:
1. The JSP is translated into a servlet. During the translation phase, each tag in the JSP is
handled differently because some of the tags provide instructions for the container and
some are used to create dynamic content.
2. After the translation is done, the servlet source file is compiled and a servlet class file is
generated.
3. The server then executes the servlet by following the life cycle of the servlet.
If the servlet already exists, the servlet is executed as mentioned in step 3.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 10
Copyright 2009, Oracle. All rights reserved.
Basic JSP Elements
A JSP contains three main elements:
Text elements
Directives
Scripting elements:
Declarations
Expressions
Scriptlets
Basic JSP Elements
Text elements: Text elements represent the static portion of the page and are formatted through
standard HTML or XML.
Directives: These elements provide instructions to the JSP at run time. The JSP container
processes the instructions that are provided in the directives while compiling the JSP.
Scripting elements: These elements represent the dynamic portion of the page. They contain
Java code. They are used to perform computation and to generate dynamic content. They include
tags called scriptlets, expressions, and declarations. The code in these scripting elements is put
in the _jspService method, which in turn is called by the service method of the servlet when
the JSP is translated to a servlet.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 11
Copyright 2009, Oracle. All rights reserved.
Declarations
Are used to define methods or variables
Begin with the sequence <%!
End with the sequence %>
Are inserted into the body of the servlet class, not within a
method, during translation
Are used in conjunction with expressions or scriptlets
<%! private int i=3; %>
<%! private String a="Hello", b=" World"; %>
Declarations
JSP declarations <%!...%> are used to declare the methods or variables that are inserted outside
the _jspService() method, whereas the scriptlet tag <%...%> generates code inside the
_jspService() method.
Here is an example of a JSP followed by the generated servlet code. The servlet code is not the
complete class, but shows the relevant parts.
<%! private int useCount = 0;
private static int countryCode = 25;
public int getSquare(int k){
return k*k;
}
%>
<TABLE BORDER="1">
<% int n =8;
for (int j=1; j <=n;j++){ %>
<TR><TD><%=j%></TD><TD><%=getSquare(j)%></TR>
<%}%>
</TABLE>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 12
Declarations (continued)
private int useCount = 0;
private static int countryCode = 25;
public int getSquare(int k){
return k*k;
}
public void _jspService(...){
// generated page context code not shown
out.write(_text[1]);
int n =8;
for (int j=1; j <=n;j++){
out.write(_text[2]);
out.print(j);
out.write(_text[3]);
out.print(getSquare(j));
out.write(_text[4]);
}
out.write(_text[5]);
}//end _jspService( )
private static final char _text[][]=new char[6][];
static {
_text[0] ="\n<html>\n <head>\n ...".toCharArray() ;
_text[1] ="\n<TABLE BORDER=\"1\">\n".toCharArray();
_text[2] ="\n<TR><TD>".toCharArray();
// finishing code not shown
}
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 13
Copyright 2009, Oracle. All rights reserved.
Expressions
Begin with the sequence <%=
Contain Java expressions that are evaluated and inserted
into the servlets output
End with the sequence %>
Do not end with a semicolon
<%= i+1 %>
<%= a + b %>
<%= new java.util.Date() %>
1
2
Expressions
Expressions are used to insert values directly into the output. The expression is evaluated first
and the result is converted to a string. For every expression in the JSP, a print statement is
inserted in the _jspService() method. Therefore, the resultant string is then written to the
output. The expressions are evaluated at run time.
1. The variable I is declared and initialized to 3 (in the previous slide). Therefore, this
expression prints the value 4. Similarly, a is initialized to Hello and b is
initialized to World. The expression a + b prints Hello World. This is the same as:
<%= "Hello" + " World" %>
2. This expression prints the current time and date.
The slide shows three expressions. The corresponding translated code that is put in the
_jspService() method is as follows:
out.print(i+1);
out.print("Hello" + " World");
out.print(new java.util.Date());
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 14
Copyright 2009, Oracle. All rights reserved.
Scriptlets
Begin with the sequence <%
Contain a block of Java code that is executed every time a
request is made
End with the sequence %>
<% if (i<3)
out.print("i<3");
if (i==3)
out.print("i==3");
else
out.print("i>3");
%>
Scriptlets
Scriptlets enable you to write blocks of Java code inside the JSP. This code is executed every
time the JSP is invoked. The code inside the scriptlet is inserted exactly as it is written into the
_jspService() method. A scriptlet can contain any valid Java code. Any errors in the
scripting elements are thrown during translation time or compilation time.
The slide shows an example of a scriptlet. You can alternatively write the code as shown below:
<%if (i<3) %>
i<3
<%if (i==3) %>
i==3
<%else %>
i>3
In this code, whatever is not enclosed within the scriptlet is treated as HTML code and gets
converted to print statements during translation. Therefore, you need not enter the print
statements repeatedly.
In the example shown in the slide, the out variable, which has not been declared so far, is used.
The following slide discusses this variable.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 15
Copyright 2009, Oracle. All rights reserved.
Implicit Objects
There are eight implicit objects, also known as predefined
variables, in JSP:
request
response
session
out
application
config
pageContext
page
Note: These objects are created in the generated servlet.
Implicit Objects
In JSP, implicit objects are provided. You can use these predefined variables without explicitly
declaring them. Implicit objects are created by the container, and contain information related to
a particular request, page, or session.
request: This variable is the HttpServletRequest object that is associated with
the request. You can access the request parameters, such as request type, HTTP headers,
and so on with this variable.
response: This variable is the HttpServletResponse object that is associated with
the response to the client.
session: This variable is the HttpSession object that is associated with the request.
Sessions are created automatically. You can also disable the sessions if you do not want to
associate a session with each client.
out: This variable is the PrintWriter object that is used to send the output to the
client.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 16
Implicit Objects (continued)
application: Servlets and JSPs store persistent data in the ServletContext
object. The application variable is the ServletContext object.
config: This variable is used to store the ServletConfig object for the page.
pageContext: The pageContext object is used to give a single point of access to
page attributes.
page: The page object is a synonym for this. It is useful if the JSP is not scripted in
Java.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 17
Copyright 2009, Oracle. All rights reserved.
Example
Example
You have learned about declarations, expressions, and scriptlets. This slide shows the result of
putting them together. The code for the example is as follows:
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
<title> Declaration Expression and Scriptlet </title> </head>
<body bgcolor="pink">
<h3> Declarations </h3>
<b> Declare i </b> <%! 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"; %>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 18
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>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 19
Copyright 2009, Oracle. All rights reserved.
Quiz
Which of the following pieces can a JSP be broken down into?
1. Static data such as HTML
2. JSP directives
3. JSP scripting elements and variables
4. A servlet class
Answers: 1, 2, 3
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 20
Copyright 2009, Oracle. All rights reserved.
Directives
Are used to set global values such as class declarations
and method implementations
Begin with the sequence <%@
End with the sequence %>
Are of the following types:
page
include
taglib
Directives
JSP directives contain messages to the JSP container. They are used to set global values. All
directives have the scope of the JSP that contains the directives.
The page directive: The page directive is used to define the important attributes for a JSP.
You can include a page directive any number of times in a JSP. You learn about the various
attributes of the page directive later in this lesson.
The include directive: This directive is used to include files in the current JSP. The file
output occurs at the location of the directive in the JSP file. Whatever file you include is
interpreted when the JSP is translated into a servlet. Typically, you use the include directive
to include files that rarely change (such as a navigation bar). For example:
<%@ include file="/navigation.jsp" %>
You cannot include another dynamic page with the include directive.
The URL that is specified for the file is interpreted relative to the path of the JSP page.
The taglib directive: This directive is used to specify custom markup tags.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 21
Copyright 2009, Oracle. All rights reserved.
include: Example
include: Example
The slide shows the result of including an HTML page in a JSP. The include directive is used
to include the file, and the file attribute is used to hold the path of the file. The HTML file that is
included is as follows:
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;
charset=windows-1252"/>
<TITLE>untitled</TITLE>
</HEAD><BODY >
<b><font color="red" size="3" >CONTENT FROM INCLUDED FILE
</font> </b>
</BODY>
</HTML>
The JSP code that is used to include the file is as follows:
...
<body>
<b>Including the content from a file here, using the <%@
include file=" " %> tag </b>
<br><%@ include file="includefile.html" %>
</body> ...
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 22
Copyright 2009, Oracle. All rights reserved.
page Directive
You can define the following attributes by using the page
directive:
import
contentType
isThreadSafe
session
buffer
autoFlush
extends
info
errorPage
isErrorPage
language
page Directive
The page directive can specify several attributes for the JSP:
import: This attribute takes a list of packages or classes, separated by commas that must
be imported by the servlet class created for a JSP.
contentType: This attribute sets the Multipurpose Internet Mail Extensions (MIME)
type for the response of the JSP. The default is text/html.
isThreadSafe: If this attribute is set to false, the client requests are queued for
processing because the generated servlet implements SingleThreadModel. The default
value is true.
session: If this attribute value is false, a clients request is not associated with a session.
The default value for a session attribute is true.
buffer: The buffer attribute can take a size in KB or the value none for the amount of
data that is to be buffered before the page is sent to the client. The default is 8 KB.
autoFlush: If the autoFlush attribute is set to false, a run-time exception is raised to
indicate buffer overflow. The default value is true, in which case the buffer to the client is
flushed automatically when it is full.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 23
page Directive (continued)
extends: The extends attribute is used to specify the class name that the generated
servlet class must extend.
info: This attribute is used to define a string that can be retrieved from the generated
servlet by using the getServletInfo() method.
iserrorPage: This attribute is used to specify whether or not the JSP is an error page.
If it is an error page, the implicit variable exception is available. This page can be invoked
by another JSP when an unchecked run-time exception is thrown.
errorPage: This attribute defines the URL to another JSP, which is an error page that is
invoked when an unchecked run-time exception is thrown.
language: This attribute defines the scripting language that is to be used in JSP.
taglib Directive
A taglib directive defines a tag library and prefix for the custom tags used on the JSP page.
The taglib directive declares that the JSP page uses custom tags, names the tag library that
defines them, and specifies their tag prefix. You must use a taglib directive before you use
the custom tag on a JSP page. You can use more than one taglib directive on a JSP page, but
the prefix defined in each must be unique.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 24
Copyright 2009, Oracle. All rights reserved.
JSP and JavaBeans
package lesson05;
import java.lang.*;
import java.util.*;
public class LuckyNumberBean {
private int luckyNum;
public LuckyNumberBean() {
luckyNum = (int) (1000 * Math.random());
}
public int getLuckyNum() {
return luckyNum;
}
public void setLuckyNum(int luckyNum) {
this.luckyNum = luckyNum;
}
}
JSP and JavaBeans
As mentioned already, JSP is component centric. You can use reusable components, such as
JavaBeans, in a JSP. A JSP provides tags to use JavaBeans. In simple applications, a JSP
includes the presentation logic as well as the business logic. The Date JSP is an example of such
a page. When there is more code involved, it is important to separate business logic and
presentation logic. You can use JavaBeans to implement the business logic and return data to the
JSP, which, in turn, formats the data and displays it in the browser. The following are the
benefits of using JavaBeans on JSP pages:
JavaBeans are reusable components. Therefore, different applications can use these
components.
Using JavaBeans results in the separation of business logic and presentation logic.
The slide shows an example of JavaBeans. According to the JavaBean specification, a JavaBean
should:
Have a zero-argument constructor
Have no public instance variables
Have accessor methods to set or get a value for each property
The example shown in the slide has a zero-argument constructor. LuckyNumberBean has a
luckyNum property. getLuckyNum() and setLuckyNum(int) are the accessor and
mutator methods, respectively, for the luckyNum property.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 25
Copyright 2009, Oracle. All rights reserved.
Using JavaBeans with JSP
Accessing JavaBeans with the <jsp:useBean> tag:
<jsp:useBean id="myBean" scope="session"
class="lesson05.LuckyNumberBean" />
Using JavaBeans with JSP
Actions are specific tags that affect the run-time behavior of the JSP and affect the response.
Note that these tags are in the XML format. The action tags in JSP are:
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:include>
<jsp:forward>
<jsp:plugin>
<jsp:param>
The <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> tags are the
action tags that are used with JavaBeans. The code given in the slide is used to instantiate an
object of the LuckyNumberBean class, and to bind it to the myBean variable. The
<jsp:useBean> tag hides the Java syntax and makes it easier to associate request parameters
with Java objects. You can also share the objects among multiple requests.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 26
Using JavaBeans with JSP (continued)
The attributes of the <jsp:useBean> tag are:
id: This attribute is used to specify a name for the object of the class.
scope: This attribute defines the scope of the object. You learn more about this
attribute in the following slide.
<jsp:include>: This tag includes a file (usually, .html or .jsp) in a JSP at request
time.
<jsp:include page="{relativeURL | <%= expression %>}" />
<jsp:forward>: This tag is used to send a request to a file. A JSP file can use this tag to
forward the client request to an HTML file, a JSP file, or a servlet for processing.
For example:
<jsp:forward page="{ relativeURL | <%= expression %> } />
<jsp:plugin>: This tag downloads a Java plug-in to the client Web browser to execute
an applet or a bean:
<jsp:plugin type=" bean| applet "
code=" classFileName "
codebase="classFileDirectoryName"
[ name=" instanceName " ][ archive="URIToArchive, ..." ]
[ align=" bottom | top | middle | left | right" ]
[ height=" displayPixels " ]
[ width="displayPixels " ]
[ hspace=" leftRightPixels " ]
[ vspace=" topBottomPixels "]
[ jreversion=" JREVersionNumber | 1.1 " ]
[ nspluginurl="URLToPlugin " ]
[ iepluginurl=" URLToPlugin "] >
[ <jsp: params>
[ <jsp: param name=" parameterName " value="
parameterValue " /> ] +
</ jsp: params> ]
[ <jsp: fallback> text message for user
</ jsp: fallback> ]
</ jsp: plugin>
<jsp:param>: This tag is used with <jsp:plugin> to specify values for the applet
parameters.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 27
Copyright 2009, Oracle. All rights reserved.
page scope
scope Attribute of <jsp:useBean> Tag
Client
Page 1 Page 2 Page 3
Request
Forward
Response
Request
Response
page scope page scope
request scope
request scope
session scope
scope Attribute of <jsp:useBean> Tag
The scope attribute determines the life of the bean object depending on the context to which it
is bound. The scope attribute can have the following values:
page: This is the default value. The bean object is placed in the pageContext object
and the servlet code can access it by calling the getAttributes() method on the
predefined pageContext variable.
request: The bean object is placed in the ServletRequest object. Use the
request object to include the bean from any JSP that is processing the same request
(until the JSP sends a response to the client, or forwards the request to another file). You
can use the request object to access the bean.
session: The bean object is stored in the HttpSession object that is associated with
the client. It can be retrieved by using the getSession() method.
application: The bean object is stored in the shared ServletContext.
ServletContext is shared by all servlets in the same Web application. You can use the
getAttribute() method to retrieve values from ServletContext.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 28
Copyright 2009, Oracle. All rights reserved.
Accessing and Setting Bean Properties
Accessing bean property:
Setting bean property:
<jsp:getProperty name="myBean"
property="luckyNum" />
<jsp:setProperty name="myBean"
property="luckyNum" value="10" />
Accessing and Setting Bean Properties
Accessing Bean Property
The <jsp:getProperty> action is used to access bean property as shown in the slide. The
value of the name attribute should match the value of the ID that is given in the
<jsp:useBean> tag. The property attribute identifies the property of the bean that is being
accessed. You can also use the following code to retrieve the bean property:
<%= myBean.getLuckyNum() %>
You can use this when with loops, conditional statements, and so on.
Setting Bean Property
The <jsp:setProperty> action is used to set the bean property. The value of the name
attribute should be the name of the bean instance that is defined by the <jsp:useBean> tag.
The property attribute holds the name of the property that is being changed, and the value
attribute holds the new value for the property.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 29
Accessing and Setting Bean Properties (continued)
The property in a bean can be set from request parameters, expressions, and a specified
string.
Example:
<jsp:setProperty name="myBean" property="luckyNum"
value='<%= Integer.parseInt(request.getParameter("num"))
%>' />
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 30
Copyright 2009, Oracle. All rights reserved.
JSP XML Document
Contains <jsp:root> as its root element
Includes only the XML syntax and does not include the
traditional JSP tags
Can be processed directly by the JSP container
Can be used with XML development tools
JSP XML Document
Traditional JSP tags cannot be used within an XML document. JSP 1.1 defines JSP syntax that is
compatible with XML. For example, the XML syntax for a traditional declaration tag is: <%!
%>, <jsp:declaration> </jsp:declaration>.
In JSP 1.1, a JSP can contain both traditional syntax and XML syntax. However, beginning with
JSP 1.2, you cannot intermix these tags on a page.
A JSP that contains the XML syntax is called a JSP XML document or a JSP document. A JSP
document is well-formed and contains only the XML syntax. <jsp:root> is the root element
of this document. The following are the three important goals of the root element:
Establishing the document as a JSP XML document, so that the JSP container can process
it
Identifying the namespaces for the XML syntax and custom tag libraries through the
xmlns attribute
Specifying a JSP version number
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 31
Copyright 2009, Oracle. All rights reserved.
Traditional Syntax Versus XML Syntax
Traditional:
It has no root element.
page directive
<%@page %>
Declaration tag
<%! %>
Expression tag
<%= expression %>
Scriptlet
<% %>
XML:
<jsp:root> is the root
element.
<jsp:directive.page/>
<jsp:declaration>
...
</jsp:declaration>
<jsp:expression>
...
</jsp:expression>
<jsp:scriptlet>
...
</jsp:scriptlet>
Traditional Syntax Versus XML Syntax
The slide shows the XML syntax for some of the traditional tags described in this lesson. You
have already learned that <jsp:root> is the root element of a JSP document. You now see
how to use the XML syntax in a JSP document.
<jsp:root xmlns:jsp="http://.."
xmlns:temp="http://"
version="1.2" >
body elements
</jsp:root>
The page Directive and include Directive
<jsp:directive.page language=" " import=" " />
<jsp:directive.include file=" " />
Declaration Tag
<jsp:declaration>
public void setCount(int i) { if(i < 10) count=i;}
</jsp:declaration>
Expression Tag
<jsp:expression> (user==null)? " ":user </jsp:expression>
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 32
Traditional Syntax Versus XML Syntax (continued)
Scriptlet
<jsp:scriptlet>
if (request.getParameter("name").equals(" "))
{........}
</jsp:scriptlet>
The JSP action tags, such as <jsp:useBean>, <jsp:forward>, and so on, are XML
compatible.
Text Element
When a JSP container encounters the text element, <jsp:text>, it passes the contents to the
current JSP out object. The code <jsp:text> Hello World </jsp:text> displays
Hello World when you run the JSP document.
JSP XML View
In JSP1.2, the JSP document can be directly processed by a JSP container. The container creates
an XML version, called XML view, of the parsing result. This XML view is the mapping of a
JSP (either a traditional page or a JSP XML document) into an XML document that describes it.
The XML view can be used by validator classes to validate a page.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 33
Copyright 2009, Oracle. All rights reserved.
JSP Segments
Use a JSP segment for creating a partial JSP page.
Include one or more segments in a JSP using
<jsp:include>.
JSP segment footer.jspf:
JSP:
Copyright 2005,
<a href="http://www.oracle.com">
Oracle
</a>
<%@ include file="/footer.jspf"%>
JSP Segments
Using JSP segments adds a degree of consistency to an overall application. An application may
have hundreds of pages and each one should have the same branding or header information and
appearance. If the developer had to create a header for each page, there is a good chance of
creating inconsistencies across pages. Instead of coding each page, the developer can create a
single header segment and include it on each of the pages.
The JSP2.0 specification recommends that developers name these segments *.jspf and
include them in a separate directory such as /web-inf/jspf.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 34
Copyright 2009, Oracle. All rights reserved.
Quiz
A JSP XML document contains both XML syntax and the
traditional JSP tags.
1. True
2. False
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 35
Copyright 2009, Oracle. All rights reserved.
What Is a Tag Library?
JSPs define six standard actions: useBean,
getProperty, setProperty, include, forward and
plugin.
JSPs allow developers to define custom actions that can
be invoked by using custom tags.
A tag library is a collection of custom tags.
Custom tags can be used to process forms, send mails,
access database, control flow, or perform business logic.
What Is a Tag Library?
JSP 1.1 introduced the ability to create and use custom tags in JSP pages. Custom tags enable
you to abstract the complexity of business logic from the presentation of Web pages. This makes
it easy for the Web author to use and empowers Web page designers, who are often not fluent in
Java coding, to have access to powerful functions using an easy tag-based interface. You can use
custom JSP tag extension in JSP pages to generate dynamic content, and you can use several
Web development tools to create the presentation. WebLogic Server 10.3 fully supports the JSP
2.0 specification.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 36
Copyright 2009, Oracle. All rights reserved.
Tag Interfaces
Implement tags using interfaces and classes in
javax.servlet.jsp.tagext.*.
Custom tags implement interfaces Tag, BodyTag, and
SimpleTag, and are called as tag handlers.
Tag Interfaces
You write a custom JSP tag by writing a Java class called a tag handler. You write the tag
handler class by implementing any one of the three interfaces. Tag, BodyTag, or SimpleTag
defines methods that are invoked during the life cycle of the tag or by extending an abstract base
class that implements one of these interfaces. Extending an abstract base class relieves the tag
handler class from having to implement all methods in the interfaces and also provide other
convenient functionality. The TagSupport, BodyTagSupport, and
SimpleTagSupport classes implement these interfaces and are included in the API.
One or more custom JSP tags can be included in a tag library. A tag library is defined by a tag
library descriptor (TLD) file. TLD describes the syntax for each tag and binds it to the Java
classes that execute its functionality.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 37
Copyright 2009, Oracle. All rights reserved.
Tag Handlers
Are objects that a JSP invokes when it encounters a
custom tag
Provide several methods that are called at various stages
of a tags life cycle. For example:
import javax.servlet.jsp.tagext.*
...
public class SayHelloTag extends SimpleTagSupport {
private String var;
...
public void doTag() throws JspException {
//contains tag logic, iteration, body evaluations
...
}
...
public void setVar( String var ) {
...
}
Tag Handlers
Simple tag handlers differ from classic tag handlers in supporting doStartTag() and
doEndTag(). The SimpleTag interface provides a simple doTag() method, which is
called only once for any given tag invocation. All tag logic, iteration, body evaluations, and so
on are to be performed in this single method. A SimpleTag handler must have a public no-
argument constructor. Most simple tag handlers should extend the SimpleTagSupport class.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 38
Copyright 2009, Oracle. All rights reserved.
Tag Library Descriptor
A tag library descriptor describes a custom tag library.
<?xml version = '1.0' ...?>
<taglib ... >
<tlib-version>1.0</tlib-version> <!-- Tag lib version -->
<short-name>...</short-name> <!- Preferred name -->
<uri>...</uri> <!- uniquely identifies the tag library-->
<tag>
<description>...</description> <!- Describes tag library -->
<name>sayHello</name> <!- Defines tag name -->
<tag-class>tag.SayHelloTag</tag-class> <!- Specify tag handler class-->
<body-content>empty</body-content>
<attribute> <!-- Declares an attribute -->
<name>var</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Tag Library Descriptor
A tag library descriptor is an XML document that contains information about a library as a
whole and about each tag contained in the library. TLDs are used by a Web container to validate
the tags and by JSP page development tools. The tag library descriptor file names must have the
extension .tld and must be packaged in the /WEB-INF/ directory or subdirectory of the
WAR file or in the /META-INF/ directory or subdirectory of a tag library packaged in a JAR
file.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 39
Copyright 2009, Oracle. All rights reserved.
Implementing Simple Tags
Implementing Simple Tags
The slide shows the invocation of a custom tag. The JSP locates the tag library by referring the
Web.xml file.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 40
Copyright 2009, Oracle. All rights reserved.
JSP Expression Language
Enables access to application data stored in JavaBeans
component
Is simple to implement as compared to custom tags and
scriptlets
Syntax (JSP and XML)
${expression}
Examples:
${1.2 + 2.3}
${4.0 >= 3}
${customer.firstName}
JSP Expression Language
The JSP expression language (EL) greatly simplifies JSP authoring by removing the need to use
embedded Java scriptlets and expressions to access request parameters or application data stored
in JavaBeans.
The expression language has its own syntax, partially based on the JavaScript syntax. The
expression language is invoked through the ${expression} syntax. The most basic semantic
is that invocation of a named variable ${foo} yields the same result as the method call
PageContext.findAttribute(foo).
To access named properties within JavaBeans and within collections such as lists, maps, and
arrays, the expression language supports the "." and "[]" operators. For example,
employee.phones.cell is equivalent to employee.getPhones().getCell() in
Java syntax.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 41
Copyright 2009, Oracle. All rights reserved.
Expression Language Implicit Objects
...
First Name: <input type='text' name='Name'/>
Last Name: <input type='text' name='Address'/>
<input type='submit' value='Submit'/>
...
...
Name is : ${param.Name}
Address is : ${param.Address}
...
Second.jsp
First.jsp
The expression language provides the following implicit objects:
pageScope
requestScope
sessionScope
param
header
pageContext
Expression Language Implicit Objects
The expression language provides the following implicit objects:
pageScope: Allows access to page-scope variables
requestScope: Allows access to request-scope variables
sessionScope: Allows access to session-scope variables
pageContext: Allows access to all properties of the page context of a JSP page
param: A Java Map object containing request parameters typically accessed using the
request.getParameter() method. The expression ${param["foo"]} or the
equivalent ${param.foo} both return the first string value associated with the request
parameter foo.
header: As with param, you can use this object to access the first string value
associated with a request header
The example in the slide shows a part of the code from two JSP files: First.jsp and
Second.jsp. In First.jsp, you enter the name and address, click the Submit button, and
the flow goes to Second.jsp. You can retrieve the values by using the
${param.xxxx}syntax.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 42
Copyright 2009, Oracle. All rights reserved.
JDeveloper and JSPs
The JSP Wizard in JDeveloper is used to create JSPs
containing skeleton code.
Structure Pane helps to ensure that the JSP and HTML
tags are properly formatted.
Tag Insight automatically inserts end tags after starting a
scriptlet.
The JSP code is automatically created and recompiled.
JDeveloper increases productivity while debugging JSPs:
Automatically includes source Java files such as your
JavaBean source
Enables you to set breakpoints and watch expressions in
JSPs
JDeveloper and JSPs
JDeveloper gives you many tools for simplifying your JSP development.
The JSP Wizard creates a JSP that contains skeleton code.
The Structure Pane and Tag Insight features help you develop syntactically correct JSPs.
When you launch your JSP, the code is re-created when needed, and recompiled.
The integrated debugger enables you to systematically run the JSP that you have written,
while viewing the generated servlet code and any JavaBeans.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 43
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Identify the differences and similarities between JSPs and
servlets
Use declarations, expressions, scriptlets, and implicit
objects on JSP pages
Use JavaBeans with JSPs
Create a JSP segment
Explain the use of JSP tag files
Run and debug a JSP-based application
Summary
JSPs are based on Java servlet technology and are an extension of servlets. JSPs can generate
dynamic content just as servlets can. However, Web designers can create JSPs with no Java
knowledge, with JavaBeans and custom tags written by programmers. A JSP is automatically
compiled into a servlet when it is invoked for the first time.
There are eight implicit objects, or predefined variables, that are created by the JSP container:
request, response, session, out, application, config, pageContext, and page.
JSP syntax includes directives (<%@directive%>) and action tags (<jsp:action>). You can
define JSP segments as .jspf files and include them on a page with the <%@include%
file="<filename>"> directive. Beginning with JSP 2.0, you can use tag files to abstract a
segment of JSP code and make it reusable using a custom action.
JDeveloper provides tools to help you create, run, and debug JSPs.
Oracle Fusion Middleware 11g: Build Java EE Applications 5 - 44
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Building a basic JSP application
Building a JSP application that uses a Java bean to
implement the business logic
Building a JSP application using custom tags and
expression language
Copyright 2009, Oracle. All rights reserved.
Accessing Resources with JNDI
and Dependency Injection
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Describe the Java Naming and Directory Interface (JNDI)
Locate or look up resources and EJBs by using:
JNDI APIs
Dependency injection (DI)
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 3
Copyright 2009, Oracle. All rights reserved.
Java Naming and Directory Interface
The JNDI is:
A standard set of interfaces that provide:
Naming services
Directory services
A service provided by Java EE containers to locate Java
EE resources or objects such as:
Data sources
Environment references
EJBs and JMS components
JNDI API JNDI SPI
Programmatic interfaces
RMI Registry
COS Naming
LDAP
JNDI provider
implementations
JNDI client
Object
Java Naming and Directory Interface
Java EE applications use the following parts of the JNDI specifications to find other distributed
objects:
An application-level interface used by client programs to access a naming and directory
service
A service-provider interface used by the JNDI API to communicate with a provider of a
naming and directory service, in a vendor-independent manner
Client applications use JNDI properties and the API to:
Connect with a JNDI service provider by establishing an initial context
Locate an object by its registered name by calling a lookup operation from the initial
context
The server implements the JNDI Service Provider Interface (SPI) library that generalizes access
to different types of JNDI provider implementations, such as Remote Method Invocation (RMI)
Registry, Common Object Services Naming, Lightweight Directory Access Protocol (LDAP),
and others. This enables different types of directory-service and naming-service
implementations to be transparently used by the Java EE container.
The types of objects typically stored in a JNDI service provider include the bean interface for
Enterprise JavaBeans (EJB) components, Java Database Connectivity (JDBC) data sources, and
Java Message Service (JMS) resources.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 4
Copyright 2009, Oracle. All rights reserved.
JNDI Structure
WLS
Server
WLS
Driver
Naming Manager
Service
Purchased
JNDI API
Written by
Developer
Other
DNS
System
File
System
LDAP
Server
Other
DNS
Driver
File Sys
Driver
LDAP
Driver
JNDI SPI
JNDI API
Application Code
JNDI Structure
As you can see, a variety of naming and directory services exist in production today. These
include services such as:
Lightweight Directory Access Protocol (LDAP)
Domain Name Service (DNS)
Network Information Service (NIS)
Remote Method Invocation (RMI)
Using the JNDI SPI, service providers for these industry naming and directory services provide a
mapping from JNDI to their particular service. Java applications can then use the JNDI API to
access any individual service uniformly. Access to the service is provided using a Naming
Manager.
A complete list of existing service providers can be located at:
http://java.sun.com/products/jndi/serviceproviders.html
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 5
Copyright 2009, Oracle. All rights reserved.
Naming Service
A naming service provides a
method for mapping identifiers
to entities or objects:
Naming Service vocabulary:
ID3
ID2
Objects
ID1
Namespace
Binding
Term
www.oracle.com is bound
to 209.10.217.38
Association of an atomic name
and an object
www.oracle.com/products
Example
A set of unique names in a
naming system
Definition
Naming Service
WebLogic Server provides naming services to client applications. These are mainly used for
looking up EJBs, DataSources, JMS queues, and so forth.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 6
Copyright 2009, Oracle. All rights reserved.
JNDI Tree
Context B
is bound to
Initial Context.
Object 3
is bound to both
Context A and B.
A binding associates an object
with a logical name and a context.
IC
A
Object 1
is bound to
Initial Context.
Object 2
is bound to
Context A.
R Root Context
Initial Context
Object 1 Object 2 Object 3 Object 4
B
JNDI Tree
A JNDI tree is described in terms of the following components:
Context: A node in the JNDI tree. It can only contain a list of Objects and Contexts.
Object: A leaf in the JNDI tree. It is bound to a Context. It cannot contain other
Objects or Contexts.
Root Context: The topmost context in the whole tree
Initial Context: A Context chosen as a starting point for all future operations. This is
somewhat like a current directory that you choose. It does not always have to be the root
context of your directory structure. For instance, if you use your file system as a directory
structure for JNDI, the root context would be C:\. It does not, however, have to be the
initial context. The initial context is merely the starting point that can traverse through the
application. For example, in a JNDI program, to locate all the text files in the windows
temporary directory, the initial context might appropriately be C:\windows\temp
instead of C:\.
Observe the Object3 object in this diagram. It is binding to two different contexts: A and B.
Does the object bound in two different contexts exist once or twice in the naming service? Or,
worded differently, was the object accessed by value or by reference?
The truth is JNDI stores the objects by value, copying them into the tree. That means there are
multiple copies in the tree. To create a by reference binding, you need to use the LinkRef
class, which is not discussed here.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 7
JNDI Tree (continued)
Modifying an object under a context does not change the same object under a different context. In
the tree above, Object3 has really two different instances. The first instance lives under context
A, the second under context B.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 8
Copyright 2009, Oracle. All rights reserved.
Contexts and Subcontexts
Subcontexts are referenced through dot delimiters (.).
Subcontexts must be created before objects are placed
into them.
Typically, when objects are bound to the JNDI tree,
subcontexts are automatically created based on the JNDI
name.
For example, if the following context exists:
com.bea.examples
you cannot bind:
com.bea.examples.ejb.SomeObject
without first creating:
com.bea.examples.ejb
Contexts and Subcontexts
Subcontexts are referenced through simple dot delimitationfor instance, the name
com.bea.examples.
You cannot insert an object into the naming service unless its subcontext already exists. Suppose
SomeObject refers to an object in the examples context, which is a subcontext of com.bea.
In this example, you cannot bind an object named com.bea.examples.ejb.SomeObject
unless the ejb subcontext was first created. The JNDI will not automatically create the
subcontext because the name of the bound object has a subcontext listed in it.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 9
Copyright 2009, Oracle. All rights reserved.
Referencing Java EE Resources with JNDI
Provide JNDI properties:
java.naming.factory.initial
java.naming.security.principal
java.naming.security.credentials
java.naming.provider.url
Establish an initial context:
Perform the lookup operation:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, t3://localhost:7001"); ...
Context ctx = new InitialContext(env);
import javax.sql.DataSource; ...
DataSource ds =
(DataSource)ctx.lookup("jdbc/Data_Source");
Initial context
Lookup
jdbc ejb
Data_Source bean
client
Referencing Java EE Resources with JNDI
To reference a Java EE resource, such as a data source or a session EJB, the client code must:
Provide JNDI properties for establishing an initial context with a JNDI service
Establish an initial context (starting point) for a directory search (lookup) operation
Perform the lookup operation relative to the initial context
Standard JNDI Properties
JNDI properties are typically required when the client is executing remotely from the JNDI
resources it uses.
The following JNDI properties are used by the client and Java EE applications to reference JNDI
resources from a JNDI service:
java.naming.factory.initial specifies the initial context factory class used
when creating a new initial context object that establishes a connection to the JNDI
service.
java.naming.security.principal specifies a username with access to the JNDI
service. Some JNDI services do not require this property to be set.
java.naming.security.credentials specifies a password for the principal
specified in the principal property.
java.naming.provider.url specifies a URL that the application client code uses
to connect to the JNDI service provider.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 10
Copyright 2009, Oracle. All rights reserved.
Providing JNDI Properties
JNDI properties may be provided as:
A jndi.properties file in the CLASSPATH application
Entries added to a java.util.Hashtable object in the
application code
java.naming.factory.initial=weblogic.jndi.Environment.
DEFAULT_INITIAL_CONTEXT_FACTORY
java.naming.provider.url=t3://localhost:7001
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic
import javax.naming.*;
...
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001"); ...
Context ctx = new InitialContext(env);
Providing JNDI Properties
JNDI properties can be specified:
In a jndi.properties file located in the CLASSPATH application
In entries programmatically added to a java.util.Hashtable object in the
application code
The code example in the slide uses the second (programmatic) technique to set the JNDI
properties. However, it is more flexible to use the first technique to provide JNDI properties
because changes can be localized to the properties file without changing the source code.
The principal and credential values must be configured in the JNDI namespace of the target
container. Consider using the Hashtable technique to avoid placing unencrypted security
credentials in the property file. Use a Hashtable if there is a need to access the EJB with
different security credentials each time a lookup request is performed.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 11
Copyright 2009, Oracle. All rights reserved.
Referencing a Local Session EJB with JNDI
Within the same Java EE container (local reference):
Define dependency in the deployment descriptor:
In web.xml, from a servlet or JSP
In ejb-jar.xml, from another session EJB
Look up EJB using the reference name:
<ejb-local-ref>
<ejb-ref-name>ejb/sessionBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>ejb.EJBLocal</local>
</ejb-local-ref>
Context ctx = new InitialContext();
EJBLocal ref = (EJBLocal)
ctx.lookup("java:comp/env/ejb/sessionBean");
...
Referencing a Local Session EJB with JNDI
An EJB is packaged into an EJB-JAR file that is deployed as part of an Enterprise Archive
(EAR) file. The EJB component and its JNDI name are typically defined in the EJB deployment
descriptors stored in the EJB-JAR file. At deployment time, the JNDI name is bound to an EJB
interface object located in the JNDI service.
How you reference an EJB component depends on where the client code executes relative to the
EJB component. The client is one of the following:
A local client, which executes in the same Java EE container as the EJB component
A remote client, which executes in a different Java Virtual Machine (JVM) or Java EE
container from the EJB component
For a local EJB client application to reference a session EJB in the same Java EE container, it
must do the following:
1. Specify an <ejb-local-ref> element for the session EJB being referenced in the
deployment descriptor.
2. Obtain an initial context by using the default no-argument constructor of
InitialContext(). The JNDI properties are implicitly acquired from a
jndi.properties file provided by the container.
3. Execute a lookup operation with the EJB reference name in the deployment descriptor.
The client application lookup request is relative to the java:comp/env root, which may be
excluded from the JNDI name in the argument to the lookup() method.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 12
Copyright 2009, Oracle. All rights reserved.
Referencing a Remote Session EJB with JNDI
From a different JVM or Java EE container (remote reference):
Define dependency in the deployment descriptor:
In web.xml, from a servlet or JSP
In ejb-jar.xml, from another session EJB
In application-client.xml, for applications outside a
container
Look up EJB reference (provide jndi.properties):
<ejb-ref>
<ejb-ref-name>ejb/session</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>ejb.EJBRemote</remote>
</ejb-ref>
Context ctx = new InitialContext();
EJBRemote ref = (EJBRemote) PortableRemoteObject.narrow(
ctx.lookup("java:comp/env/ejb/session"),SessionBean.class);
...
Referencing a Remote Session EJB with JNDI
For a remote EJB client code (in another Java EE container or running as a stand-alone Java
application), the client application:
Defines an <ejb-ref> element with the JNDI name, the remote session EJB, and its
interface in the client deployment descriptor
Obtains an initial context by using a client-supplied set of JNDI properties in a
jndi.properties file in the CLASSPATH application
Performs the lookup operation by using the EJB reference name specified in the client
application deployment descriptor
Note: By convention, the remote Java code uses the
javax.rmi.PortableRemoteObject.narrow() method to assist casting the remote
object reference returned by the lookup operation to the appropriate Java interface class.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 13
Copyright 2009, Oracle. All rights reserved.
JNDI State Replication
The JNDI state replication feature is being supported in a
clustered WebLogic Servers environment.
WebLogic Server WebLogic Server
JNDI cluster
1 4
Bind message
sent to the
cluster
Bind message
propagated to all
the members of
the cluster
Instance 1 binds the
message
Instance 2 looksup the
bind message
2 3
JNDI State Replication
The JNDI state replication causes changes made to the context on one WebLogic Server instance
of a cluster to be replicated to the JNDI namespace of other WebLogic Servers in the cluster. By
enabling JNDI state replication, you can bind a serializable value into an application context
(using a remote client, EJB, or a servlet) on one server and read it on another server.
When a client connects to a cluster, it is actually connecting to one of the WebLogic Servers in
the cluster. Because the JNDI tree for this WebLogic Server contains the RMI stubs for all
services offered by the other WebLogic Servers in the cluster, in addition to its own services, the
cluster appears to the client as one WebLogic Server hosting all the clusterwide services. When
a new WebLogic Server joins a cluster, each WebLogic Server already in the cluster is
responsible for sharing information about its own services to the new WebLogic Server. With
the information collected from all the other servers in the cluster, the new server will create its
own copy of the clusterwide JNDI tree.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 14
Copyright 2009, Oracle. All rights reserved.
Quiz
When objects are bound to the JNDI tree, subcontexts are
automatically created based on the JNDI name.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 15
Copyright 2009, Oracle. All rights reserved.
What Are Annotations?
They are additional information (metadata) in the operating
code that instructs a development tool to process a Java
class in a specific way.
They are used to mark methods, classes, fields,
parameters, variables, and constructors.
What Are Annotations?
In Java, there are several classes, methods, and members that contain operating code. JSR-175
enables these sets of classes, methods, and members to be marked with additional information
that is not part of the operating code. For example, a Fuji apple has the attribute that it is red.
Assuming that there is a FujiApple class, you can specify its color by using an annotation of
the @Color annotation type. By doing this, you have provided metadata about the apple. This
information is used by development tools, deployment tools, or run-time libraries to process the
color attribute of the FujiApple class in a specific way. Such annotations are called metadata.
They can be used to describe the usage and meaning of entities such as methods and classes. For
example, the Java beans architecture uses different naming conventions for different methods
(such as getName and setName) to indicate what a particular method does (getName
retrieves the name; setName provides the name). Similarly, the EJB architecture also uses a
specific naming pattern to mark methods as remote method and home method.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 16
Copyright 2009, Oracle. All rights reserved.
Dependency Injection
The concept of dependency injection implies that it is:
A programming design pattern that enables you to inject
resources at run time
Based on the principle of Inversion of Control (IOC)
An alternative to the JNDI implementation
JMS resources
EJB
container/
Web
container
EJB/
Servlet
Injection
EJBs
Dependency Injection
Dependency injection (DI) is a programming design pattern that enables you to declare
component dependencies. It is based on the principle of Inversion of Control (IOC) that is used
to reduce dependencies between systems (loose coupling). DI enables one component to call
another component or resources through interfaces. The components are glued together by using
configuration, instead of code. The complexities of the service or resource instantiation,
initialization, sequencing, and lookup are handled by the specific container (EJB container for
the EJBs and Web container for the servlet).
DI enables you to declare the component dependencies at design time. The EJB container reads
the target EJB configuration, figures out what beans and resources the EJB requires, and injects
them into the target EJB at run time. For example, you can use @EJB annotation in a session
bean to inject EJBs. Similarly, the @Resources annotation can be used to inject non-EJB
resources such as a database connection.
The implementation of DI is totally opposite to that of the implementation of JNDI. In case of
JNDI, it is the responsibility of the EJB to do a lookup and obtain a reference of the resources.
As a result, the component and resource name are hard-coded in the EJB.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 17
Copyright 2009, Oracle. All rights reserved.
Dependency Injection
Dependency injection is introduced in the Java EE 5.0
specification:
Is based on declaring resources by using annotations (or
deployment descriptors)
Eliminates writing explicit JNDI API calls
Is used by classes managed by a Java EE container
Cannot be used by classes external to a Java EE
container
Is implemented by using the following key annotations:
@Resource (javax.annotation.Resource)
@EJB (javax.ejb.EJB)
Dependency Injection (continued)
In Java EE 1.4, many enterprise Java applications reference external resources and services, such
as DataSource, EJB, or Web services. As previously discussed, a client must:
Explicitly declare dependency on a resource in a deployment descriptor element
Obtain an initial context for a JNDI service
Perform a JNDI lookup operation to obtain a reference to the resource
Dependency injection:
Eliminates the requirement to write JNDI calls to reference resources, the inverse of JNDI
Is declared by using annotations or deployment descriptors. In Java EE 5, dependency
injection is provided through the declaration of a resource annotated with:
- @Resource for dependencies of resources, such as data sources, JMS resources,
and so on
- @EJB for a dependency on another EJB component
Note: The Java API for XML Web Services 2.0 defines the @WebServiceRef
annotation for injecting Web services references.
Is managed by the Java EE containerthat is, the Java EE 5.0 container handles the
complexities of service or resource instantiation and initialization by injecting an instance
of the dependent resource when required
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 18
Copyright 2009, Oracle. All rights reserved.
Types of Dependency Injection
The Java EE 5.0 specification supports the following types of
dependency injection:
Field injection, which injects a resource to a field
Setter (property) injection, which injects a resource by
invoking a setter method
@Resource (name = "jdbc/fodDS")
private javax.sql.DataSource fodDS;
private DataSource fodDS;
...
@Resource (name = "jdbc/fodDS")
private void setfodDS(javax.sql.DataSource ds) {
fodDS = ds;
}
Types of Dependency Injection
To use field injection, simply define a field and annotate it to be a resource reference. If you do
not define the resources name and type, the container derives this information from the fields
name and type. For example, you can inject a data source to a field as follows:
@Resource
private javax.sql.DataSource fodDS;
In the example, the data source within a JNDI name jdbc/fodDS must be available;
otherwise, the container throws an exception. Field injection must be completed before methods
of the managed class are invoked.
To use setter (or property) injection, define a set method and annotate it as a resource reference.
The application does not need to invoke the setter method; the Java EE container invokes the
setter method before the business methods into which the resources are being injected. If the
annotation name property or the data type of the setter injection is not defined, it is derived from
the setter methods name and parameter type.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 19
Copyright 2009, Oracle. All rights reserved.
Defining the @Resource Annotation
The @Resource annotation definition is:
The @Resource annotation parameters can be:
Derived
Explicitly specified
public @interface Resource {
public enum AuthenticationType {CONTAINER, APPLICATION}
String name() default "";
Class type() default Object.class;
AuthenticationType authenticationType()
default AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
}
Defining the @Resource Annotation
The parameters of the @Resource annotation (injecting only one resource) or @Resources
annotation (injecting two or more resources) are as follows:
name is a String type specifying the JNDI name of the resource.
type is a Class type of the resource being used.
authenticationType is an enum type value set to CONTAINER or APPLICATION
specifying the type of authentication needed to use the resource.
shareable is a boolean type indicating whether the resource is sharable. The default
value is true.
mappedName is a String type specifying the product-specific name that the resource
should be mapped to. This is a vendor-dependent name that is not portable across
containers.
description is a String type providing a brief description of the resource.
Note: Most annotation parameters (if not specified) are derived from the type of field or
property being injected. Other parameters have a default value if not specified, such as the
authenticationType, which has a default value of CONTAINER.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 20
Copyright 2009, Oracle. All rights reserved.
Using Java EE Resources with
Dependency Injection
Using Java EE resources with dependency injection is
performed with the @Resource annotation. Examples are:
Data sources:
JMS resources (a queue or topic):
Environment entries:
@Resource(name="jdbc/fodDS")
private javax.sql.DataSource myDS;
Connection conn = myDS.getConnection();
@Resource(name="jms/demoQueue")
private Queue myQueue;
@Resource int maxItemsPerCart = 20;
Using Java EE Resources with Dependency Injection
The first example shows how to reference a data source with dependency injection. The data
source with the JNDI name jdbc/fodDS must be defined.
The second example uses a resource annotation to inject a JMS destinationin this case, a
queue. To use the JMS queue as a resource, it must be defined in the JMS server configuration
file before you can define the dependency.
The third example defines environment entries, which generally specify business parameters that
may vary from one environment to another or from time to time. However, because this is a part
of the code, to change it requires modifying the code. It is better to use an <env-entry>
element in the deployment descriptor instead. Other resource examples can include:
Mail resources. For example:
- First, configure a mail resource in the application server.
- Use the Resource annotation to inject an instance of a mail session:
@Resource(name="mail/OrderEntry")
private javax.mail.Session ms;
EJB context. For example, to inject a SessionContext object, use:
@Resource javax.ejb.SessionContext ctx;
Timer service. For example, to inject TimerService to an EJB, use:
@Resource javax.ejb.TimerService ts;
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 21
Copyright 2009, Oracle. All rights reserved.
Working with Dependency Injection
Dependency injection:
Eliminates use of JNDI complexities
Results in fewer lines of code
Yields more concise code. However, annotations can:
Hard-code resources
Be overridden with XML elements in deployment descriptors
Cannot be used with helper classes, which must use JNDI
services
Working with Dependency Injection
Dependency injection makes resources and services easier to use because you eliminate the need
to manage the complexities of using JNDI. A number of lines of code or service locator patterns
written are reduced or eliminated.
Because Java EE supports dependency injection via either XML or annotation, use annotation
when it makes sense. An annotation can make your code more readable and concise but can also
cause maintenance problems, because they require that resource references be hard-coded into
the application code, as in the environment entry example seen earlier. However, annotations
can be overridden using XML elements in deployment descriptors.
A limitation of dependency injection is that it supports managed classes. Therefore, dependency
injection cannot be used from helper classes or from classes executing outside a Java EE
container. These helper classes must still use JNDI to use Java EE resources or services.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 22
Copyright 2009, Oracle. All rights reserved.
Referencing EJBs with Dependency Injection
In EJB 3.0, dependency is expressed by using:
The @EJB annotation:
The <ejb-ref> deployment descriptor element as an
alternative method
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface EJB {
String name() default "";
String beanName() default "";
String mappedName() default "";
String description() default "";
Class beanInterface() default Object.class;
}
Referencing EJBs with Dependency Injection
The parameters of the @EJB (referencing a single EJB 3.0 session bean) annotation or the
@EJBs (referencing multiple EJB 3.0 session beans) annotation are:
name: A String specifying the JNDI name of the EJB referenced
beanName: A String specifying the name of the EJB, defined by using either the
<ejb-name> element or the name parameter of the bean class
beanInterface: A Class type identifying the interface implemented by the object
mappedName: A String for a product-specific name to which the service is mapped
description: A String specifying a brief description of the EJB
Note: If a parameter is not specified, it is derived from the name of the field or property being
injected; otherwise, the default value is applied.
For example, to use an EJB named ShoppingCart from a servlet or another EJB, you can use
dependency injection to get an instance of the ShoppingCart EJB and invoke a method:
@EJB(mappedName="ShoppingCart")
private ShoppingCart myCart;
myCart.addItem("Item 1");
In this example, the name is the JNDI name of the EJB being injected. beanName is used to
remove ambiguity from a bean when more than one bean implements the same interface.
beanInterface is used when the EJB is used on a class without knowing which interface is
being used by the component.
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 23
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe the Java Naming and Directory Interface (JNDI)
Locate or look up resources and EJBs by using:
JNDI APIs
Dependency injection
Oracle Fusion Middleware 11g: Build Java EE Applications 6 - 24
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Using the @Resource annotation in a servlet application to
access a database table
Using the @EJB annotation in a servlet application to inject
an EJB
Copyright 2009, Oracle. All rights reserved.
Developing the Business Logic with
Session Beans
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Describe session beans
Create stateless and stateful session beans by using
annotations
Describe the passivation and activation of stateful session
beans
Use interceptor methods and classes
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 3
Copyright 2009, Oracle. All rights reserved.
What Is a Session Bean?
A session bean is a type of Enterprise JavaBean (EJB) that:
Implements a business process
Represents a client/server interaction
Has a short lifespan
Lives in memory rather than in persistent storage
Is used to create a Session Facade
What Is a Session Bean?
Session beans represent actions in the business process, such as process order. A session bean
implements one or more business processes. For example, it can retrieve and update inventory
data in a database.
Note: A session bean can retrieve or update the data, but it does not necessarily represent
persistent data. That is, a session bean is not directly associated with a row of a database table.
As the name suggests, session beans are often used to model a client/server session or
conversation. The Session Facade pattern uses a session bean to provide a business service
interface to clients, while hiding the business objects that implement that service and their
interactions inside the application server.
Session beans are short-lived. Their life cycles are dependent on the clients session. When there
is a request for a session bean, the container instantiates the session bean and associates one
instance of this bean to the client. The EJB container uses management methods for creating and
destroying session beans.
Session beans are transient because they do not survive a server crash or a network failure. If,
after a crash, you instantiate a bean that had previously existed, the state of the previous instance
is not restored.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 4
Copyright 2009, Oracle. All rights reserved.
Stateless Versus Stateful Session Beans
There are two types of session beans:
Stateless session bean (SLSB):
Conversation is contained in a single method call.
Business process does not maintain client state.
Stateful session bean (SFSB):
Conversation may invoke many methods.
Business processes can span multiple method requests,
which may require maintaining a client state.
EJB container
Client 1
Client 2
Pool of SLSBs
EJB container
Client 1
Client 2
SFSBs
Stateless Versus Stateful Session Beans
Stateless session beans do not maintain client state between method calls. Thus, each invocation
of a stateless business method is independent of its previous invocation (for example, calculating
taxes or shipping charges). When the client requests a stateless bean instance, it can receive an
instance from the pool of instances or a new instance created by the container.
Stateful session beans maintain a conversational state across method invocations (for example,
an online shopping cart of a customer). When the customer starts online shopping, the
customers details are retrieved from the database. The same details are available for the other
methods that are invoked when the customer adds or removes items from the cart, places the
order, and so on.
Stateful session beans are transient because the state does not survive session termination,
system crash, or network failure. When a client requests a stateful session bean instance, the
client is assigned one stateful instance, and the state of the bean is maintained for that client.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 5
Copyright 2009, Oracle. All rights reserved.
Dependency Injection in EJB
The concept of dependency injection implies that it is:
A programming design pattern that enables you to inject
resources into a session bean at run time
Based on the principle of Inversion of Control (IOC)
An alternative to the JNDI implementation
EJB
container
EJB Injection
EJBs
JMS resources
Dependency Injection in EJB
Dependency injection (DI) is a programming design pattern that enables you to declare
component dependencies. It is based on the principle of Inversion of Control (IOC) that is used
to reduce dependencies between systems (loose coupling). DI enables one component to call
another component or resources through interfaces. The components are glued together by using
configuration, instead of code. The complexities of the service or resource instantiation,
initialization, sequencing, and lookup is handled by the EJB container.
DI enables you to declare the component dependencies at design time. The EJB container reads
the target EJB configuration, figures out what beans and resources the EJB requires, and injects
them into the target EJB at run time. For example, you can use the @EJB annotation in a session
bean to inject EJBs. Similarly, the @Resources annotation can be used to inject non-EJB
resources, such as a database connection.
The implementation of DI is totally opposite to that of implementing Java Naming and Directory
Interface (JNDI). In case of JNDI, it is the responsibility of the EJB to do a lookup and obtain a
reference of the resources. As a result, the component and resource name are hard-coded in the
EJB.
Note: Dependency injection is not limited to EJBs. You can use it in the Web tier (such as in
JSPs and servlets) and in the EJB tier with any EJB or JPA entity.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 6
Copyright 2009, Oracle. All rights reserved.
Life Cycle of a Stateless Session Bean
Ready
Creation
@PostConstruct
Does not
exist
Destruction
@PreDestroy
Method
Life Cycle of a Stateless Session Bean
Creation: Creation of an SLSB is initiated by the EJB container. The container typically creates
a pool of SLSBs that wait to service the requests of any clients. A stateless session bean is
created in the following sequence (as needed):
1. newInstance()
2. Dependency injection
3. PostConstruct callback
The @PostConstruct annotated method will be called by the container after the bean has
been constructed and before any business methods of the bean are executed. It is not a
mandatory feature. Similarly, a @PreDestroy annotated method will execute before the bean
instance is removed by the container. After this method has executed, the bean can be garbage
collected. This is also not mandatory.
Method: When a client invokes a method, the container chooses an SLSB from the pool and
invokes the requested method on it. Because SLSB conversations last for only one method call
and do not retain state, the container can return the SLSB to the available pool after the method
is complete. The bean will then wait in the pool until it is selected to fulfill another request.
Destruction: While managing the pool of SLSBs, the container may choose to destroy a bean
based on its age or to manage other resources (for example, memory limitations). At this point, a
predestroy callback is invoked if one is defined, and the SLSB is then destroyed.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 7
Copyright 2009, Oracle. All rights reserved.
Elements of a Stateless Session Bean
A stateless session bean contains:
Business interfaces, which contain the business method
definition
A bean class, which implements the business method
@Remote
@Local
Interfaces Bean class
String sayHello()
String sayHello()
{
return "Hello";
}
Remote
client
@Stateless
Local
client
JVM
String sayHello()
Elements of a Stateless Session Bean
Stateless session beans comprise the following elements:
Business interfaces: A stateless session business interface is a standard Java interface that
has a list of business method definitions, accessible by the client application. Business
interfaces can also use annotations:
- The @Remote annotation can be used to denote the remote business interface. You
use this interface to execute a session bean remotely.
- The @Local annotation can be used to denote the local business interface. You can
use this interface to execute a session bean locally. It is applicable if the client
application and the EJB container (executing the session bean) are running on the
same Java Virtual Machine (JVM).
It is possible that the application architecture requires both the remote and local interfaces.
For example, in an order processing application, the Web client (local client) can run in the
same JVM as the session bean. The Web client application can be used to submit new
orders. Simultaneously, the same session bean can be executed remotely by a rich client
application (remote client, executing on an end-user desktop machine) for entering data.
The business interfaces are generated at design time by tools such as Oracle JDeveloper,
Netbeans, or Eclipse, or generated at deployment time by the EJB container.
The bean class: A stateless session bean class is any standard Java class that has a class-
level annotation of @Stateless. The bean class implements the business methods that
are defined in the business interfaces.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 8
Copyright 2009, Oracle. All rights reserved.
Defining the Stateless Session Bean
// HelloWorldBean.java
package helloworld.ejb;
import javax.ejb.Stateless;
@Stateless(name="HelloWorld",
mappedName="HelloWorldSessionEJB")
public class HelloWorldBean implements HelloWorld
{
public String sayHello()
{
return "Hello World!";
}
}
1
3
4
5
2
Defining the Stateless Session Bean
Following are the code sections (numbered in the slide) for a HelloWorld SLSB:
1. Library: Stateless session beans import the javax.ejb.Stateless annotation class.
In general, EJBs import the javax.ejb.* class that corresponds to the type of bean
being created.
2. Annotations: The @Stateless annotation here identifies this as a stateless session bean.
The name parameter specifies the bean name. It forms a part of the JNDI lookup name,
and the mappedName parameter specifies the other part of the JNDI lookup name for the
bean (which means, EJB is published to JNDI with the name
HelloWorldSessionEJB#helloworld.ejb.HelloWorld). Annotations are
extensively used by EJB 3.0 to assist in generating or documenting code or in providing
services (for example, security) during run time. Annotations are discussed throughout this
course as you encounter them.
3. Bean class name: This is the name of the stateless session bean class.
4. Interface class name(s): This code section contains the names of the interfaces that are
defined for the bean class.
5. Bean methods: This section contains the code that defines the beans methods.
Note: Because EJB 3.0 beans are Plain Old Java Objects (POJOs) instead of extensions of
the generic javax.ejb.EnterpriseBean interface, the bean methods section is not
filled with no-op methods. Only methods that actually implement behavior are defined
here, making the code much more readable.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 9
Copyright 2009, Oracle. All rights reserved.
Analyzing the Remote and Local Interfaces
// HelloWorld.java
package helloworld.ejb;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
public String sayHello();
}
1
2
3
4
// HelloWorldLocal.java
package helloworld.ejb
import javax.ejb.Local;
@Local
public interface HelloWorldLocal {
public String sayHello();
}
1
2
3
4
Analyzing the Remote and Local Interfaces
The following code sections are highlighted in the slide:
1. Library: The remote interfaces import the javax.ejb.Remote interface.
2. Annotations: The @Remote annotation identifies this as a remote interface. Alternatively,
the bean class could have included the @Remote annotation and it could have been left out
here.
3. Interface class name: This code section contains the name of the interface for the bean
class. The client looks up this name to retrieve the interface for the bean.
4. Bean method declarations: This section includes declarations for the public methods of
the bean class.
A session bean, by default, defines a couple of interfaces: local interface and remote interface.
Each interface is meant for a different type of client. By default, the local interface is for a local
client that runs in the same JVM as the EJB 3.0 containerfor instance, a JSP page making a
call to an EJB, both executing in the same JVM for a Java EE server instance. When the client
looks up a bean stub via the local interface, the container returns a Java reference of the session
bean object. The method call invocations over Java references are very fast and efficient.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 10
Analyzing the Remote and Local Interfaces (continued)
The remote interface is for remote clients. When a client looks up the session bean stub via the
remote interface, the container returns a serialized stub object that implements the remote
interface. The remote stub knows how to pass remote procedure calls (RPCs) to the server, even
in a clustered environment. The remote interface may contain the same methods as the local
interface.
In terms of structure, local interfaces are identical to remote interfaces except that they import
the javax.ejb.Local interface and use the @Local annotation. The local and remote
interfaces may differ in terms of the methods that you want to expose to local or remote clients.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 11
Copyright 2009, Oracle. All rights reserved.
Creating a Test Client for the SLSB
// HelloWorldClient.java
import helloworld.ejb;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloWorldClient {
public static void main(String [] args)
throws NamingException {
try {
final Context context = new InitialContext();
HelloWorld helloWorld =
(HelloWorld)context.lookup(
"HelloWorldSessionEJB#helloworld.ejb.HelloWorld");
System.out.println(helloWorld.sayHello());
} catch (Exception ex) { ex.printStackTrace(); }
};
}
1
2
3
Creating a Test Client for the SLSB
The following code sections are highlighted in the slide:
1. Library: Import the package with the bean interface and the javax.naming.* libraries
for handling the JNDI lookup.
2. Bean lookup: The test client looks up the bean interface via JNDI.
3. Bean method execution: The test client invokes a bean interface method to test the SLSB.
Note: JDeveloper generates most of this code to simplify testing of your EJBs.
After the session bean is deployed into the EJB 3.0 container, a stub object is created and it is
registered in the servers JNDI registry. The client code obtains a stub of the bean from the JNDI
using its default JNDI name. You can make method calls against the stub object and the call is
transparently delegated to the bean instance in the EJB 3.0 container.
Local clients should use a beans local interface. A beans local interface provides much better
performance than its remote interface because the network is not needed for communication. In
addition, some EJB container services are available only to local clients (for example, EJB
TimerService).
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 12
Copyright 2009, Oracle. All rights reserved.
Life Cycle of a Stateful Session Bean
Ready
Creation
Passive
Activation Passivation
Does not
exist
Destruction
Ready (in TX)
Commit/
roll back
TX method
Method
TX method
Timeout
Life Cycle of a Stateful Session Bean
Creation: Unlike stateless session beans, creation of a stateful session bean (SFSB) is triggered
by a client. The execution will then proceed according to the following sequence of steps where
applicable:
1. When a client first invokes a method of an SFSB, the EJB container invokes
newInstance() to create the bean.
2. The container implements dependency injection.
3. The container execute the PostConstruct callback.
4. The container execute the Init() or ejbCreate() method.
Transactions: Stateful session beans can live across multiple method invocations and, therefore,
their life cycle includes a Ready (in Transaction) state and transaction-related callbacks as
follows:
1. TX Method - afterBegin(): After a transaction is started, this callback can be
triggered.
2. Commit - beforeCompletion() & afterCompletion(true): When
completing a transaction, these two callbacks are available.
3. Rollback - afterCompletion(false): This callback is available if the transaction
fails.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 13
Life Cycle of a Stateful Session Bean (continued)
Passivation and activation: Passivation and activation processes result in two additional life
cycle callback methods:
Passivation: Pre-passivate callback
Activation: Post-activate callback
The concepts of passivation and activation are discussed in detail in the following slide.
Destruction and timeout: Whenever a client invokes a method marked with the @Remove
annotation, the container destroys the bean after the execution of the method completes. Stateful
session beans are destroyed explicitly or by the container due to timeout (an extended period of
client inactivity). A predestroy callback is available for use before the destruction of an SLSB.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 14
Copyright 2009, Oracle. All rights reserved.
Passivation and Activation Concepts
Passivation and activation are stages in a session beans life
cycle controlled by the EJB container.
Passivation:
Serializes the bean state to secondary storage
Removes the instance from memory
Activation:
Restores the serialized beans state from secondary storage
Creates a new bean instance or uses a bean from the pool
(initialized with the restored state)
Passivation and Activation Concepts
Stateful session bean instances are assigned to individual clients because their current state
depends on earlier interactions with the client. If a clients bean instance is used by another
client, that SFSB may no longer have the proper state for the first client. To improve the
scalability of the system, the container can choose to passivate an SFSB instance, storing the
beans state in secondary storage and making that bean instance available for recycled use by
another client. In this way, the container can manage a larger number of clients with fewer
active SFSB instances in memory.
Passivation enables the container to preserve the conversational state of a bean instance by
serializing the bean and its state into a secondary storage and removing it from memory.
Activation occurs when a client invokes one of the methods of a passivated bean instance. The
preserved conversational state data is activated by deserializing the bean from secondary storage
and bringing it back into memory. The container can passivate a bean instance for reasons
controlled by the environment into which the bean is deployed (for example, limited available
memory, period of bean inactivity, and so on). However, the container will always activate a
passivated bean when a client calls one of its methods. During the passivation process, the
container serializes the bean state and saves it to temporary storage. However, some state
variables may hold resources (such as a data source connection) or violate rules for successful
passivation. These variables typically cannot be serialized and must be reinstated when the bean
instance is activated again.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 15
Copyright 2009, Oracle. All rights reserved.
Creating a Stateful Session Bean
To create a stateful session bean, perform the following steps:
1. Define the @Stateful class-level annotation in any
standard Java class.
2. Implement the business methods defined in the business
interfaces.
Creating a Stateful Session Bean
With EJB 3.0, you can develop a stateful session bean in nearly the same way that you would
develop a stateless session bean. The differences are highlighted in the next few slides as you
examine the sample code for a shopping-cart stateful session bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 16
Copyright 2009, Oracle. All rights reserved.
Defining the Stateful Session Bean
// CartBean.java
package cart.ejb;
import javax.ejb.Stateful;
@Stateful(name="Cart", mappedName="CartSessionEJB")
public class CartBean implements Cart {
private ArrayList items;
@PostConstruct
public void initialize() { items = new ArrayList(); }
public void addItem(String item) { items.add(item); }
public void removeItem(String item) {
items.remove(item); }
public Collection getItems() { return items; }
@PreDestroy
public void cleanup() {System.out.println("CLEAR!");}
@Remove
public void dumpCart() {System.out.println("BYE!");}
}
1
3
4
2
5
Defining the Stateful Session Bean
The following code sections are highlighted in the slide:
1. Library: Stateful session beans import the javax.ejb.Stateful annotation class. As
stated previously, EJBs import the javax.ejb.* package that corresponds to the type of
bean being created.
2. Annotations: The @Stateful annotation here identifies this as a stateful session bean.
3. @PostConstruct callback is used in this code example. Both stateless and stateful
session beans can have a PostConstruct callback to initialize complex attributes. The
use of the @PostConstruct annotation here indicates that initialize() is the
PostConstruct callback method.
4. @PreDestroy annotation is used as a callback notification to signal that the instance is
in the process of being removed by the container. The method annotated with
@PreDestroy is typically used to release resources that it has been holding.
5. @Remove annotation here indicates that the bean should be destroyed after the execution
of the dumpCart() method.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 17
Copyright 2009, Oracle. All rights reserved.
Analyzing the Remote and Local Interfaces
// Cart.java
package cart.ejb;
import javax.ejb.Remote;
@Remote
public interface Cart {
public void addItem(String item);
public void removeItem(String item);
public Collection getItems();
}
1
3
2
// CartLocal.java
package cart.ejb
import javax.ejb.Local;
@Local
public interface CartLocal {
1
2
Analyzing the Remote Interface and Local Interfaces
The following code sections are highlighted in the slide:
1. Library: Remote interfaces import the javax.ejb.Remote library, and local
interfaces import the javax.ejb.Local library.
2. Annotations: The @Remote and @Local annotations identify these as remote and local
interfaces, respectively.
3. Methods: Only those public methods that need to be exposed to a client are included in the
interfaces.
Note: There is really no substantive difference between developing the remote and local
interfaces of stateful and stateless session beans.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 18
Copyright 2009, Oracle. All rights reserved.
Creating a Test Client for the SFSB
// CartClient.java
import
public class CartClient {
public static void main(String[] args) throws
Exception {
Context context = new InitialContext();
Cart cart = (Cart)
context.lookup("CartSessionEJB#cart.ejb.Cart");
cart.addItem("Item1");
cart.addItem("Item2");
Collection items = cart.getItems();
for (Iterator i = items.iterator(); i.hasNext();) {
String item = (String) i.next();
System.out.println(" " + item);
}
}
}
Creating a Test Client for the SFSB
In the code in the slide, note that each execution of cart.addItem() modifies the state of
the carts items attribute. The return of cart.getItems() depends on the current state of the
bean as modified by the prior calls to cart.addItem().
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 19
Copyright 2009, Oracle. All rights reserved.
Calling a Stateless Bean from a Stateful Bean by
Implementing DI
@Stateful(name="Cart"", mappedName="CartSessionEJB")
public class CartBean implements Cart {
@EJB private HelloWorld obj;
}
Calling a Stateless Bean from a Stateful Bean by Implementing DI
Dependency injection is the easiest way to access a session bean. You just have to use the @EJB
annotation to obtain a reference to an EJB that you want to inject in your managed class (classes
such as servlets, whose life cycle is managed by the container). You can then use the EJB object
as any other Java object in your managed class.
The @EJB annotation defines two optional attributes: name and beanInterface. The name
attribute specifies the JNDI name of the referenced EJB, and the businessInterface
attribute specifies the interface class (either remote or local bean interface). For example, the
@EJB annotation shown in the slide can also be written as @EJB(name="Cart",
beanInterface=Cart.class).
Note: Only managed classes (such as servlets, JSF managed beans, and EJBs) can use
dependency injection to access a session bean. Nonmanaged application components (such as
JSPs and helper classes) have to use JNDI lookup to obtain a reference to a session bean. For
example, in the preceding scenario, if you remove the dependency injection to call the
HelloWorld EJB, the JNDI lookup code to refer to the HelloWorld EJB inside the Cart
EJB should be:
...
InitialContext context = new InitialContext();
HelloWorld helloWorld =
(HelloWorld)context.lookup("java:comp/env/ejb/HelloWorld");
...
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 20
Copyright 2009, Oracle. All rights reserved.
Interceptor Methods and Classes
EJB 3.0 introduces the ability to create custom interceptor
methods and classes that are called before invoking the
methods they intercept. Interceptors:
Are available only for session beans (stateless and
stateful) and message-driven beans
Provide more granular control of a beans method
invocation flow
Can be used to implement custom transaction or security
processes instead of having those services provided by
the EJB container
Interceptor Methods and Classes
An interceptor catches invocation of a beans methods and executes its own methods prior to
executing the beans methods. The interceptors are typically used to implement common code.
For example, any enterprise application can use interceptors to implement common logging code
that is being used by all the EJBs. The interceptors can also be used to implement application
security to block the execution of a beans methods by users whose identities have not been
verified.
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 21
Copyright 2009, Oracle. All rights reserved.
Interceptor Method
import javax.ejb.Stateless;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
@Stateless
public class HelloWorldBean implements HelloWorld
{
@AroundInvoke
public Object myInterceptor(InvocationContext ctx)
throws Exception {
System.out.println("Entering method: " +
ctx.getMethod().getName());
return ctx.proceed();
}
public void sayHello()
{ System.out.println("Hello World!"); }
}
1
2
3
4
Interceptor Method
A bean class can define an internal interceptor method to be used when any of its methods are
invoked. Only one interceptor method may be defined. Here are the relevant code sections:
1. Libraries: Include the javax.ejb.AroundInvoke and
javax.ejb.InvocationContext libraries
2. @AroundInvoke annotation: Identifies the interceptor method of the bean class
3. InvocationContext: Provides the environmental context for the call to the bean
4. proceed(): Allows execution flow to continue
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 22
Copyright 2009, Oracle. All rights reserved.
Interceptor Classes
External interceptor classes can be created to abstract the
behavior of interceptors and to define multiple interceptors for a
bean.
// Bean Class
@Stateless(name = ... , mappedName = ... )
@Interceptors(CheckUserInterceptor.class)
@Interceptors(LogActivity.class)
public class HelloWorldBean implements HelloWorld
{ }
// Interceptor Class
public class CheckUserInterceptor {
@AroundInvoke
public Object checkId(InvocationContext ctx) {}
}
Attaching the
interceptor class in
the bean class
Defining the interceptor
class and specifying the
interceptor method
Interceptor Classes
By using external interceptor classes, interceptor behavior can be abstracted and shared by
multiple beans.
Although there can be only one interceptor method for a bean, you can associate multiple
interceptor classes for a bean. In that case, the interceptors execute according to the order in
which they are declared. If there is a bean interceptor method as well, it executes last (just before
the invocation of the bean method).
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 23
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe session beans
Create stateless and stateful session beans by using
annotations
Describe the passivation and activation of stateful session
beans
Use interceptor methods and classes
Oracle Fusion Middleware 11g: Build Java EE Applications 7 - 24
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Creating a stateless session bean and implementing a
business method
Creating a test client to invoke the stateless session bean
Creating a stateful session bean that calls the stateless
session bean by implementing dependency injection
Creating a test client to invoke the stateful session bean
Creating an interceptor class that contains a method to
calculate the time to execute a beans method
Practice Overview: Creating Session Beans
In this practice, you learn to work with session beans by using JDeveloper. You create both the
stateless and stateful session beans and execute them by creating a sample test Java client. You
perform the following set of tasks in this practice:
Create a stateless session bean and implement a business method.
Create a test client to invoke the stateless session bean.
Create a stateful session bean that calls the stateless session bean by implementing
dependency injection. Here you expose a set of methods to store the clients information.
Create a test client to invoke the stateful session bean.
Create an external interceptor class that defines a method, which can be used to determine
the time that a method takes to execute. You can then use the interceptor class in any of the
session beans to find out the exact time a beans method take to execute.
Copyright 2009, Oracle. All rights reserved.
Developing the Persistence Layer with
JPA Entities
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Create a JPA entity
Select a primary key field
Perform object-relational mapping (ORM) by using
annotations
Map inheritance between entities
Map relationships between entities
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 3
Copyright 2009, Oracle. All rights reserved.
What Are JPA Entities?
A Java Persistence API (JPA) entity is:
A lightweight object that manages persistent data
Defined as a Plain Old Java Object (POJO) marked with
the @Entity annotation (no interfaces required)
Not required to implement interfaces
Mapped to a database by using annotations
@Entity
@Table(name="ORDERS")
Database
@Id
@Column(name="ORDID")
POJO
ORDERS
What Are JPA Entities?
The JPA is a part of the Java EE 5/EJB 3.0 specification that simplifies Java persistence to a
database. It provides an ORM approach that enables you to declaratively define how to map Java
objects to relational database tables. The JPA works both inside a Java EE 5 application server,
and outside an EJB container in a Java Standard Edition 5 (Java SE 5) application.
A JPA entity, or simply, entity:
Manages persistence data
Has fields that are mapped to columns in a relational database table by using annotations
Does not require that any interfaces be defined
Using JPA, you can designate any POJO class as a JPA entity by marking the POJO with the
@Entity annotation. An entity is not required to implement any interfaces. In an entity, all
fields are considered persistent unless annotated with the @Transient annotation.
Note: You need to implement the java.io.Serializable interface if the entity needs to
be passed by value through a remote interface.
The following annotations are used to map a POJO to a relational data construct:
@Table maps the object to a table.
@Column maps a field to a column (required if the field and column names are different).
@Id identifies primary key fields.
Note: Annotations for mapping relationships are discussed later in this lesson.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 4
Copyright 2009, Oracle. All rights reserved.
What Are JPA Entities?
@Entity
@Table(name="Orders")
public class Orders {
@Id
@Column(name="ORDERID")
int orderId;
@Column(name="ORDER_DATE
")
Date orderDate;
}
JPA entity
Database table
ORDER_DATE
ORDERID
Orders
What Are JPA Entities? (continued)
The slide displays a simple mapping between a JPA entity and a database table.
Note: If you do not specify the @Table annotations by default, the name of the generated table
is the name of the Java class. This also applies to the class variables. By default, the column
name is the name of the class variable if you do not specify the @Column annotation.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 5
Copyright 2009, Oracle. All rights reserved.
Domain Modeling with Entities
Entities support standard object-oriented domain modeling
techniques:
Inheritance
Encapsulation
Polymorphic relationships
Entities can be created with the new operator.
Domain Modeling with Entities
Domain modeling is the process of listing the entities in an enterprise application domain, and
defining the relationship between them. It displays the relationships among all major entities
within the system and usually identifies their important methods and attributes.
Entities are a metadata-driven POJO technology that does not require the implementation of any
predefined system interfaces or extension of a predefined system class. To create a domain
model with entities, code the domain model as POJOs and use annotations or XML to give the
persistence provider the following information:
What are the domain objectsusing the @Entity and @Embedded annotations
How to uniquely identify the domain objectsusing the @Id annotation
What are the relationships between the domain objectsusing the @OneToOne,
@OneToMany, and @ManyToMany annotations
How the domain objects are mapped to the database tablesusing annotations such as
@Table, @Column, or @JoinColumn
Entities also provide support for rich domainmodeling capabilities, such as inheritance and
polymorphism. It supports several inheritance mapping strategies: single table, joined subclass,
and table per class.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 6
Copyright 2009, Oracle. All rights reserved.
Managing Persistence of Entities
The life cycle of an entity is managed by using the
EntityManager interface, which is part of the JPA.
An entity can be created by using:
The new operator (creates detached instance)
The EntityManager Query API (synchronized with the
database)
An entity is inserted, updated, or deleted from a database
through the EntityManager API.
new
Entity Entities
EntityManager
Database
find()
Query
persist()
merge()
remove()
DML
Managing Persistence of Entities
Because an entity is a memory representation of persistent data, the storage and retrieval of an
entity and its life cycle are managed by using the JPA. This API provides the
EntityManager interface whose methods are used to find, insert, update, and remove entity
instances that are associated with a row in a database table. Entities can be created with:
The new operator and a constructor of the entity. In this case, the entity remains in a
detached state (not managed by the EntityManager). An entity can become attached to
the EntityManagers context when you pass the entity to the persist(), merge(), or
refresh() method.
The EntityManager and its Query API, which are part of the JPA
The EntityManager interface provides:
The find() method to retrieve a database row and instantiate an entity copy
Access to a Query API for creating and executing queries based on either of the following:
- Java Persistence Query Language (JPQL)
- Native SQL statements
Methods to perform persistent operations, as in the following examples:
- persist() to mark a new instance for insertion into the database
- merge() to integrate (either insert or update) an instance into the database
- remove() to remove an instance from the database
Note: The data manipulation language (DML) statements executed on the data store are
performed by the EntityManager API.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 7
Copyright 2009, Oracle. All rights reserved.
Declaring an Entity
Declare a new Java class with a no-arg constructor.
Annotate it with @Entity.
Add fields corresponding to each database column:
Add setter and getter methods.
Use the @Id annotation on the primary key getter method.
@Entity // annotation
public class Customer implements java.io.Serializable {
private int customerID;
private String name;
public Customer() { ... } // no-arg constructor
@Id // annotation
public int getCustomerID() { ... }
public void setCustomerID(int id) { ... }
public String getName() { ... }
public void setName(String n) { ... }
}
Declaring an Entity
As discussed earlier, an entity is a POJO marked with the Entity annotation.
The POJO generally follows JavaBeans naming conventions. To create an entity, perform the
following steps:
1. Declare a standard Java class. The class must have a no-arg constructor, as required by the
EJB 3.0 specifications. It may have additional constructors if desired.
2. Insert the @Entity annotation before the public modifier of the class definition.
3. Add the entity fields that represent the persistent state of the bean, where each field is
associated with a column in the database table.
4. Define the public getter and setter methods for fields in the class.
5. Insert the @Id annotation before at least one getter method whose field is used as a way to
uniquely identify the instance. This becomes the primary key field.
Note: The EJB 3.0 specification requires that an entity have a primary key.
Without @Table and @Column annotations being specified, the following default entity
mappings are applied:
The class name is mapped (as is) to the database table name. It is case-sensitive.
The field names are mapped (as is) to the column names.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 8
Copyright 2009, Oracle. All rights reserved.
Mapping Entities
Mapping of an entity to a database table is performed:
By default
Explicitly using annotations or in an XML deployment
descriptor
@Entity
@Table(name="CUSTOMERS")
public class Customer implements java.io.Serializable {
@Id
@Column(name="CUSTID")
private int customerID;
private String name;
public int getCustomerID() { ... }
public void setCustomerID(int id) { ... }
public String getName() { ... }
public void setName(String n) { ... }
}
NAME
CUSTID (PK)
CUSTOMERS
Mapping Entities
Mapping an entity to a database table is performed:
By default:
- The class name is mapped as the table name.
- The field names are mapped as the column names.
Explicitly (overriding default mapping) by using:
- The @Table annotation to specify the corresponding database table name
- The @Id annotation to specify the entitys primary key, or identifier
- The @Column annotation to specify the corresponding column name
The example shows the Customer class being mapped to the CUSTOMERS table by setting the
name parameter in the @Table annotation. The customerID field is mapped to the CUSTID
column through the use of the @Column annotation that appears before the getCustomerID()
method declaration. The name parameter of the @Column annotation specifies the column name.
The @Id annotation indicates that it is a primary key field.
An entity can be mapped to more than one table sharing a relationship. The primary table is
mapped using the @Table annotation and the secondary table is mapped using the
@SecondaryTable annotation. The primary and the secondary tables must have the same
primary key.
Note: The Transient annotation can be used for a property or field of the entity bean class that
is not persistent.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 9
Copyright 2009, Oracle. All rights reserved.
Quiz
An entity is a lightweight persistence domain object that
represents:
1. A relational database
2. A table in a relational database
3. Entity beans in EJB 2.x specification
4. Persistence data in a file
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 10
Copyright 2009, Oracle. All rights reserved.
Mapping Inheritance
Entities can implement inheritance relationships.
You can use three inheritance mapping strategies to map
entity inheritance to database tables:
Single-table strategy
Joined-tables strategy
Table-per-class strategy
Use the @Inheritance annotation.
Mapping Inheritance
You can map object-oriented inheritance into relational databases by implementing inheritance
relationship between different entities. You can use the following inheritance mapping strategies
supported by JPA.
Single-table strategy: The single-table strategy specifies that there should be one and only
one table per class hierarchy. This table should have a column for each unique field for
every class in the hierarchy. The table must have an additional column (also called a
discriminator column) that identifies the objects type. The @DiscriminatorColumn
annotation maps to a specific database column whose values are used to differentiate classes
in an inheritance hierarchy by type. The single-table strategy is the optimal strategy for
performance as the persistence engine does not have to do any complex joins when loading
such an object.
Joined-tables strategy: In joined-tables strategy, each entity in the hierarchy maps to its
own dedicated table (one-to-one relationship). The specific table maps the fields declared
on the respective entity. The parent entity in the hierarchy is mapped to a base table. All the
other child entities in the hierarchy are mapped to separate tables that join the base table.
From a performance perspective, the joined-table strategy is worse than the single-table
strategy because it requires the joining of multiple tables for polymorphic queries.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 11
Mapping Inheritance (continued)
Table-per-class strategy: In table-per-class strategy, both the superclass and the subclasses
are stored in their own tables and no relationship exists between any of the tables. The
greatest disadvantage of using this mapping type is that it does not provide good support for
polymorphic queries because each subclass is mapped to its own table.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 12
Copyright 2009, Oracle. All rights reserved.
Single-Table Strategy
//Parent entity
@Entity
@Table(name="USERS")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="USER_TYPE", ... )
public class user implements java.io.Serializable { ... }
//Child entity
@Entity
@DiscriminatorValue(value="C")
public class customer extends user ...
//Child entity
@Entity
@DiscriminatorValue(value="S")
public class supplier extends user ...
USERS table
3
4
2
1
Single-Table Strategy
The slide displays the single-table inheritance mappings strategy. The USERS table contains
data common to all the users, including the customer-specific data and supplier-specific data.
The first and second records in the USERS table contain the customer information, whereas the
third record contains the supplier information. This segregation of the customer data and the
supplier data is being indicated by the USER_TYPE column (of the USERS table) and, therefore,
is the discriminator column. The "C" and "S" values in the USER_TYPE discriminator column
indicate the customer-specific record and the supplier-specific record, respectively.
The slide also displays the inheritance mapping for the user, customer, and supplier entities. The
annotations are described as follows:
1. The @Inheritance annotation specifies the strategy to be
InheritanceType.SINGLE_TABLE on the user entity.
Note: The @Table annotation specifies the name of the single table used for inheritance
mapping.
2. The @DiscriminatorColumn annotation specifies the details of the discriminator
column. The name element specifies the name of the discriminator, which is
USER_TYPE.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 13
Single-Table Strategy (continued)
3. The customer class (subclass of user) specifies the discriminator value to be "C", by
using the @DiscriminatorValue annotation. That is, when the persistence provider
saves a customer object into the USERS table, it sets the value of the USER_TYPE
column to "C".
4. The supplier class (subclass of user) specifies the discriminator value to be "S", by
using the @DiscriminatorValue annotation.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 14
Copyright 2009, Oracle. All rights reserved.
Joined-Tables Strategy
//Parent entity
@Entity
@Table(name="USERS")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="USER_TYPE", ... )
public class user ...
//Child entity
@Entity
@Table(name="CUSTOMER")
@DiscriminatorValue(value="C")
@PrimaryKeyJoinColumn(name="UID")
public class customer extends user ...
//Child entity
@Entity
@Table(name="SUPPLIER")
@DiscriminatorValue(value="S")
@PrimaryKeyJoinColumn(name="UID")
public class supplier extends user ...
USERS table
CUSTOMER table
SUPPLIER table
1
2
3
Joined-Tables Strategy
The slide displays the joined-tables inheritance mappings strategy. In this type of strategy, the
parent of the hierarchy contains only columns common to its children. The USERS table
contains columns (such as the UID column) that are common to all the user types. The child
tables in the hierarchy contain columns specific to the entity types. For example, the C_RATING
column is specific to the CUSTOMER table.
The parent/child object-oriented hierarchy chain is implemented by using one-to-one
relationships. For example, the USERS and CUSTOMERS tables are related through the UID
foreign key in the CUSTOMER table pointing to the primary key of the USERS table. The
discriminator column is still used in the parent table to differentiate the users type in the
hierarchy.
The inheritance mapping for the user, customer, and supplier entities are basically
similar to that of the single-table strategy. Here, you need to add some additional annotations to
identify the tables mapped to the child entities, and also their respective primary keys. The
annotations are described as follows:
1. The @Inheritance annotation specifies the strategy to be
InheritanceType.JOINED on the user entity.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 15
Joined-Tables Strategy (continued)
2. The @Table annotation specifies the table name, CUSTOMER, mapped to the customer
entity. The @PrimaryKeyJoinColumn annotation specifies the foreign key column,
UID, on the CUSTOMER table that implements the one-to-one relationship between the
USERS and CUSTOMER tables.
3. The @Table annotation specifies the table name, SUPPLIER, mapped to the supplier
entity. The @PrimaryKeyJoinColumn annotation specifies the foreign key column,
UID, on the SUPPLIER table that implements the one-to-one relationship between the
USERS and SUPPLIER tables.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 16
Copyright 2009, Oracle. All rights reserved.
Specifying Entity Identity
The identity of an entity can be specified by using:
The @Id annotation
The @IdClass annotation
The @EmbeddedId annotation
Specifying Entity Identity
Every entity in a domain model should be uniquely identifiable and, therefore, must have a
primary key. The identity of an entity can be specified by using the following annotations:
@Id annotation: The @Id annotation can be used to mark a field or property as identity
for an entity. The only consideration in this case is that it works only for identities with just
one field or property. If you have to use more than one property or field (also known as a
composite key) to uniquely identify an entity, you can do it by implementing either the
@IdClass or the @EmbeddedId annotation.
@IdClass annotation: The @IdClass annotation enables you to specify a composite
primary key class that is mapped to multiple fields or properties of the entity. The names of
the fields or properties in the primary key class must correspond to the primary key fields
or properties of the entity, and their types must also be the same.
@EmbeddedID annotation: The @EmbeddedID annotation is applied to a persistent
field or property of an entity class or mapped superclass to denote a composite primary
key. The composite primary key is defined in an embeddable class in the entity class. The
embeddable class must be annotated as @Embeddable.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 17
Copyright 2009, Oracle. All rights reserved.
Generating Primary Key Values
Use the @GeneratedValue annotation.
@Entity
@Table(name="CUSTOMERS")
public class Customer implements java.io.Serializable {
@Id
@SequenceGenerator(name = "CUSTOMER_SEQ_GEN",
sequenceName = "CUSTOMER_SEQ", initialValue = 1,
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "CUSTOMER_SEQ_GEN")
@Column(name = "CUSTID", nullable = false)
private Long customerId;
...
public int getCustomerID() { ... }
...
}
1
2
3
4
Generating Primary Key Values
A primary key for an entity (which is usually annotated with the @Id annotation) can be given a
value manually, or you can use the underlying persistence framework to automatically generate
the primary key values. The @GeneratedValue annotation tells the persistence framework to
autopopulate the column with the specified sequence generator.
Consider the code in the slide. Because customerID is going to be the primary key for the
Customer entity, you have to mark the field with the @GeneratedValue annotation. The
annotation delegates the burden of creating values from developers to the persistence engine.
The types of primary key valuegeneration strategies that can be specified in the
@GeneratedValue annotation are as follows:
TABLE indicates that the container assigns values by using an underlying database table.
SEQUENCE and IDENTITY specify the use of a database sequence or identity column,
respectively.
AUTO indicates that the JPA persistence provider should pick an appropriate strategy for
the particular database.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 18
Generating Primary Key Values (continued)
The code in the slide depicts the following:
1. The @ID annotation marks the customerId property as the primary key for the
Customer entity.
2. The @SequenceGenerator annotation creates a sequence generator named
CUSTOMER_SEQ_GEN that references a CUSTOMER_SEQ database sequence object. The
initial value of the sequence is 1, and is being incremented by 1 each time that a value is
generated.
3. The @GeneratedValue annotation specifies a primary key value generator based on a
primary key identity column.
4. The customerId property of the Customer entity is mapped to the CUSTID column
of the CUSTOMERS table, being specified as the primary key.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 19
Copyright 2009, Oracle. All rights reserved.
Mapping Relationships Between Entities
Annotations for entity relationships:
@OneToOne
@ManyToOne
@OneToMany
@ManyToMany
Customer Address
Order Customer
Customer
Order
Customer
Supplier
Mapping Relationships Between Entities
The following annotations are used to specify relationships between entities:
The @OneToOne annotation defines a single-valued association to another entity.
Example: A Customer object may be associated with one and only one Address
object.
The @ManyToOne annotation defines a single-valued association to another entity that
has many-to-one multiplicity. Example: Many Order can be placed by one Customer.
A @OneToMany annotation defines a many-valued association with one-to-many
multiplicity. Example: One Customer can place many Order.
A @ManyToMany annotation defines a many-valued association with many-to-many
multiplicity. A many-to-many association has two sides: an owning side and a nonowning
(or inverse) side. Example: Many Customer can buy products from many Supplier.
Relationships can be unidirectional or bidirectional. Bidirectional relationships, which have an
owning side and an inverse side, are persisted based on references held by the owning side of the
relationship. Unidirectional relationships have only an owning side.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 20
Mapping Relationships Between Entities (continued)
The developer must maintain consistent in-memory entity references on both sides of the
relationship.
Rules that apply to bidirectional relationship:
The inverse side refers to its owning side by using the mappedBy element of the
OneToOne, OneToMany, or ManyToMany annotation. The mappedBy element
designates the relationships owning field.
The mappedBy element cannot be specified on the ManyToOne annotation and must be
on the inverse side of a OneToMany or OneToOne relationship.
In OneToOne relationships, the owning side contains the foreign key.
In ManyToMany relationships, either side can be the owning side.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 21
Copyright 2009, Oracle. All rights reserved.
STREET
ADDRESS_ID (FK)
Implementing One-to-One Relationships
You can map one-to-one relationships by using the
@OneToOne annotation.
Depending on the foreign key location, the relationship can
be implemented by using:
The @JoinColumn annotation
The @PrimaryKeyJoinColumn annotation
CUST_NAME
CUSTID (PK)
CUSTOMER
HOUSE_NO
ADDRESS_ID (PK)
ADDRESS
Address Customer
Mapped to Mapped to
Implementing One-to-One Relationships
The one-to-one relationships are mapped by using the primary key and foreign key association.
Depending on where the foreign key resides (either in the parent table or child table), the
relationship can be implemented by using the @JoinColumn annotation or the
@PrimaryKeyJoinColumn annotation.
@JoinColumn annotation: You can use the @JoinColumn annotation to implement a
one-to-one relationship between two tables if the underlying table for the referencing entity
is the one containing the foreign key to the table to which the referenced child entity is
mapped. For example, consider the CUSTOMER table to be the parent table and the
ADDRESS table to be the child table. You can use the @JoinColumn annotation to map
these two tables if the CUSTOMER table contains a foreign key column that is the primary
key column in the ADDRESS table.
@PrimaryKeyJoinColumn annotation: You can use the
@PrimaryKeyJoinColumn annotation to implement a one-to-one relationship between
two tables if the foreign key reference exists in the table to which the referenced entity is
mapped. For example, consider that table A and table B share the same primary key, and
the primary key of table B is also a foreign key referencing the primary key of table A.
Such associations are mapped by using the @PrimaryKeyJoinColumn annotation.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 22
Copyright 2009, Oracle. All rights reserved.
Implementing One-to-One Relationships
Example: Mapping a one-to one relationship between the
Customer class and the Address class by using the
@JoinColumn annotation
// In the Customer class:
@Table(name="CUSTOMER")
...
@OneToOne
@JoinColumn(name="MAILING_ADDRESS_REF",
referencedColumnName="ADDRESS_PK")
protected Address address;
...
// In the Address class:
@Table(name="ADDRESS")
...
@column(name="ADDRESS_PK")
...
Implementing One-to-One Relationships (continued)
The slide shows a code example of implementing a one-to-one relationship between the
Customer and Address entities by using the @JoinColumn annotation. The CUSTOMER table
contains a foreign key named MAILING_ADDRESS_REF that refers to the ADDRESS tables
ADDRESS_PK primary key. The @JoinColumn annotations name element refers to the name of
the foreign key in the CUSTOMER table. The referencedColumnName element specifies the
name of the primary key in the ADDRESS table that the MAILING_ADDRESS_REF foreign key
(located in the CUSTOMER table) refers to. The relationship is defined in the
Customer.address field in the Customer entity.
In case of a bidirectional one-to-one relationship, the entity in the inverse side of the relationship
contains the mappedBy element in the @OneToOne annotation. For example, to make the
relationship between the Customer entity and the Address entity bidirectional, add the
following code to the Address entity:
...
@OneToOne(mappedBy="address")
protected Customer customer;
...
Note: You do not have to redundantly specify the @JoinColumn annotation in the
Address.customer field in the Address entity. Moreover, if you want to make the
relationship unidirectional in the opposite direction, move the @JoinColumn annotation from
Customer.address into the Address.customer field.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 23
Copyright 2009, Oracle. All rights reserved.
Implementing Many-to-One Relationships
Mapping a many-to-one relationship:
Using the @ManyToOne annotation
Defines a single-valued association
Example: Mapping an Orders class to a Customer
// In the Order class
@Entity
@Table(name="ORDER")
public class Order ... {
...
@ManyToOne
@JoinColumn(name="ORDERS_CUSTID_REF",
referenceColumnName="CUSTID_PK", updatable=false)
protected Customer customer;
...
}
Implementing Many-to-One Relationships
The @ManyToOne annotation defines a single-valued association to another entity that has many-to-one
multiplicity. The Order entity shares a many-to-one relationship with the Customer entity. The name
element of the @JoinColumn annotation refers to the foreign key in the ORDER table. The
referencedColumnName element specifies the primary key in the CUSTOMER table (which is
mapped to the Customer entity) that the foreign key in the ORDER table refers to. The relationship is
defined in the Order.customer field in the Order entity.
Note: The @OnetoOne, @ManyToOne, @OneToMany, and @ManyToMany annotations also provide
the following optional attributes:
targetName identifies the fully qualified class name of the associated entity. It is optional because
the name of the associated target entity can usually be inferred from the type of the object being
referenced.
cascade defines a comma-separated set of operations propagated to the associated entity. The
types of cascade operations are:
- PERSIST: Causes associated entities to be inserted
- MERGE: Causes associated entities to be merged (inserted or updated)
- REMOVE: Causes associated entities to be deleted
- REFRESH: Causes associated entities to be refreshed
- ALL: Includes all the four operations
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 24
Implementing Many-to-One Relationships (continued)
Note: When true, the nullable attribute of @Column or @JoinColumn indicates that the field
allows database NULL values to be inserted; otherwise, a NULL is not allowed. When the updatable
attribute is false for the @Column or @JoinColumn annotations, the persistence provider cannot
modify the column value; otherwise, it can be changed.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 25
Copyright 2009, Oracle. All rights reserved.
Implementing One-to-Many Relationships
Mapping a one-to-many relationship by using the @OneToMany
annotation.
//In the Customer class:
@Table(name="CUSTOMER")
...
@OneToMany(mappedBy="customer")
protected Set<Order> order;
...
// In the Order class:
@Table(name="ORDER")
...
@ManyToOne
@JoinColumn(name="ORDERS_CUSTID_REF",
referenceColumnName="CUSTID_PK", updatable=false)
protected Customer customer;
...
Implementing One-to-Many Relationships
A @OneToMany annotation defines a many-valued association with one-to-many multiplicity.
The Set<Order> type defines a generic collection of Order objects. By using generic
collection types, the JPA persistence provider determines the entity type at the other end of the
relationship. As a result, all that is required to resolve the mapping for the @OneToMany side is
the field or property specified on that entity, which in this case is customer.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 26
Copyright 2009, Oracle. All rights reserved.
Implementing Many-to-Many Relationships
Mapping a many-to-many relationship by using the
@ManyToMany annotation.
// In the Customer class:
...
@ManyToMany(cascade=PERSIST)
@JoinTable(name="CUST_SUP",
joinColumns=
@JoinColumn(name="CUST_ID",referencedColumnName="CID"),
inverseJoinColumns=
@JoinColumn(name="SUP_ID", referencedColumnName="SID"))
protected Set<Supplier> suppliers;
...
// In the Supplier class:
...
@ManyToMany(cascade=PERSIST, mappedBy="suppliers")
protected Set<Customer> customers;
...
Implementing Many-to-Many Relationships
A @ManyToMany annotation defines a many-valued association with many-to-many
multiplicity. A customer can purchase goods from multiple suppliers, and a supplier can sell
goods to multiple customers. This type of mapping requires an association or join tables that
holds references back (foreign key) to the primary keys of the entities at either end of the
relationship. For example, the CUST_SUP association table (specified by the name attribute of
the @JoinTable annotation) has two columns: CUST_ID is a reference column pointing back
to the CID primary key column in the CUSTOMER table, and SUP_ID is a reference column
pointing to the SID primary key column in the SUPPLIER table.
The use of the mappedBy element in the @ManyToMany annotation allows the mapping
information contained in the @JoinTable annotation to be shared by both the relationship
fields.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 27
Copyright 2009, Oracle. All rights reserved.
Quiz
In a unidirectional relationship, both the entities have a
relationship field or property that refers each other.
1. True
2. False
Answer: 2
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 28
Copyright 2009, Oracle. All rights reserved.
Managing Entities
Entities are managed by using the EntityManager API.
EntityManager performs the following tasks for the
entities:
Implements the object-relational mapping between Java
objects and database
Performs the CRUD operations for the entities
Manages the life cycle of the entities
Manages transactions
Managing Entities
The JPA EntityManager interface manages entities in terms of actually providing
persistence services. The entities do not persist themselves. The EntityManager interface
reads the ORM metadata for an entity and performs persistence operation. The
EntityManager knows how to create, read, update, and delete (CRUD) entities from the
database. In addition, you can use EntityManager to manage the life cycle, performance
tuning, caching, and transactions for the entities.
You learn more about the EntityManager interface in the lesson titled Manipulating JPA
Entities with the EntityManager API.
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 29
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Create an JPA entity
Select a primary key field
Perform object relational mapping by using annotations
Map inheritance between entities
Map relationships between entities
Oracle Fusion Middleware 11g: Build Java EE Applications 8 - 30
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practice covers the following topics:
Creating a simple entity bean by coding the bean
Using the JDeveloper wizards to create a set of entity
beans
Creating and managing a session bean that provides client
access to the entity beans
Creating a test client to invoke the session bean
Copyright 2009, Oracle. All rights reserved.
Manipulating JPA Entities with the
EntityManager API
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Declare an EntityManager reference with the
@PersistenceContext annotation
Look up an EntityManager reference by using
dependency injection
Use the EntityManager API to:
Find an entity by its primary key
Insert a new entity
Modify an existing entity
Delete an entity
Execute dynamic queries with the Query API
Write simple JPQL queries
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 3
Copyright 2009, Oracle. All rights reserved.
What Is EntityManager?
EntityManager:
Is an interface defined in JPA
Is a standard API for performing CRUD operations for
entities
Acts as a bridge between the object-oriented and the
relational models
JPA
EntityManager Entities
manages
What Is EntityManager?
EntityManager is an interface that is defined as a part of the EJB 3.0 Java Persistence API
(JPA) specification. It specifies standard APIs for managing the life cycle of the entities, and
also for performing a create, read, update, and delete (CRUD) operation on the entities. The
EntityManager acts as a bridge between the object-oriented and the relational worlds. It
interprets the object-relational mapping (ORM) specified for an entity and saves the entity in the
database.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 4
Copyright 2009, Oracle. All rights reserved.
Application entity classes
(Persistence unit)
Persistence
context
What Is EntityManager?
EntityManager is:
Associated with a persistence context
An object that manages a set of entities defined by a
persistence unit
EntityManager
Database
manages
What Is EntityManager? (continued)
EntityManager is also an instance that is associated with a persistence context. A
persistence context is defined as a set of managed entity instances, each of which has a unique
persistent identity. The persistence context shown in the diagram is the set of entity instances
associated with a row in a database. The EntityManager interface provides methods that
manage entity instances and their life cycles within the persistence context. The
EntityManager API is used to create and remove persistent entity instances to find entities
by their primary key and to query entities.
By default, the lifetime of the persistence context corresponds to the life of a transaction. An
extended persistence context can be extended beyond that of a single transaction. The
EntityManager API assumes that the mapped database is accessed using read-committed
isolationthat is, it uses an optimistic locking strategy.
A persistence unit defines a set of:
Entities that can be managed by a specific EntityManager instance
Related and grouped application classes that are mapped to a single database
An entity has a persistence identity when it has been assigned a unique identifier value, such as
the primary key. The persistence identity is used to ensure that an entity is unique.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 5
Copyright 2009, Oracle. All rights reserved.
Persistence context
Managing an Entity Life Cycle
with EntityManager
New
Managed
Detached
Removed
EntityManager
Database
= Persistent identity
1
4
persist()
merge()
remove()
INSERT
DELETE
flush()
3
merge()
UPDATE
SELECT
2
find()
flush()
Managing an Entity Life Cycle with EntityManager
The diagram shows the life cycle of an entity as managed by the EntityManager API. The
diagram does not illustrate the handling of related entities or error scenarios. The numbers
represent state changes of entities while the methods of the
javax.persistence.EntityManager interface are executed on the entity.
1. A new entity does not have a persistent identity and is not associated with a persistence
context until either a persist() or merge() operation is executed by the
EntityManager. In either case, a database INSERT statement is executed, the entity
enters the managed state, and it becomes known as a managed entity.
2. A managed entity has a persistence context and identity that is initialized when the find()
method is called. A find() method executes a SELECT statement based on the primary
key and results in a new instance of an entity that forms a part of the managed persistence
context. On a managed entity, flush() causes an UPDATE, and a merge() is ignored.
3. A detached entity is an object resulting from a transaction commit or rollback scenario, or
a serialized instance passed as a parameter from a separate application tier. A detached
entity is not associated with a persistence context until a merge() is performed. Then the
entity becomes managed and an UPDATE is applied to the associated database row.
4. A removed entity has a persistence context and identity, and is marked for DELETE when
the remove() method is executed. A flush() removes the entity from the database.
Note: Not all the methods from the EntityManager interface are shown.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 6
Managing an Entity Life Cycle with EntityManager (continued)
A detached entity instance continues to live outside the persistence context in which it was
persisted or retrieved. Therefore, the state of the detached entity may not synchronize with the
database.
An application can access the available state of the detached entity instance after the persistence
context ends, provided that the available state is a persistent field that:
Is not annotated with fetch=LAZY
Was accessed by the application
If the persistent field is an association, its available state can be accessed only if the associated
instance is available.
Note: The EntityManager contains() method can be used to check whether an entity
instance is managed in the current persistence context. The contains() method returns:
TRUE if the entity was retrieved and not removed or detached, or if the entity is new and
persisted
FALSE if the entity is detached or removed, or if it is new and not persisted
Entity Life-Cycle Callback Methods
Each entity may implement various callback methods during the management of an instances
life cycle. A method designated as a life-cycle callback method receives notification of events
that affect the entity during its life cycle. A life-cycle callback method may be defined in either
the entity class or entity listener class. Any entity may have any number of listener classes
defined. A callback method defined in the entity class has the following signature:
void method-name()
A callback method defined in the entity listener class has the following signature:
void method-name(Object obj)
Here, the Object argument is the entity instance for which the callback is invoked.
Callback methods can be public, private, protected, or at the package level, but they
cannot be static or final. The Java Persistence API specification defines the following
annotations to designate a life-cycle event callback method:
PrePersist is invoked before the EntityManager persist() method is
executed.
PostPersist is invoked after the entity has been made persistent.
PreRemove is invoked before the EntityManager remove() method is executed.
PostRemove is invoked after the entity has been removed.
PreUpdate is executed before the database update operation occurs.
PostUpdate is executed after the database update operation occurs.
Note: PreUpdate and PostUpdate methods are invoked before or after (respectively)
when the entity state is updated, or when the changes are flushed to the database, which
may occur at the end of a transaction.
PostLoad is invoked after the entity has been loaded into the current persistence context
or after the refresh operation (before a query result is accessed or an association is
traversed).
Note: Life-cycle methods are also invoked on operations with appropriate cascade-type
operations on associated entities.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 7
Copyright 2009, Oracle. All rights reserved.
Accessing an EntityManager Instance
in an Application
Container-managed EntityManager instances:
Are implemented inside a Java EE container
Use the @PersistenceContext annotation
Are obtained in an application through dependency injection
or JNDI lookup
Application-managed EntityManager instances:
Are implemented outside a Java EE container
Are obtainable by using the EntityManagerFactory
interface
Accessing an EntityManager Instance in an Application
The most common and widely used EntityManager in a Java EE environment is the
container-managed EntityManager. In this mode, all the EntityManager instances are
injected into the applications by using the @PersistenceContext annotation. The Java EE
container manages the task of looking up, opening, and closing the EntityManager, and is
also responsible for managing the transaction boundaries. Therefore, a container-managed
EntityManager must implement the Java Transaction API (JTA) transactions. You can
obtain a container-managed EntityManager in an application through dependency injection
or through JNDI lookup.
The application-managed EntityManager enables you to control every aspect of
EntityManagers life cycle in the application code. In this mode, the EntityManager is
retrieved through the EntityManagerFactory API. Because application-managed
EntityManager is implemented outside a Java EE container, the transactions in application-
managed EntityManager is controlled through the EntityTransaction API.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 8
Copyright 2009, Oracle. All rights reserved.
Creating a Container-Managed EntityManager
Instance
A session bean using container injection:
@Stateless
public class CustomerBean {
@PersistenceContext(unitName="Model")
private EntityManager em;
...
public void createCustomer() {
final Customer cust = new Customer();
cust.setName("Valli Pataballa");
...
em.persist(cust);
}
...
}
Creating a Container-Managed EntityManager Instance
The slide shows an example of a session bean acquiring an EntityManager instance through
container injection (dependency injection) by implementing the @PersistenceContext
annotation. In this case, the EntityManager instance is bound to the Model persistence unit,
which includes the Customer entity. If a Java EE module has a single persistence unit,
specifying the unitName is redundant. The EntityManager is used to persist a new
Customer instance by invoking the persist() method.
Note: Persistence units cannot be set up using code. You need to configure them by using the
persistence.xml deployment descriptor.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 9
Copyright 2009, Oracle. All rights reserved.
Creating an Application-Managed
EntityManager Instance
A Java SE application using an EntityManagerFactory
API:
public class CustomerApp {
public static void main(String args[]) {
final EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Model");
final EntityManager em =
emf.createEntityManager();
final Customer cust = new Customer()
cust.setName("Ron Howard");
...
em.persist();
}
}
Creating an Application-Managed EntityManager Instance
The slide shows an example of how a Java SE application obtains an EntityManager
instance. In this case, an EntityManagerFactory instance is created and bound to the
Model persistence unit (defined in the persistence.xml deployment descriptor), which
includes the Customer entity. The createEntityManagerFactory() method of the
javax.persistence.Persistence object is essentially a programmatic substitute for
the @PersistenceUnit annotation that is used to inject an instance of
EntityManagerFactory in a Java EE environment. An EntityManager instance is then
created from that factory and is used to persist a new Customer instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 10
Copyright 2009, Oracle. All rights reserved.
Specifying Database Operations with
the EntityManager API
The EntityManager API provides the following methods that
map to CRUD database operations:
find(classname,pk)
SELECT
createQuery()
createNamedQuery()
persist(o)
INSERT DELETE
remove(o)
Specifying Database Operations with the EntityManager API
The EntityManager API provides the following methods that map to CRUD database
operations:
persist() maps to an INSERT (create) operation.
find() maps to a SELECT (read) operation.
remove() maps to the DELETE operation.
merge() attaches an entity instance to the EntityManagers persistence context,
making the instance managed. You can update an entity by using the entitys public API to
modify its persistent state, or by using an update query. In both the cases, the actual
database update happens when the current transaction context commits. Alternatively, you
can call the flush() method to persist entity state before the current transaction context
commits.
Note: The Java Persistence API specification assumes the use of optimistic locking, where the
databases to which persistence components are mapped are accessed by implementations using
read-committed isolation. The specification does not define database isolation levels.
Note: The EntityManager interface provides additional methods, known as the Query API,
for finding entities:
createQuery() creates a Query object for executing a Java Persistence Query
Language (JPQL) statement.
createNamedQuery() creates a Query object for executing a named JPQL or native
query.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 11
Copyright 2009, Oracle. All rights reserved.
Commonly Used Methods in the
EntityManager Interface
Method signature of the most commonly used methods of the
EntityManager interface:
public void persist(Object entity);
public <T> T merge(T entity);
public void remove(Object entity);
public <T> T find(class<T> entityClass, Object
primaryKey);
public void flush();
public void refresh(Object entity);
public void clear();
public Query createQuery (String jpqlString);
public Query createNamedQuery (String name);
Commonly Used Methods in the EntityManager Interface
The slide shows the method signature of the most commonly used methods of the
EntityManager interface.
persist()saves an entity instance into the database, and also makes the entity managed.
It takes an entity object as a parameter.
merge()merges the state of the given entity into the EntityManagers persistence
context. It takes an entity object as the parameter and returns the entity instance that the
state was merged to.
remove()removes the entity instance from the database.
find()finds an entity instance by its primary key. It retrieves an entity instance from the
database by using the entity class name and the entity ID, which are passed as the methods
parameter.
flush()synchronizes the state of the entities in the EntityManagers persistence
context with the database.
refresh()resets the state of the instance from the database, overwriting any changes
made to the entity. It takes an entity object as its parameter.
clear()clears the EntityManagers persistence context, causing all managed entities
to become detached. Changes made to entities that have not been flushed to the database
are not persisted.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 12
Commonly Used Methods in the EntityManager Interface (continued)
createQuery()creates a dynamic query by using a JPQL statement. It takes a JPQL
query string as its parameter.
createNamedQuery()creates an instance of Query for executing a named query (in
the JPQL or in native SQL) on the entity instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 13
Copyright 2009, Oracle. All rights reserved.
Quiz
The application-managed EntityManager is implemented
outside a Java EE container.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 14
Copyright 2009, Oracle. All rights reserved.
Inserting New Data
To insert new data, perform the following steps:
1. Create a new entity object.
2. Call the EntityManager.persist() method.
@PersistenceContext(unitName="Model")
private EntityManager em; // inject the EntityManager
... // object
public void persistUser() {
Users user = new Users();
user.setFirstName("Steve");
user.setLastName("King");
em.persist(user);
// On return the user object contains persisted state
// including fields populated with generated id values
}
Inserting New Data
The process of creating new data rows requires two steps, provided that you have created an
instance of EntityManager:
1. Create an instance of the entity by using the new operator and a constructor of the entity
class. Optionally, call the setter methods of the new object to set the state (except for the
generated or calculated values, such as primary key fields).
2. Call the persist() method of the EntityManager object with the entity instance to
be persisted.
Note: If the assigned or generated primary key value is not unique, an exception is thrown.
On return, the object supplied as the parameter is updated with the persistent state of the object.
This means that the generated primary key and calculated fields of the entity are updated to be
consistent with the state of the associated data row in the database table. For this reason, you are
able to determine the value of generated primary key fields after the persist() operation is
successfully executed.
Note: If the entity being persisted has relationships with other entities, the related entity objects
are also inserted in the same persistence context. The related entities can be created in the same
way or can be located by using a find() or Query API method.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 15
Copyright 2009, Oracle. All rights reserved.
Deleting Data
To delete data, perform the following steps:
1. Find, set, or refresh the state of the entity to be deleted.
2. Call the EntityManager.remove() method.
@PersistenceContext(unitName="Model")
private EntityManager em;
...
// Remove a Product by primary key Id value
public void removeProducts(Products products) {
products = em.find(Products.class,
products.getProdId());
em.remove(products);
}
...
Deleting Data
To delete an entity instance, perform the following steps:
1. Either query, refresh, or create the entity with its state containing the primary-key value.
2. Execute the remove() method of the EntityManager object.
Note: A removed entity becomes detached, and the state of the deleted entity is available in
memory after the call is made. If the deleted entity is related to other entity objects, the related
entities may be deleted if the relationship mapping or annotation is specified as
cascade=CascadeType.REMOVE. Otherwise, an exception is thrown if dependent entities
exist.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 16
Copyright 2009, Oracle. All rights reserved.
Updating and Synchronizing the Entity with the
Database
1. Retrieve the rows in a database table into the entity by
using the EntityManager API.
2. Use the setter methods of the entity to update the data
attributes.
3. Use the flush() method to synchronize the state of the
entities in the EntityManagers persistence context with
the database.
4. Use the merge() method to reattach an entity to the
persistence context to synchronize it with the database.
Updating and Synchronizing the Entity with the Database
To update rows in a database table, retrieve those rows into the entities by using the
EntityManager API. Then you can use the setter methods of the entities to update any data
attributes (mapped to table columns in the database). The updates are automatically sent to the
database.
By default, all the EntityManager operations (such as persisting entities, removing entities,
and updating entities) are cached in the memory. They are synchronized to the database in a
single batch when the current thread (the stack of method calls) finishes, or before the next
database query is issued (whichever comes first). Inside a transaction, you can flush the current
in-memory changes in the EntityManager to the database by calling the
EntityManager.flush() method.
The EntityManager keeps track of the entities that it retrieved, and captures all updates to
the entities that need to be synchronized to the database. But how do you update a detached
entity and get the changes synchronized to the database? You can use the
EntityManager.merge() method to perform this task by passing the entity instance as the
call parameter.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 17
Copyright 2009, Oracle. All rights reserved.
Updating Data
To update data, perform the following steps:
1. Find, set, or refresh the state of the entity to be updated.
2. Call the EntityManager.merge() method.
@PersistenceContext(unitName="Model")
private EntityManager em;
...
// Update a Product by primary key Id value
public void updateProducts(Products products) {
products = em.find(Products.class,
products.getProdId());
products.setListPrice("1000");
...
em.merge(products);
}
...
Updating Data
To update an entity instance, perform the following steps:
1. Either query, refresh, or create the entity with its state containing the primary-key value.
2. Update the entity attributes with new values.
3. Execute the merge() method of the EntityManager object.
Note: merge() will insert the object if it does not exist. Therefore, if you want an update,
ensure that the object exists.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 18
Copyright 2009, Oracle. All rights reserved.
Finding an Entity by Primary Key
To locate an entity by primary key, perform the following steps:
1. Create and set the primary key object and value.
2. Call the EntityManager find() method with the
following parameters:
Entity class
Primary-key object
import org.srdemo.persistence.Users;
@PersistenceContext(unitName="Model")
private EntityManager em;
...
public Users findUserByPrimaryKey(Long id) {
Users user = null;
user = em.find(Users.class, id);
return user;
}
Finding an Entity by Primary Key
The find() method of the EntityManager API performs a search by primary key
operation. To use the find() method, perform the following steps:
1. Obtain and set the value of the primary key object.
2. Call the find() method with the first parameter specifying the Java type of the entity to
be retrieved, and the second parameter specifying the identity value for the entity instance
to retrieve.
The find() method will return a null if the entity is not found for an instance of the class for
the entity type specified in the first parameter.
Note: The entity instance returned by the find() method is automatically attached to the
EntityManagers persistence context, which means that you can use the EntityManager
to manage that entity instance.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 19
Copyright 2009, Oracle. All rights reserved.
Quiz
The EntityManager.flush() method:
1. Retrieves the rows in a database table into the entity
2. Reattaches an entity to the persistence context
3. Synchronizes the state of the entity in the
EntityManagers persistence context with the database
Answer: 3
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 20
Copyright 2009, Oracle. All rights reserved.
What Is JPA Query API?
The JPA Query API:
Includes:
EntityManager methods to create queries
Query interface methods for executing queries
Java Persistence Query Language (JPQL)
Supports:
Named queries
Dynamic queries
What Is JPA Query API?
The JPA Query API enables you to use either JPQL or SQL to create and execute queries. The
Query API includes EntityManager interface methods for creating instances, the Query
interface methods that define and execute the query, and JPQL that defines searches against
persistent entities independent of the mechanism used to store those entities.
The Query API supports two types of queries: named and dynamic. Named queries are meant
to define complex or commonly used queries, and are intended to be stored and reused.
Alternatively, dynamic queries are created without disturbing normal operations at run time. The
named queries are prepared once at the time of initialization, whereas dynamic queries are
prepared every time they are executed.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 21
Copyright 2009, Oracle. All rights reserved.
Retrieving Entities by Using the Query API
The EntityManager interface provides the Query API
methods to execute JPQL statements:
createQuery(String jpql)
createNamedQuery(
String name)
EntityManager
Query instance methods:
setParameter(String, Object)
Object getSingleResult()
List getResultList()
int executeUpdate()
Query setMaxResults(int)
Query setFirstResult(int)
Retrieving Entities by Using the Query API
The EntityManager interface exposes a Query API through the following methods:
createQuery()creates a dynamic query and accepts a JPQL query as its parameter.
createNamedQuery() creates a query instance based on a named (precompiled)
query. In this case, the query can be JPQL or native SQL.
All methods return a javax.persistence.Query instance, which provides the following
API calls:
setParameter(String, Object) sets the named parameter to the object value.
getSingleResult() returns a single Object instance result, if any.
getResultList() returns a List collection of entity instances, if any.
setMaxResults(int) and setFirstResult(int) return a Query object and
accept integer parameters. The former sets the maximum number of instances returned,
and the latter sets the first instance to be returned. These methods are useful for paging
through large sets of data.
executeUpdate() executes a JPQL UPDATE or DELETE operation returning the
number of rows affected, and throws an exception for a SELECT statement.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 22
Copyright 2009, Oracle. All rights reserved.
Writing a Basic JPQL Statement
Syntax for a simple JPQL statement:
Examples:
Find all Users entities:
Find a Users entity with a specific email address:
Find a Users entity based on a parameter value:
SELECT object(o)
FROM abstract-schema-name o
[WHERE condition]
SELECT object(o) FROM Users o
SELECT object(o) FROM Users o
WHERE o.email = '[email protected]'
SELECT object(o) FROM Users o
WHERE o.firstName = :givenName
Writing a Basic JPQL Statement
The slide illustrates the basic query syntax for a JPQL statement, which has:
A mandatory SELECT clause that returns a single entity instance or a collection of entity
instances, whose types are determined by the abstract-schema-name specified in the FROM
clause
A mandatory FROM clause that identifies the abstract-schema-name of the entity being
queried. The abstract-schema-name is the name of the entity class, which is given an
identifier name (such as the alias o in the slide examples). The identifier refers to an
instance of the entity and is used as a prefix for field names, such as o.firstName in the
last example in the slide.
An optional WHERE clause with one or more conditions
The OBJECT()function that is applied to the abstract-schema-name identifier indicates that
instances of the identifier type are being retrieved. The first example returns a collection of all
Users entity instances. The second query example returns a single Users instance where the
email property has the string value [email protected]. The last example is a
parameterized JPQL statement. The named parameter givenName is preceded by a colon and
acts as a placeholder that supplies the value for the conditional expression at run time. The
parameterized query can be written by using the following syntax:
SELECT object(o) FROM Users WHERE o.firstName = ?1
Note: The numbered parameter notation is an alternative to the named notation.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 23
Copyright 2009, Oracle. All rights reserved.
Creating Named Queries
To create a named query, perform the following steps:
1. Define the query with the NamedQuery annotation.
2. Create a Query object for the named query with the
createNamedQuery() method, setting parameters and
returning results.
public List<Users> findUsersinCity(String cityName) {
Query query = em.createNamedQuery("findUsersByCity");
query.setParameter("city", cityName);
return query.getResultList();
}
@NamedQuery(name="findUsersByCity",
query="SELECT object(o) FROM Users o " +
"where o.city = :city");
Creating Named Queries
Often queries are predefined and stored with EntityManager, allowing queries to be defined
ahead of time, recalled, and used at run time.
To create a named query, write a NamedQuery annotation to define the query name and query
string in the entity bean. In the example in the slide, the findUsersByCity named query is
declared in the Users.java entity class definition.
To use the named query with the Query API, perform the following steps:
1. Create a Query object with the createNamedQuery() method, whose argument is the
name assigned to the name attribute of the NamedQuery annotation.
2. With the query instance returned, call the setParameter() method to supply values
for each named parameter or placeholder in the query string. The example uses one
parameter called city, whose value is supplied by the cityName argument in the
findUsersinCity() method.
3. Call the getResultList() method to return a collection of entities.
Note: You call the getSingleResult() method to execute a SELECT query that returns a
single result, and you call the getResultList() method to execute a SELECT query that
returns the query results as a list. If you call the getSingleResult()method and more than
one result is returned, it will throw a NonUniqueResultException.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 24
Copyright 2009, Oracle. All rights reserved.
Writing Dynamic Queries
Example: Find service requests by primary key and a specified
status.
public List findServiceRequests(Long id, String status){
if (id != null && status != null ) {
Query query = em.createQuery(
"select object(sr) from ServiceRequests sr " +
"where sr.svrId = :srvId and sr.status = :status");
query.setParameter("srvId", id);
query.setParameter("status", status);
return query.getResultList();
}
return null;
}
Writing Dynamic Queries
By using the Query API of EntityManager, you can create dynamic queries that respond to
the application requirements. The createQuery()method accepts a single String
argument that defines a JPQL statement to select ServiceRequests entity object instances
matching particular search criteria supplied by the application user.
Because the parameter is a String, the query string can be dynamically constructed based on
user input to return the desired results.
The example in the slide shows how to use the following:
The setParameter() method supplies values to the :srvId and :status
placeholders in the query string.
The getResultList() method returns a List collection of service-request instances
because the JPQL statement return type is defined by the abstract schema name used in the
FROM clause. In this case, the type is ServiceRequests.
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 25
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Declare an EntityManager reference with the
@PersistenceContext annotation
Look up an EntityManager reference by using
dependency injection
Use the EntityManager API to:
Find an entity by its primary key
Insert a new entity
Modify an existing entity
Delete an entity
Execute dynamic queries with the Query API
Write simple JPQL queries
Oracle Fusion Middleware 11g: Build Java EE Applications 9 - 26
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers the adding named queries to entities.
Copyright 2009, Oracle. All rights reserved.
Developing the Business Logic with
Web Services
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to:
Describe Web service technologies
Identify the role of SOAP, Web Services Description
Language (WSDL), and Universal Description, Discovery
and Integration (UDDI) in Web services
Decide on the Web service development approach
Develop Web services by using the top-down approach
with JDeveloper
Objectives
This lesson provides an overview of Web services, and covers:
A discussion about some of the de facto standards such as SOAP, WSDL, and UDDI
A complete description about developing a Web service by using the bottom-up approach
and top-down approach
Developing a Web service by using the top-down approach with Oracle JDeveloper 11g
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 3
Copyright 2009, Oracle. All rights reserved.
Web Service
Is a technology that is based on a set of standards for
building interoperable distributed applications
Performs self-describing business functions
External
applications
HTML
XML
Web
presentation
Business
logic
Web
service
Database
Application server
HTTP client
Web Service
A Web service is designed to expose business logic that can be accessed by any application. It is
a software component, identified by a Uniform Resource Identifier (URI), whose interfaces and
bindings can be described by standard Extensible Markup Language (XML) vocabularies.
The Web service technology (based on a set of standards) has revolutionized the way in which
the application-to-application communication used to happen in an enterprise. An enterprise
system usually has multiple applications, each running on different hardware and sometimes
implemented in different languages. These applications often need to exchange data with one
another, and developers must write additional code to make this integration possible. The Web
service technology provides a solution for the enterprise application integration.
A Web service supports direct interaction with other software applications or components and is
network accessible. With a Web service, you can make your applications programmatically
accessible to other applications over the Internet. Web services establish a method to standardize
communication, making it easier for applications to share information.
For example, in the case of a merger or an acquisition, companies can avoid investing large
sums of money on developing software to integrate the systems of the different companies.
The information systems of different companies can be linked by extending each companys
business applications as Web services. These business systems can then be accessed by using
simple SOAP messages over the normal HTTP protocol.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 4
Copyright 2009, Oracle. All rights reserved.
Web Service Standards
Web service standards can be defined in terms of the following:
SOAP
WSDL
UDDI
Web Service Standards
SOAP is an extensible, text-based framework that enables communication between
different applications without prior knowledge of each others environment.
The applications can interoperate with each other or even connect dynamically to services
without establishing any initial agreements between them. SOAP is extensible and is
generous in terms of supporting intermediaries and layered architectures.
WSDL is an XML-based language for describing and accessing Web services. It provides
a simple way for service providers to describe the basic format of requests to their systems
regardless of the underlying protocol (such as SOAP) or encoding (such as Multipurpose
Internet Mail Extensions [MIME]). WSDL describes services as a set of endpoints
operating on messages that are described abstractly.
UDDI is an XML-based registry that enables businesses to list themselves and their
services on the Internet. It is a platform-independent framework for describing services,
discovering businesses, and integrating business services. Its ultimate goal is to streamline
online transactions by enabling companies to find one another on the Web and to make
their systems interoperable for e-commerce.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 5
Copyright 2009, Oracle. All rights reserved.
SOAP: XML Messaging for Web Services
SOAP:
Is an XML-based protocol for exchanging data
Represents requests and responses as XML messages
Uses HTTP and other protocols at the transport layer
Supports data encoding and literal styles
Hides details of implementations
Works with:
Any programming language
Any hardware and software platform
Client
Request (SOAP)
Web service
Response (SOAP)
SOAP: XML Messaging for Web Services
SOAP is a lightweight, XML-based protocol for exchanging data in a distributed environment.
It hides technology choices and implementation details from both the service requestor and the
service provider. SOAP is defined in XML and, therefore, it places no restriction on the format.
It introduces a self-describing data representation in XML. By looking at the request and
response messages, you can easily find out what was sent as part of a request and what the
response was. If the response has a fault element, by looking at it, you know what caused the
error.
SOAP provides a mechanism for exchanging structured and typed information between peers in
a decentralized, distributed environment by using XML. SOAP itself does not define any
application semantics such as a programming model or implementation-specific semantics;
instead, it defines a simple mechanism to express application semantics by providing a modular
packaging model and encoding mechanisms for encoding data within modules.
SOAP V1.2 describes how the data types defined in the associated XML schemas can be
serialized, or marshaled, over HTTP (or other transports such as Simple Mail Transfer Protocol
[SMTP] or FTP). SOAP is transport independent. Most common implementations are over
HTTP. Both the publisher and the consumer of SOAP messages must have access to the same
XML schemas in order to correctly exchange the information. The schemas are normally posted
on the Internet and may have to be downloaded to be used by applications that exchange XML
messages whose structures are based on the schema.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 6
Copyright 2009, Oracle. All rights reserved.
Web Services Description Language (WSDL)
A WSDL document is an XML
document that describes:
What the service does
How the service is accessed
Where the service is located
It defines the messages and
the operations of a service
abstractly in XML.
Types
Messages
Port types
Bindings
Services
WSDL document structure
WSDL document
Web Services Description Language (WSDL)
WSDL corresponds to an interface definition language that provides a standard way to describe
Web services. WSDL uses the XML format for describing Web services. It describes what
functionality a Web service offers, how it communicates, and where it is accessible. Because
WSDL is in the standard XML format, the services developed can easily be made available to
thousands of users. Users must invoke the correct services with the appropriate parameters.
WSDL defines an XML grammar to specify the location of the service and to describe the
operations of a service.
A WSDL document contains the service interface definition, the implementation details, the
access protocol, and the contact endpoints information about an operation. The WSDL document
describes a Web service by using these major elements:
<portType>: Describes a Web service, the operations that can be performed, and the
messages that are involved
<message>: Describes the messages used by the Web service; defines the data elements
of an operation
<types>: Defines the data types used by the Web service
<binding>: Defines the communication protocols used by the Web service
<service>: Describes the name and location of the Web service and the context with
which it can be accessed
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 7
Copyright 2009, Oracle. All rights reserved.
UDDI Registry
The UDDI registry:
Is an online electronic registry for registering businesses
and Web services
Is a specification for description and discovery
Supports Publishing and Inquiry APIs to publish and query
a Web service
UDDI Registry
You should have seen the definition and the benefits of Web services. You should have also
observed that WSDL is used to describe Web services and that SOAP is used to invoke them. To
invoke a Web service, the service requestor should first discover the service, and then send the
SOAP message. Because UDDI is a registry where businesses and Web services are registered,
the requestor can use UDDI to discover a Web service.
UDDI is a directory service where businesses can register and search for Web services. It is a
platform-independent framework for describing services, discovering businesses, and integrating
business services.
The UDDI registry can be used at a business level to verify whether there are any Web service
interfaces with a given type of service. UDDI serves as a mechanism for businesses to reach
their customers and partners. It is used to locate information about how the service is exposed
and to learn the technical details required for interaction with that service.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 8
UDDI Registry (continued)
The UDDI business registry is a logically centralized, physically distributed service with
multiple root nodes that replicate data with each other on a regular basis. After a business
registers with a single instance of the business registry service, the data is automatically shared
with other UDDI root nodes and becomes freely available to anyone who needs to discover
which Web services are exposed by a particular business. These are public registries. You can
also have private UDDI registries.
To ensure that most platforms can access UDDI services, the UDDI directory exposes a set of
APIs. These APIs fall under two main categories: Inquiry and Publishing. To use these APIs,
you must send SOAP messages with appropriate body content. The SOAP response that comes
back from a UDDI registry contains information about the businesses that match the search
criteria.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 9
Copyright 2009, Oracle. All rights reserved.
Web service
Service
implementation
Web Service Architecture
Web service
client application
Web services
directory
Internet
Interface
(WSDL)
WSIL
browser
1
Generate
WSDL
2
Register
(UDDI)
3
Find
(UDDI)
Find Locate
Invoke request (SOAP)
Send response
(SOAP)
4
5
Web Service Architecture
The diagram shows a conceptual architecture of Web services. The provider of a Web service
performs the following steps to expose a Web service endpoint:
1. Generating the WSDL: The Web service is developed and the XML format describing the
service (the WSDL) is generated.
2. Registering with the Web service registry: The Web service provider registers itself as a
business entity and publishes the WSDL in one or more UDDI registries (for example,
Oracle Service registry).
The consumer of a Web service performs the following steps to invoke a Web service:
3. Searching with an UDDI registry or a Web Services Inspection Language (WSIL)
browser: The consumer searches the UDDI registry or uses a WSIL browser to locate the
WSDL for the Web service.
4. Invoking the Web service: The consumer sends a SOAP request to invoke the Web service
by using the information stored in the WSDL. The WSDL information, which is obtained
from the UDDI registry or WSIL browser, includes:
- The URL for the service endpoint to locate the service functions
- The WSDL that defines interface methods and messages provided by the service
5. Communicating the response: The provider responds with a SOAP message that
communicates information to the consumer. The SOAP request and response are typically
transmitted using the simple HTTP request-response protocol.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 10
Web Service Architecture (continued)
WSIL is defined as an XML grammar by the WS-Inspection specification to address the need to
facilitate the aggregation of references to different types of service description documents stored
in the form of WSDL and UDDI registries. The WS-Inspection specification provides a means to
inspect sites for service and locate pointers to service description documents.
Note: Java applications can use the Web Services Invocation Framework (WSIF), which is a
Java API to invoke Web services.
You can use the WSIL browser to search for WSDL descriptions of services. The WSIL browser
can locate services published in UDDI registries or in local file systems.
The following are the file formats used extensively by Web service standards:
XML: Extensible Markup Language (XML) is a set of rules for defining data markup in a
plain text format.
XSD: XML Schema Definition (XSD) specifies how to formally describe the elements in
an XML document.
XSL: Extensible Stylesheet Language (XSL) is a specification (or template) for separating
style from content when you create HTML or XML pages.
XSLT: Extensible Stylesheet Language Transformations (XSLT) is the language used in
XSL style sheets to transform XML documents into other XML documents.
XPath: XML Path (XPath) is a language with a set of syntax rules for defining parts of an
XML document.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 11
Copyright 2009, Oracle. All rights reserved.
Quiz
The <portType> element in a WSDL describes a Web
service, the operations that can be performed, and the
messages that are involved.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 12
Copyright 2009, Oracle. All rights reserved.
Web Service Metadata for
Java Platform (JSR-181)
Is a Java specification to develop Web services by using a
document written in annotated Java syntax
Defines a processor model that acts as a bridge between
the annotated document and the Web service artifacts
Web Service Metadata for Java Platform (JSR-181)
JSR-181 defines an annotated Java syntax to enable easy definition of Web services in Java.
According to JSR-181, a Java Web service is a simple Plain Old Java Object (POJO) with a few
annotations. The annotations are used to define and describe the Web service architecture, such
as the Web service name, all the methods that should be exposed in the Web service interface,
parameters, their types, the bindings, and other information.
JSR-181 also defines a processor (processing environments) that acts as a tool to bridge the gap
between an annotated file and the Web service artifacts. For example, the processor can be used
to generate a WSDL document from an annotated file or vice versa. It can also be used to
generate an Enterprise Archive (EAR) package that can be deployed as a Web service within
any Java 2, Enterprise Edition (Java EE) 1.4compliant container. It is essential to note that JSR-
181 does not define any run-time environment for the Web services, but only provides a model
for processing the annotated file and mapping the annotated file to the Java EE 1.4 run-time
environment.
Note: JSR-175 defines the rules for adding annotations into the Java language syntax.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 13
Copyright 2009, Oracle. All rights reserved.
Examining the JSR-181 Processor Model
JSR-181
processor
WSDL
Deployment
descriptors
Java
classes
Web service artifacts
Annotated
Java file
Generates
Input
Examining the JSR-181 Processor Model
The slide displays a sample JSR-181 processor model. The JSR-181 processor can be any tool
(such as JDeveloper) that enables a Web service program written in Java (by using Java
annotations) to produce the required Web service artifacts. It provides all the functionalities
(such as generating Java-to-WSDL mappings and WSDL-to-Java mappings, and generating
EAR packages) required to develop and deploy the Java Web service.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 14
Copyright 2009, Oracle. All rights reserved.
Describing JSR-181 Annotations
Standard annotations defined by JSR-181:
javax.jws.soap.SOAPBinding
@SOAPBinding
javax.jws.WebResult
@WebResult
@WebParam
@WebMethod
@WebService
Annotation
javax.jws.WebService
javax.jws.WebParam
javax.jws.WebMethod
Java Class or Interface
Describing JSR-181 Annotations
As defined in JSR-181, the important annotations used to define a Java class as a Web service
are the following:
@WebService: Marks the class indicating that it implements the Web service
@WebMethod: Marks methods that generate the service endpoint interface
@WebParam: Defines Web service parameters that are specified in the wsdl:part
element of the WSDL document
@WebResult: Defines the return value in the wsdl:part element of the WSDL
document
@SOAPBinding: Specifies the SOAP binding details, and provides annotation members
for style, use, and parameterStyle properties that customize mappings in the
wsdl:binding element
Oracle WebLogic Server Web Services supports the entire set of annotations described in
JSR-181.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 15
Copyright 2009, Oracle. All rights reserved.
Sample Annotated Java Web Service File
import javax.jws.WebService;
import javax.jws.WebMethod;
@WebService(serviceName = "Hello")
public class Hello {
@WebMethod(operationName="sayHello")
public String sayHello() {
return "Hello World!";
}
}
1
2
Sample Annotated Java Web Service File
The slide shows a sample annotated Java file. The Hello Java class is deemed to be a Web
service implementation class, which defines and implements a sayHello method that can be
exposed as a Web service. The annotations are:
1. @WebService: Marks the Hello class indicating that the class implements the Web
service. The serviceName attribute specifies the name of the Web service.
2. @WebMethod: Marks the sayHello method that generates the service endpoint interface
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 16
Copyright 2009, Oracle. All rights reserved.
What Is JAX-WS?
JAX-WS:
Stands for Java API for XML Web Services
Defines the core specification for the Web services
standard in Java EE 5
Provides an extension to the JAX-RPC 1.0 Web services
standard
Enables you to expose both POJOs and stateless
Enterprise JavaBeans (EJBs) as Web services by
implementing metadata annotations
What Is JAX-WS?
Java API for XML Web Services (JAX-WS) is a specification for building Web services and
Web service clients that communicate by using XML-based protocols (such as SOAP). JAX-WS
allows developers to write message-oriented as well as RPC-oriented Web services.
For more information about Web services technology and its standards, refer to the OracleAS
10g R3: Build Web Services course.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 17
Copyright 2009, Oracle. All rights reserved.
Quiz
As defined in JSR-181, the important annotations used to
annotate a Java class as a Web service are:
1. @SOAPBinding
2. @Resource
3. @WebParam
4. @EJB
5. @WebService
Answers: 1, 3, 5
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 18
Copyright 2009, Oracle. All rights reserved.
Web Service Development Approach
There are two approaches:
Bottom-up approach
You can generate the Web service by using the existing
code.
It requires little or no knowledge of WSDL or XML.
Top-down approach
You can generate the Web service from an existing WSDL
file.
Server-side and client-side development can be done
simultaneously.
Web Service Development Approach
Web services can be generated by using either a bottom-up approach or a top-down approach.
Each of these has advantages and disadvantages that determine the pattern that should be used in
a given situation.
The bottom-up approach starts with coding the business logic that is being abstracted into an
interface definition. The interface is then exposed as a Web service. It requires little or no
knowledge of WSDL or XML because the WSDL document is automatically generated by the
development tools.
With the top-down approach, both the server-side and the client-side developers use a WSDL
document to produce the artifacts necessary for their respective environments. The server-side
developer can start with the WSDL document to define new implementations of portType
(defined by WSDL), and the client-side developer can start with the same WSDL document to
develop a Web service client. This leads to the independent development of the client-side and
server-side simultaneously. The top-down approach model also provides reusability of new
schema types developed for the current Web service. It can be achieved by simply incorporating
the new XML Schema Definition (XSD) schema into the required Web services.
Some developers have also used a third method, primarily because of shortcomings or defects in
tools, and a lack of thorough understanding of Web services tools and technologies. In what is
called round-trip development, the developer uses a part of the top-down process followed by
parts of the bottom-up process. For example, you will follow this approach when you are given a
WSDL and also have to work with existing domain classes.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 19
Copyright 2009, Oracle. All rights reserved.
Web service
client development
Web service
development
Bottom-Up Approach
Web service
client
Java class/EJB
Java-to-WSDL
WSDL
Generate Java
artifacts
Generate WSDL
artifacts
1
2
1
2
WSDL-to-Java
Bottom-Up Approach
Web Service Development
1. The business logic is coded using either Java classes or EJBs. These contain methods that
are exposed in the Web service interface.
2. The Web service generation tool (in this case, Java-to-WSDL) generates the WSDL.
The Web service generation tool can be the WebServicesAssembler (WSA) tool or
JDeveloper.
Web Service Client Development
1. The Web service generation tool (in this case, WSDL-to-Java) generates the client-side
proxy class and other client-side artifacts from the WSDL.
2. The Web service client application uses the proxy class to communicate with the Web
service application.
Note: With the bottom-up approach, the development of the Web service client is dependent on
the implementation of the Web service because all the client-side artifacts (such as the proxy and
the stubs) are developed from the WSDL document. The bottom-up approach also often leads to
very fine-grained services. Therefore, the top-down approach of Web services development is
much preferred.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 20
Copyright 2009, Oracle. All rights reserved.
Web service
client development
Web service
development
Top-Down Approach
Web service
client
Web service
implementation
WSDL-to-Java
WSDL-to-Java
WSDL
XSD schemas
Generate Java
artifacts
Generate Java
artifacts
1
2 2
1
Top-Down Approach
Web Service Development
1. A WSDL document is created. You can incorporate multiple XSD schemas in the WSDL
document, which describes the input and the output data types for the Web service
operation.
2. The Web service generation tool (in this case, WSDL-to-Java) generates the Java artifacts,
such as the service endpoint interface, which are implemented as a Web service.
Web Service Client Development
1. This is similar to Web service development.
2. The Web service generation tool (in this case, WSDL-to-Java) generates the Java artifacts,
such as the client-side proxy class and stub, which are used by the client application to
communicate with the Web service.
Note: In the top-down approach, the development of the client-side and the server-side can be
done in parallel, and without any dependency on each other.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 21
Copyright 2009, Oracle. All rights reserved.
Developing a Web Service by Using
the Top-Down Approach
To develop a Web service by using the top-down approach in
JDeveloper, perform the following steps:
1. Define an XSD schema.
2. Create the WSDL document incorporating the XSD
schema.
3. Generate the Web service artifacts from the WSDL
document by using JDeveloper.
4. Implement the Web service logic.
5. Deploy the generated artifacts by using JDeveloper.
Deploys
Web service
WSDL
Java
classes
XSD
Developing a Web Service by Using the Top-Down Approach
To develop a Web service by using the top-down approach model, you start with defining a
single or a collection of XSD schemas, which describe the input and output data types for the
Web service operations. These XSD schemas are used to design the WSDL document. It can be
done by either creating a new WSDL document or editing an existing one. The WSDL document
is processed to generate the Java artifacts by using JDeveloper. These artifacts are used to
implement the Web service logic. These artifacts are then assembled and deployed to the
application server.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 22
Copyright 2009, Oracle. All rights reserved.
Defining an XSD Schema
Input
type
Output
type
Defining an XSD Schema
You can create an XSD schema by using JDeveloper. You can visually insert or modify the XSD
elements (such as complex types and elements) by using the XSD schema editor utility in
JDeveloper. You can insert an XSD node (such as an element, a complex type, and a simple
type) by right-clicking any existing node and selecting one of the following options: insert
before element, insert inside element, or insert after element, and thereby selecting the
appropriate node to insert. You can modify an existing node by double-clicking a specific node
and modifying its value.
The XSD schema (CreditService.xsd) has been defined that consists of XML complex
type and XML elements. The complex CreditCard type is defined to handle the input
operation type (method parameter), and the elementsvalid and errorare defined to
handle the output operation type (method return type) of the Web service logic (implemented
using a Java method).
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 23
Copyright 2009, Oracle. All rights reserved.
Creating the WSDL Document
XSD
schema
<definitions name="CreditService"...
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org"
...
<xsd:import namespace="http://www.example.org "
schemaLocation="CreditService.xsd"/>
</schema>
</types>
...
WSDL
Imports
Creating the WSDL Document
The slide displays a part of the WSDL document where the specified XSD schema
(CreditService.xsd) has been incorporated.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 24
Copyright 2009, Oracle. All rights reserved.
Creating the WSDL Document
...
<message name="CreditCardValidationRequestMessage">
<part name="CreditCard" element="types:CreditCard"/>
</message>
<message name="CreditCardValidationResponseMessage">
<part name="valid" element="types:valid"/>
</message>
...
<portType name="ValidateCreditCard">
<operation name="VerifyCC">
<input message="tns:CreditCardValidationRequestMessage"/>
<output message="tns:CreditCardValidationResponseMessage"/>
...
</operation>
</portType>
...
Creating the WSDL Document (continued)
The <message> and <portType> elements of the WSDL document are displayed in the
slide. There are two <message> elements: CreditCardValidationRequestMessage
and CreditCardValidationResponseMessage.
CreditCardValidationRequestMessage takes care of handling the input operation
and is associated with defining the input parameter for the Web service operation defined in the
Web service endpoint interface. The part element indicates that the Web service operation
takes a parameter of the CreditCard type. The type is defined as an XML element in the
XSD schema (CreditService.xsd).
Similarly, CreditCardValidationResponseMessage is associated with the output
operation and specifies the return type of the Web service operation.
The <portType> element indicates the name of the implementation class,
ValidateCreditCard. This class implements the method defined in the service endpoint
interface. The <portType> element also specifies the <operation> element whose name
attribute is set to VerifyCC, which is the name of the method defined in the service endpoint
interface. The service endpoint interface is then exposed as a Web service. The <input> and
<output> elements contain the corresponding input message and output message names.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 25
Copyright 2009, Oracle. All rights reserved.
Modifying the WSDL Document
Modifying the WSDL Document
You can create or modify the WSDL document in JDeveloper by using the WSDL editor tool.
The WSDL editor gives you a design view of the WSDL document that enables you to segregate
the different sections of the WSDL document (such as, services, bindings, and port
types) in a hierarchical structure. You can expand the tree of a specific section, and can
modify the values of different elements present in that specific section. You can double-click
any element to modify its value. For example, to modify the value of the VerifyCC element
(in the port types section), click the VerifyCC element to open the dialog box that enables
you to modify the attributes (such as the name attribute) of the VerifyCC element. You can
also perform the same task by using the Structure window. For example, you can insert a
predefined schema in the WSDL document by executing the following steps:
1. Open the WSDL document in design view.
2. In the Structure window of JDeveloper, navigate to definitions > Types > types > schema
node. Right-click the schema node and select Insert inside schema > xsd:import from the
pop-up menu.
3. Enter CreditService.xsd in the schemaLocation field and
http://www.example.org in the namespace field.
4. Click the OK button.
Similarly, you can also modify the values of the other elements present in the WSDL document.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 26
Copyright 2009, Oracle. All rights reserved.
Creating the Web Service by Using
Oracle JDeveloper 11g
1
2
Creating the Web Service by Using Oracle JDeveloper 11g
You can use the Oracle JDeveloper 11g Integrated Development Environment (IDE) to develop
Web services. You can expose any Java resource (such as a Java class or an EJB) as a Web
service in JDeveloper. JDeveloper also enables you to generate a Web service from a WSDL
document and a PL/SQL package.
You can use the Java Web Service from WSDL Wizard to generate the Web services artifacts
from a given WSDL document.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 27
Copyright 2009, Oracle. All rights reserved.
Implementing the Web Service Logic
Implementing the Web Service Logic
The slide displays the JDeveloper IDE. It consists of the Application Navigator pane, Structure
pane, and the code editor. In the Application Navigator, all the necessary resources or artifacts
(such as the WSDL document and XSD schema) to develop and deploy a Web service
application are displayed (generated by the wizard).
If you select any of the Web service artifacts from the Application Navigator pane, the
corresponding structure of the component is displayed in the Structure pane. For example, if you
select the Web service implementation class (ValidateCreditCardImpl.java) in the
Application Navigator pane, you can see its constructor and methods in the Structure pane. Now,
if you select any of the methods of the ValideateCreditCardImpl.java in the
Structure pane, you can see the corresponding code in the code editor. The Web service
application exposes the verifyCC() method as a Web service. You need to modify the code
to implement the verifyCC() method (Web service logic) to validate a credit card.
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 28
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe Web service technologies
Identify the role of SOAP, WSDL, and UDDI in Web
services
Decide on the Web service development approach
Develop Web services by using the top-down approach by
using JDeveloper
Oracle Fusion Middleware 11g: Build Java EE Applications 10 - 29
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers the following topics:
Creating a Web service application by using the top-down
Web service development approach
Testing the Web service application by using JDeveloper
Copyright 2009, Oracle. All rights reserved.
Developing the Web Interface Using
JavaServer Faces
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Describe the purpose of JavaServer Faces
Use JSF components
Explain the use of managed beans
Describe the life cycle of a JSF application
Explain the role of the JSF tag libraries
Describe how JDeveloper supports JSF
Create a JSF-based JSP in JDeveloper
Objectives
In this lesson, you learn about JavaServer Faces (JSF), which are JavaServer Pages (JSP) that contain
special user interface (UI) components. Like JSP, JSF supports the MVC framework and is,
therefore, a valuable technology for building the view component of Java EE applications. You learn
that JDeveloper provides a feature-rich development environment for building JSF pages quickly and
easily.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 3
Copyright 2009, Oracle. All rights reserved.
JSF: Overview
JavaServer Faces (JSF) is a server-side component
framework for Web applications.
JSF:
Is an implementation of the MVC design pattern
Enables separation of business and presentation logic
Enables separation of navigational and data flow
JSF: Overview
JSF is a server-side UI technology, as opposed to a client-side UI technology such as Swing. JSF is
also a component-based architecture, which means that instead of working with markup, the
developer works with UI components, similar to Swing.
JSF also implements the MVC design pattern, which includes the UI (view), controller, and the
model. The built-in controller provides developers with a technique to cleanly separate the
navigational aspects of an application from the data presentation logic.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 4
Copyright 2009, Oracle. All rights reserved.
JSF: Benefits
Simplifies Java EE development
Is intended for RAD style development tools
Is a component-based architecture
Supports Java EE framework:
State management
Error handling
Input validation
Type conversion
Event handling
Page navigation
Is portable across JSF implementations
JSF: Benefits
The JSF technology provides Web application life cycle management through a controller servlet and
a rich component model with event handling and component rendering.
Because JSF is a component-based architecture, it simplifies the development process. Part of the
direction of the JSF specification is to make the architecture readily accessible by using GUI
development tools, such as JDeveloper.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 5
Copyright 2009, Oracle. All rights reserved.
Key Terms
UI component: The components that manage data to be
displayed on a page
Managed bean: Objects that maintain data and methods
that are used across multiple pages
Expression Language: Shortcut to access properties and
methods from a JSF page
Navigation model: The rules that govern page flow
Life cycle: The processes that are executed from the time
a page is loaded until it is complete
Key Terms
Each of these key terms is discussed in detail later in this lesson.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 6
Copyright 2009, Oracle. All rights reserved.
JSF Architecture
JavaServer Faces has:
A set of prefabricated UI components
An event-driven programming model
A component model that enables third-party developers to
build additional components
It can be thought of as Swing for server-side applications.
JSF Architecture
The UI component classes included with the JavaServer Faces technology include the component
functionality, not the client-specific presentation. With ease-of-use being the primary goal, the
JavaServer Faces architecture defines a separation between application logic and presentation,
making it easy to connect the presentation layer to the application code.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 7
Copyright 2009, Oracle. All rights reserved.
JSF Architecture
Page
HTML
render kit
Page
Back-end
code
HTML
browser
Phone/
PDA
WML
render kit
Front
controller
JSF Architecture (continued)
The slide shows the JSF architecture in a simplified manner. Just like any other MVC-based
architecture, JSF architecture has its own front controller called the FacesServlet. The FacesServlet
acts as a gatekeeper for the application. Upon an initial Web request to access a JSF application, the
FacesServlet handles the request by first preparing the JSF context, which is a Java object that holds
all application data.
As stated earlier, a JSF page is made of a tree of UI components that can be associated with model
objects called backing beans. These backing beans handle application or business logic for the
application.
JSF UI components have the ability to render themselves differently depending on the client type
viewing the component. When a page has to be rendered to a particular client type, whether the client
type is an HTML browser running on a desktop or a Wireless Markup Language (WML) browser
running on a wireless phone, a particular renderer is used for displaying the data maintained in the UI
components. Because JSF decouples the UI component from its rendering logic, the same UI
component is used for displaying information about different client types using different protocols.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 8
Copyright 2009, Oracle. All rights reserved.
JSF Components
JSF Components consists of three parts:
UI components: Functionality, attributes, or behavior
Renderers: Converts components to and from a specific
markup language
Render kits: Library of renderers (The Basic
HTML RenderKit is part of the specification.)
JSF Components
The Components model is a major part of JSF. JSF Components consist of three parts:
The components themselves define basic attributes, functionality, or behavior for the
components. For example, a button has some expected behaviors, such as what happens when it
is clicked. These are defined within the component. If a component has a value-changed event,
the developer can create a listener for that event. The framework then invokes that listener at
the right time. Components are standardized within JSF, so you can use any component from
any vendor with the framework and mix and match them as required, and they all behave in the
same way.
Renderers convert a component to and from a specific markup language. A renderer makes JSF
components flexible with respect to which type of client can use the component. Attributes say
nothing about how the component is displayedthat is the responsibility of the renderer. A
renderer for a component may output very complex HTML, such as a tree control, or a simple
item, such as output text. The generated markup may include JavaScript as well as HTML if a
particular component has complex client-side behaviors.
Render kits are a library of renderers. The Basic HTML RenderKit is part of the JSF
specification.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 9
Copyright 2009, Oracle. All rights reserved.
JSF UI Components
Are the basic building blocks of a JSF application
Are stateful server objects
Do not define rendering
Can represent simple to
complex user interface
components ranging from
a button or input field to a complete page
Can be associated to model data objects through value
binding
Can use helper objects, such as validators, converters,
listeners, and events
JSF UI Components
JSF UI components are what you use to build a JSF user interface. UI components are stateful server
objects. They are maintained on the server. They do not define any rendering characteristics.
Rendering is handled by the renderers.
The components range from simple text field components to complex shuttle type controls. Each
component can be associated to a model by using value binding. Each component can also use helper
objects that are included in JSF, such as validators, converters, listeners, and events.
When a JSP page is created using JSF components, a component tree or view is built into memory
on the server with each component tag corresponding to a UIComponent instance in the tree. The
component tree is used by the JSF framework to handle your application request and create a
rendered response.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 10
Copyright 2009, Oracle. All rights reserved.
JSF Component Architecture
Expr. Language
Managed bean
JSF page
J2EE Persistence Layer/JDBC
<f:view>
<h:inputText
required="true"
value="#{emp.name}"
/>
</f:view>
Markup
RDBMS
UI component
Device Renderer
JSF Component Architecture
In this diagram, all the three main JSF components are highlighted: the component renderer, the
component itself, and the binding expression.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 11
Copyright 2009, Oracle. All rights reserved.
Quiz
Identify the correct statements about JavaServer Faces.
1. It includes a set of APIs for representing the user
interface (UI) components and managing their state,
handling events and input validation, converting values,
defining page navigation, and supporting
internationalization and accessibility.
2. It includes a default set of UI components.
3. It includes a server-side event model.
4. It includes state management.
5. It includes managed beans (JavaBeans created with
dependency injection).
Answers: 1, 2, 3, 4, 5
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 12
Copyright 2009, Oracle. All rights reserved.
Tag Handlers and Component Trees
Each tag has a corresponding tag handler class.
JSF tag handlers collaborate with each other to build a
component tree.
Examples of JSF tags are:
f:form, h:inputText, h:inputSecret,
h:commandButton
UIForm
UIInput UIOutput UICommand
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 13
Copyright 2009, Oracle. All rights reserved.
Tag Libraries
Core tag library
f: tags for faces
Custom actions independent of any rendering kit
Example: f:validator, f:converter,
f:selectItem
HTML tag library
h: tag for HTML
Component tags for all UI components and HTML rendering
kit
Example: h:form, h:inputText, h:messages
Tag Libraries
Core tag library
Validation: It is difficult to imagine a Web application that does not perform a healthy dose of
data validation. JavaServer Faces provides a handful of standard validators and a simple
mechanism for implementing your own validation.
Data Converters: A Web application stores data of many types, but the Web user interface
deals exclusively with text. For example, suppose the user needs to edit a Date object. First,
the Date object is converted to a string that is placed inside a text field. The user then edits the
text field. The resulting string must be converted back to a Date object.
Navigation: Consider what happens when the user of a Web application fills out a Web page.
The user enters text and clicks option buttons and drop-down lists. All of these edits happen
inside the users browser. The changes are transmitted to the server when the user clicks a
button that posts the form data. At that time, the Web application analyzes the user input and
must decide which JSF page to use for rendering the response. The navigation handler is
responsible for selecting the next JSF page.
HTML tag library
This library contains tags for standard HTML style elements.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 14
Copyright 2009, Oracle. All rights reserved.
Configuration Files
faces-config.xml
Defines managed beans
Specifices navigation rules
Must exist with WEB-INF
Similar to struts-config.xml
Servlet mapping in web.xml uses a faces extension.
URL pattern *.faces maps to
java.faces.webapp.FacesServlet.
Configuration Files
One or more configuration files are used to configure a JSF application. The main configuration file
for an application is the WEB-INF/faces-config.xml file. Files in the same format can be
bundled also within JAR files containing custom components, renderers, or any other custom JSF
classes.
Within the <faces-config> element body, top-level elements can be included in any order. Each
top-level element is described in a separate section in the appendix. The
top-level elements are all optional and can be included more than once, unless otherwise stated. Most
top-level elements contain other elements.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 15
Copyright 2009, Oracle. All rights reserved.
JSF Renderers
Two rendering models:
Direct implementation
Delegated implementation
Delegated implementation enables separation of UI from
how they appear to the user.
Each JSF implementation must provide a default RenderKit
instance.
JSF specification includes the Standard HTML RenderKit
Specification.
JSF Renderers
The renderer creates the client-side representation of the component, takes any input from the client,
and transforms it into something that the component can understand. The typical renderer
implementation generates HTML and understands how to transform values from HTML form POSTs
into values the component understands. However, this is not the only client type that can be rendered
by a JSF renderer. For example, the reference implementation comes with a set of Extensible User
Interface Language (XUL) renderers.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 16
Copyright 2009, Oracle. All rights reserved.
Managed Beans
Java objects (empty constructor), maps, lists
Defined in faces-config.xml
Defined with various scopes:
application
session
request
none
Lazy initialization by JSF as needed
Managed Beans
Along with components, managed beans are a key part of JSF. Any Java object can be a managed
bean as long as it has a no-arg constructor. The managed bean is defined in XML in the faces-
config.xml file. This file exists in the WEB-INF directory of the application and is the master file
for a JSF application.
When you create a page, you can automatically create a managed bean with references to the objects
you create on the page. This type of managed bean is called a backing bean, and it also provides a
place to put code. In many cases, the backing bean contains only action code with no references to
the UI components, or references to only a few of the components that you need to manipulate
programmatically.
Managed beans can also be used to hold information about the request, application, or session.
The life cycle of a managed bean is handled by JSF. When the bean is first referenced, JSF creates an
instance of the relevant Java class and keeps it around as long as is specified by the bean definition.
The none scope listed in the slide is used to define transitory objects that are used just to populate
other managed beans and are never used outside that context.
Usage of that managed bean is then through Expression Language, which is discussed in the
following slide.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 17
Copyright 2009, Oracle. All rights reserved.
Expression Language
Dot notation for attributes (JavaBean model):
#{userbean.name} same as
instance.getName();
Map notation:
#{foo["baa"]} same as
instance.get("baa");
Expressions can be of any depth:
#{foo["baa"].person.name}
Expression Language
Expression Language (EL) is the binding factor in JSF. It provides the hook between the user
interface and the managed bean facility. Almost any property in a component can be set to an EL
expression.
The primary use of EL is to set properties is to bind the value of a component to something in the
model. You can also bind attributes to EL, such as the rendered attribute supported by all
components. You can set a value directly or to an expression that evaluates to a Boolean value to do
conditional processing.
You can use EL not only for binding to managed beans, but also for directly referencing various
known scopes, such as request or session scope.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 18
Copyright 2009, Oracle. All rights reserved.
Life Cycle of a JSF Page
A JSF page is represented by a tree of UI components,
called a view.
When a client makes a request for the page, the life cycle
starts.
During the life cycle, JSF implementation must build the
view while considering the state saved from the previous
postback.
When the client performs a postback of the page, JSF
implementation must perform life-cycle steps:
Validation
Conversion
Life Cycle of a JSF Page
The life cycle of a JavaServer Faces page is similar to that of a JSP page. The client makes an HTTP
request for the page, and the server responds with the page translated to HTML. However, because of
the extra features that JavaServer Faces technology offers, the life cycle provides some additional
services to process a page.
A JavaServer Faces page is represented by a tree of UI components, called a view. When a client
makes a request for the page, the life cycle starts. During the life cycle, the JavaServer Faces
implementation must build the view while considering the state saved from the previous postback.
When the client performs a postback of the page, the JavaServer Faces implementation must perform
several tasks, such as validating the data input of components in the view and converting input data
to types specified on the server side. The JavaServer Faces implementation performs all these tasks
as a series of steps in the life cycle.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 19
Copyright 2009, Oracle. All rights reserved.
JSF Life Cycle: Initial Request
Restore/create
view.
Client/Browser
Render
response.
Apply
request
values.
Update
model.
Invoke
application.
Process
validation.
JSF Life Cycle: Initial Request
The life cycle handles both kinds of requestsinitial requests and postbacks. An initial request for a
page is when the user requests the page for the first time.
During the initial request, JSF creates a server-side component tree based on the components on the
page. It populates the tree with whatever values are appropriate at the time. Because this is an initial
request with no user input or actions to process, JSF executes only the restore view and render
response phases.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 20
Copyright 2009, Oracle. All rights reserved.
JSF Life Cycle: Postback
Restore/create
view.
Client/Browser
Render
response.
Apply
request
values.
Update
model.
Invoke
application.
Process
validation.
Life Cycle: Postback
A postback occurs when the user submits the form contained on a page that was previously loaded
into the browser as a result of executing an initial request. When the life cycle handles a postback, it
executes all the phases.
Apply request values: Components that hold a value, such as input fields, have their values applied
to their counterparts in the view tree. Events such as ValueChangeEvents (VCE) or ActionEvents
(AE) are queued for processing later at the end of this phase. A VCE means that a value has changed
for a specific UI component. An AE means that a button (or any UI component that is a source of an
action) was clicked.
Process validation: Validation and conversion logic is executed for each component (both
built-in validation and data conversion, or custom validation and conversion added onto the
components). If a validation error occurs, an error is reported, the life cycle halts, and the response is
rendered with validation error messages.
Update model: Any managed bean properties that are bound to UI components by using the Value
attribute are updated with the value of the component.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 21
Life Cycle: Postback (continued)
Invoke application: Queued ActionEvents are executed in this phase. For example, an action
method such as loginAction() is executed at this point.
Render response: Three things happen here1) a possible navigation is handled depending on the
outcome of the action method (if any), 2) the view tree renders itself to the client, and 3) the view
tree is saved for future requests.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 22
Copyright 2009, Oracle. All rights reserved.
Quiz
Backing beans are JSF-managed beans that are associated
with the UI components on a JSF page.
1. True
2. False
Answer: 1
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 23
Copyright 2009, Oracle. All rights reserved.
Using JSF Tag Libraries
JSF UI components are encapsulated in JSP
tag libraries:
Core: For application tasks,
such as validation, and data
type conversion
HTML: For rendering basic
HTML, such as input fields,
menus, tables, and buttons
Using JSF Tag Libraries
JDeveloper provides the standard JavaServer Faces (JSF) tag libraries for use in your JSF pages:
JSF Core tag library: Used with other components to perform core actions that do not depend
on a particular render kit
JSF HTML tag library: Used to represent HTML form controls and other basic HTML
elements. These controls display data or accept data from the user. This data is collected as part
of a form and is submitted to the server, usually when the user clicks a button.
To use any of the standard JavaServer Faces tags, you must include the taglib directives at the top
of each page containing the tags defined by the tag library. For example:
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
For a JSP document, the directives are different:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0
xmlns:h="http://java.sun.com/jsf/html
xmlns:f="http://java.sun.com/jsf/core">
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 24
Copyright 2009, Oracle. All rights reserved.
JSF Applications
A typical JSF application consists of:
One or more JSPs containing JSF components
A navigation model specified in the
faces-config.xml file
A set of managed beans that facilitate the UI logic of the
application
JSF Applications
Typically, a JSF application consists of a number of JSF pages connected by JSF navigation cases
that are defined in the faces-config.xml file. Each page probably uses a set of managed beans
to help facilitate page-specific UI application logic. It may also include other managed beans for
application-level methods, which are typically helper type methods that multiple pages may use.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 25
Copyright 2009, Oracle. All rights reserved.
JSF and JDeveloper 11g
JDeveloper provides many features for creating JSF
components:
JSF visual editing
JSF UI component
visual editing
Provides back-end
code generation
(double-click)
JSF Configuration Editor
for productive editing of faces-config.xml
JSF and JDeveloper 11g
JDeveloper is a feature-rich development environment for JSF. It provides visual editing for pages,
including drag-and-drop for JSF components. It also provides back-end code generation that creates
backing beans for you. It also keeps the backing beans in sync with components added to the page.
It also includes the JSF Configuration Editor that provides an easy way to see and modify any part of
the Faces configuration (managed beans, navigation cases, validators, converters, and so on).
When you create an application or page using JSF technology in JDeveloper, the necessary JSF tag
libraries and JAR files are automatically set up in the project properties. The faces-config.xml
file is created and the Faces Servlet and Faces Servlet Mapping definitions are automatically inserted
into a web.xml file.
In JDeveloper, you can develop applications with JSF technology when you:
Create a new application using a template, such as a Web application (JSF, EJB, or TopLink)
that uses the JSF technology scope
Create a new JSF Page Flow and Configuration file, or a JSF JSP file in an existing project
Add the JSF technology scope to an existing project in the project properties
Create a new project using an existing JSF application or .war file
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 26
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Diagram
JSF Navigation Diagram
JDeveloper includes a Visual Editor or diagrammer for the JSF navigation model, which you can also
edit directly in XML. The diagram in the slide depicts a series of rules, which are named events that
link pages (or views in JSF) together. If a command item, such as a button on the Main page, raises
an editProduct outcome, then the JSF framework acts as a page flow controller to forward (or
redirect, if required) the browser to the EditProduct page.
This is an example of where good tooling for JSF can make a real difference. Rendering the
navigation model as a diagram and enabling visual editing gives the developer both a productive way
of defining the application page flow and a visual document of the application page structure and
relationships.
If the application flow needs to changefor example, if a page needs to be addedthen the
relationships in this diagram can be redrawn, but the pages themselves do not have to be touched.
This is an implementation of the JSP Model 2 Architecture as pioneered by the Struts framework.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 27
Copyright 2009, Oracle. All rights reserved.
Adding to JSF with ADF Faces
Built on top of JSF APIs
Much larger component set:
over 100 types
More advanced and
interesting components
Partial-page rendering
Scrollable, sortable table
Rich feature set for customizing
applications
Uses Ajax, SVG, and
Flash
ADF model support
Runs on any JSF-compliant implementation
Adding to JSF with ADF Faces
Oracle ADF Faces is a rich set of user interface components based on the JavaServer Faces JSR.
Oracle ADF Faces uses the flexible JSF rendering architecture to combine the power of Ajax and JSF
to provide over 100 components with built-in functionalitysuch as data tables, hierarchical tables,
and color and date pickersthat can be customized and reused in your application.
Each component also offers complete customization, skinning, and support for internationalization
and accessibility. ADF Faces also provides a rich set of Flash- and SVG-enabled components that are
capable of rendering dynamic charts, graphs, gauges, and other graphics that provide real-time
updates. This built-in support for Ajax, SVG, and Flash enables developers to build rich UIs without
an extensive knowledge of the underlying technologies.
ADF Faces also simplifies the code necessary to connect application logic in existing business
services to UI components. Its components are JSR-227 compliant, enabling developers to easily
bind services to their UIs at design time.
ADF Faces components can be used in any IDE that supports JSF.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 28
Copyright 2009, Oracle. All rights reserved.
Using ADF Faces Layout Components
af:spacer
af:separator
af:panelSplitter
af:panelStretchLayo
ut
af:panelAccordion
af:panelFormLayout
af:panelTabbed
af:showDetail
af:panelGroupLayout
af:panelCollection
af:panelHeader
af:showDetailHeader
af:group
af:panelList
af:panelBox
af:panelBorderLayout
You can use the following components to achieve the desired
layout:
Using ADF Faces Layout Components
ADF Faces layout components include the following:
spacer, separator: To add blank space and divider lines
panelSplitter, panelStretchLayout: To enable automatic component stretching on
your pages
panelSplitter, panelAccordion: To create collapsible panes
panelFormLayout: To arrange items in columns or grids
panelTabbed: To create stacked tabs
showDetail: To hide and display groups of content
panelGroupLayout: To enable automatic scrollbars on your pages, and arrange items
horizontally or vertically
panelCollection: To add menus, toolbars, and status bars to data aggregation components
such as tables, trees, and tree tables
panelHeader, showDetailHeader: To create titled sections and subsections
group: To group semantically related components
panelList, panelBox: To create styled lists and content boxes
panelBorderLayout: To place items in fixed, peripheral areas around a central area
The following slides show how to use these components for various layout tasks.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 29
Copyright 2009, Oracle. All rights reserved.
Creating Resizable Panes
Panel Splitters
af:panelSplitter
Horizontal
orientation:
Vertical
orientation: Nested:
Creating Resizable Panes
When you have groups of unique content to present to users, consider using multiple panes separated
by adjustable splitters. When viewing the page in a client browser, users can change the size of panes
by dragging a splitter, and also choose to collapse or restore panes. When a pane is collapsed, its
contents are hidden; when a pane is restored, the contents are displayed.
The af:panelSplitter component enables you to organize contents into two panes separated
by an adjustable splitter. Clicking the arrow button on a splitter collapses or expands a pane (and its
contents) in the direction of the arrow. The value of the orientation attribute determines
whether the panes are horizontal (default) or vertical. The pane contents are specified in the facets
first and second. The slide shows a page divided into two horizontal panes (placed left to right),
and another page divided into two vertical panes (placed top to bottom). It also shows a nested
panelSplitter, created by a horizontal panelSplitter into the first facet of a vertical
panelSplitter.
The af:panelSplitter component uses geometry management to stretch its children
components at run time. This means when the user collapses one pane, the contents in the other pane
are explicitly resized to fill up the available space. If af:panelSplitter is the root component
for your page contents, you have to set the inlineStyle attribute on af:panelSplitter for
maximum stretching.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 30
Copyright 2009, Oracle. All rights reserved.
Creating Collapsible Panes
with the Panel Splitter Component
Attributes:
Both panes displayed, with
splitterPosition governing the
size of the first pane and splitter
arrow pointed toward the first pane
false false
false
true
true
collapsed
First pane hidden; second pane
stretches
false
Both panes displayed, with
splitterPosition governing the
size of the second pane and splitter
arrow pointed toward the second
pane
true
Second pane hidden; first pane
stretches
Behavior
true
positionedFromEnd
Creating Collapsible Panes with the Panel Splitter Component
Another feature of the panel splitter component is that users can collapse or restore its panes. When a
pane is collapsed, the pane contents are hidden; when a pane is restored, the contents are displayed.
The collapsed attribute on af:panelSplitter determines whether the splitter is in a
collapsed (hidden) state. By default, the collapsed attribute is false, which means both panes
are displayed. When the user clicks the arrow button on the splitter, collapsed is set to true and one
of the panes is hidden.
ADF Faces uses the collapsed and positionedFromEnd attributes to determine which pane
(that is, the first or second pane) to hide (collapse) when the user clicks the arrow button on the
splitter. When collapsed is true and positionedFromEnd is false, the first pane is
hidden and the second pane stretches to fill up the available space. When collapsed is true and
positionedFromEnd is true, the second pane is hidden instead. Visually, the user can know
which pane will be collapsed by looking at the direction of the arrow on the button. When the user
clicks the arrow button on the splitter, the pane collapses in the direction of the arrow. The
splitterPosition and collapsed attributes are persistablethat is, when the user moves
the splitter or collapses a pane, ADF Faces can implicitly persist the attribute value changes for the
component.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 31
Copyright 2009, Oracle. All rights reserved.
Creating Collapsible Panes
with the Panel Accordion
<af:panelAccordion>
<af:showDetailItem text="This is a pane"/>
<af:showDetailItem text="This is another pane"/>
</af:panelAccordion>
With default settings Characteristics of Panel
Accordion component:
Does not automatically
stretch it children
Panes cannot be resized at
run timeonly expand or
contract
Panes defined by
showDetailItem
Creating Collapsible Panes with the Panel Accordion Component
Another component that enables you to create collapsible panes is panel accordion. A series of
af:showDetailItem components inside af:panelAccordion make up the accordion panes,
with one af:showDetailItem component corresponding to one pane. The pane contents are the
children components inside each af:showDetailItem.
You can use more than one af:panelAccordion component on a page, typically in different
areas of the page, or nested. After adding the af:panelAccordion component, insert a series of
af:showDetailItem components to provide the panes by using one af:showDetailItem
for one pane. Then insert components into each af:showDetailItem to provide the pane
contents.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 32
Copyright 2009, Oracle. All rights reserved.
Panel Accordion Overflow
Automatic overflow icons
to display
content out of view
Panel Accordion Overflow
At run time, when available browser space is less than the space needed to display expanded pane
contents, ADF Faces automatically displays overflow icons that enable users to select and navigate to
those panes that are out of view. The slide shows overflow icons at the upper left (first example) and
at the lower right (second example). When the user clicks the overflow icon, ADF Faces displays the
overflow pop-up menu, as shown in the slide, for the user to select and navigate to a pane that is out
of view.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 33
Copyright 2009, Oracle. All rights reserved.
<af:showDetailItem
text="Browse Products"
inlineStyle="width:100%;
height:100%;" flex=1">
<af:showDetailItem
text="Selected Product"
inlineStyle="width:100%;
height:100%;" flex="2">
Setting Panel Accordion Properties
With discloseMany="true"
discloseNone="true"
Setting Panel Accordion Properties
The following properties govern the behavior of the panel accordion at run time:
discloseNone: Allow all panes to be collapsed at once (default is false)
discloseMany: Allow multiple panes to be expanded at once (default is false)
The following properties of showDetailItem affect the behavior of the accordion panes:
text: Specifies the text string to display as the title in the header of the container.
flex: Specifies a non-negative integer that determines how much space is distributed among
the af:showDetailItem components of one af:panelAccordion. By default, flex
is 0 (zero), that is, the pane contents of each af:showDetailItem are inflexible. To enable
flexible contents in a pane, specify a flex number larger than 0.
inflexibleHeight: Specifies the number of pixels a pane will use. Default is 100 pixels.
that is, if a pane has a flex value of 0 (zero), ADF Faces will use 100 pixels for that pane,
and then distribute the remaining space among the nonzero panes. If the contents of a pane
cannot fit within the af:panelAccordion container given the specified
inflexibleHeight value, ADF Faces automatically pushes out nearby contents into
overflow menus, as described previously.
Because neither of the above components automatically stretches its children, you may need to set
the width and height of any children of showDetailItem to 100%.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 34
Setting Panel Accordion Properties (continued)
The discloseMany attribute governs how many panes can be visible at once:
Set to true if you want users to be able to expand and see the contents of more than one pane
at the same time
By default, discloseMany is falsethat is, only one pane can be expanded at any one
time. For example, suppose there is one expanded pane A and one collapsed pane B when the
page is first loaded. If the user expands pane B, pane A will be collapsed because only one pane
can be expanded at any time.
The discloseNone attribute governs whether users can collapse all panes.
Set the discloseNone attribute to true to enable users to collapse all panes.
By default, discloseNone is falsethat is, one pane must remain expanded at any time.
You can add toolbars and toolbar buttons in the pane headers. To add toolbar buttons to a pane, insert
the af:toolbar component into the toolbar facet of the af:showDetailItem component
that defines that pane. Then insert the desired number of af:commandToolbarButton
components into the af:toolbar component. Although the toolbar facet is on
af:showDetailItem, it is the parent component af:panelAccordion that renders the
toolbar and its buttons.
To allow users to print the contents of a single pane, place the
af:showPrintablePageBehavior component (wrapped in af:commandButton) within
the af:showDetailItem whose pane contents you want users to be able to print.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 35
Copyright 2009, Oracle. All rights reserved.
Creating Titled Sections and Subsections
Panel header
component with
sections and
subsections:
af:panelHeader
Show detail header component with sections that expand or
collapse: af:showDetailHeader
Creating Titled Sections and Subsections
You may want to divide a page into sections and subsections, starting each section or subsection with
a header. The af:panelHeader component enables you to create sections and subsections with a
label and an icon at the top of each section or subsection header, as shown in the first example in the
slide.
To enable users to toggle the display of contents under each section or subsection header, use the
af:showDetailHeader component instead. This is similar to the af:panelHeader component,
except that it renders a toggle icon that lets users hide or display the section or subsection contents.
The second example in the slide shows a top section with its contents displayed, and a subsection
with its contents hidden. Partial page rendering (PPR), which is covered later in this lesson, is
automatically used to refresh a section of the page when the user selects to hide or show contents
under the header.
The disclosed attribute on af:showDetailHeader specifies whether to show or hide the
contents under its header. The default is falsethat is, the contents are hidden. When the user
clicks the toggle icon, an org.apache.myfaces.trinidad.event.DiscloserEvent is raised
to the server. If you want to perform special handling of this event, you can bind the components
disclosureListener attribute to a DisclosureListener method in a backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 36
Copyright 2009, Oracle. All rights reserved.
Grouping Related Components
Use af:group to:
Add multiple components to a facet
Group related
child components
<af:panelFormLayout>
<af:inputDate label="Pick a date"/>
<!-- first group -->
<af:group>
<af:selectManyCheckbox label=
"Select all that apply">
<af:selectItem label="Coffee" value="1"/>
//other select items
</af:selectManyCheckbox>
<af:inputText label="Special instructions"
rows="3"/>
</af:group>
<!-- Second group -->
<af:group>
<af:inputFile label="File to upload"/>
<af:inputText label="Enter passcode"/>
</af:group>
<af:inputText label="Comments" rows="3"/>
<af:spacer width="10" height="15"/>
<f:facet name="footer"/>
</af:panelFormLayout>
Grouping Semantically Related Components
The af:group component aggregates or groups together child components that are related
semantically. The af:group component does not provide any layout for its children. Used on its
own, the af:group component does not render anything; only the child components inside of
af:group render at run time.
You can use any number of af:group components to group related components together. For
example, you might want to group some of the input fields in a form layout created by
af:panelFormLayout, as shown in the example in the slide that groups two sets of child
components inside af:panelFormLayout.
When the af:group component is used as a child in a parent component that provides special
rendering for af:group children, then visible separators, such as bars or dotted lines, display
around the children of each af:group. For example, af:panelFormLayout and
af:toolbar support special rendering for af:group children. The example in the slide shows
how at run time the af:panelFormLayout component renders dotted separator lines before and
after the first and second af:group of children components. Children inside af:group are never
split across a column on a form.
The af:group component is especially useful when you need to group components under a
facet, because a facet may have only one child.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 37
Copyright 2009, Oracle. All rights reserved.
Arranging Items Around a Central Area
Arranging Items Around a Central Area
The af:panelBorderLayout component is a layout element for arranging components in
predefined, named areas around a center area. The center area is where direct children components of
af:panelBorderLayout render consecutively. In addition to the center area, the
af:panelBorderLayout component supports the following named areas, each of which is
defined by a facet bearing the name for the area:
top: Renders children above the center area
bottom: Renders children below the center area
start: Renders children at the left of the center area between the top and bottom facet
children, if the reading direction of the client browser is left-to-right. If the reading direction is
right-to-left, it renders children at the right of the center area.
end: Renders children at the right of the center area between the top and bottom facet
children, if the reading direction of the client browser is left-to-right. If the reading direction is
right-to-left, it renders children at the left of the center area.
left: Renders children at the left of the center area between top and bottom facet children.
If the reading direction is left-to-right, left has precedence over start if both left and
start facets are used. If the reading direction is right-to-left, left also has precedence over
end if both left and end facets are used.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 38
Arranging Items Around a Central Area (continued)
right: Renders children at the right of the center area between top and bottom facet
children. If the reading direction is left-to-right, right has precedence over end if both
right and end facets are used. If the reading direction is right-to-left, right also has
precedence over start if both right and start facets are used.
innerTop: Renders children above the center area, but below the top facet children
innerBottom: Renders children below the center area, but above the bottom facet children
innerLeft: Similar to left, but renders between innerTop and innerBottom, and
between left and the center area
innerRight: Similar to right, but renders between innerTop and innerBottom, and
between right and the center area
innerStart: Similar to innerLeft, if the reading direction is left-to-right; similar to
innerRight, if the reading direction is right-to-left
innerEnd: Similar to innerRight, if the reading direction is left-to-right; similar to
innerLeft, if the reading direction is right-to-left
Note: For BiDi support (right-to-left layout), Oracle Applications developers should not use the left
and right areas of af:panelBorderLayout. Start and end should be used instead of left and
right.
To add items in predefined areas using PanelBorderLayout:
1. Add the Panel Border Layout component to the JSF page.
2. To place content in the center area, insert the desired components inside
af:panelBorderLayout.
3. The children components are displayed consecutively in the order in which you inserted the
desired components. If you want some other type of layout for the children, wrap the
components inside af:panelGroupLayout.
4. To place the content in one of the named areas around the center area, do one of the following:
- If the facet is visible (for example, start or end), insert the desired components into
the facet, grouping multiple components because a facet can take only one child.
- If the facet is not visible, right-click af:panelBorderLayout, select Facets - Panel
Border Layout from the context menu, and choose a facet name from the list. Visible
facets are indicated by a check mark in front of the facet name. Insert the desired
components into the visible facet.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 39
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Describe the purpose of JavaServer Faces
Use JSF components
Explain the use of managed beans
Describe the life cycle of a JSF application
Explain the role of the JSF tag libraries
Describe how JDeveloper supports JSF
Create a JSF-based JSP in JDeveloper
Summary
JSF is a server-side component framework for Web applications that implements the MVC design
pattern.
JSF components have attributes, behaviors, and one or more renderers whose job it is to decide how
the component is displayed. The UI components may also be represented in managed beans, which
are Java objects that are managed in the faces-config.xml file. Managed beans provide a code
point for processing or UI manipulation. You can use Expression Language to bind UI components
and actions to managed beans.
The life cycle for the initial request of a JSF JSP includes creating a server-side tree based on the
components on the page, and then rendering the response. When the user submits a form on the page,
a postback occurs, in which values of UI components are applied to their counterparts in the server-
side tree, validation and conversion logic is executed for each component, the business model is
updated, action events are executed, and then finally the response is rendered, which may include
navigation to another page.
There are two basic tag libraries for defining JSF components: JSF Core for application tasks and JSF
HTML for rendering basic HTML. JDeveloper provides these tags from the Component Palette.
JDeveloper also provides visual editing of the JSF JSP and faces-config.xml file, which
includes the JSF Navigation Diagram.
Oracle Fusion Middleware 11g: Build Java EE Applications 11 - 40
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
This practice covers the following topics:
Creating a Managed Bean to support a page
Creating a basic JSF page
Adding layout components to the JSF page
Copyright 2009, Oracle. All rights reserved.
Planning Navigation and Page Flow
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 2
Copyright 2009, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the
following:
Use a JavaServer Faces (JSF) Navigation diagram to plan
the pages of an application and the navigation between
them
Describe JSF Navigation
Describe the types of JSF Navigation cases
Create a backing bean for a JSF page
Objectives
In this lesson, you learn how to use JSF to control navigational and data flow within an
application. The JSF Navigation diagram provides a way to visually design navigation and flow,
handle interactions with business services, and determine which page to display. Additionally,
JSF components are mapped to managed beans, which control user actions on the components
themselves.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 3
Copyright 2009, Oracle. All rights reserved.
<body>
<form action="myNewPage.html">
<button type="button"/>
</form>
<a href="http://myNewPage.html">
Go To My New Page
</a>
</body>
Traditional Navigation
In traditional navigation, a button or hyperlink is used to
navigate to a specific page.
Traditional Navigation
This type of navigation is also referred to as the Model 1 type. In both cases, if the physical
location of the page is changed, you have to modify all the links and forms that use it.
JSF controls the pages using an XML file that contains all the navigation mechanisms.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 4
Copyright 2009, Oracle. All rights reserved.
What Is JSF Navigation?
JSF Navigation is defined through rules.
Rules use outcomes to determine which page is displayed
in a user interface (UI) event.
Rules can be defined as:
Static
Dynamic
They are defined in faces-config.xml.
What Is JSF Navigation?
JSF Navigation is a set of rules that define navigation from view to view. Generally, you define
one navigation rule per page. Each navigation rule may have several valid outcomes. For
example, a login page may have several outcomes: one for a successful login, and another for a
login failure. Both of these outcomes are defined in the navigation rule.
The rules can be defined as static or dynamic. Static rules are an explicit reference to an
outcome. A dynamic rule is a rule that is bound to a method that may return one of several
possible outcomes.
Navigation rule definitions are stored in the JSF configuration file (faces-config.xml).
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 5
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
myNewPage
firstPage.jsp myNewPage.jsp
success
firstPage
Button
JSF Navigation Rules
JSF Navigation: Example
In JavaServer Faces, navigation between application pages is not hard coded in the file, but is
defined by a set of rules. Navigation rules determine the next page that is to be displayed, when
a user clicks a navigation component, such as a button or a hyperlink.
A navigation rule defines the navigation from one page to one or more other pages.
Each navigation rule can have one or more cases, which define where a user can go from that
page. For example, if a page has links to several other pages in the application, you can create a
single navigation rule for that page and one navigation case for each link to the different pages.
The rule itself can define the navigation from:
A specific JSF page
All pages whose paths match a specified pattern, such as all the pages in one directory,
which is called a pattern-based rule
All pages in an application, which is called a global navigation rule
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 6
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Rules
Navigation rules are stored in faces-config.xml.
Navigation rules can be defined by using:
The faces-config console
The Pageflow diagrammer
The faces-config.xml file directly
JSF Navigation Rules
Navigation rule definitions are stored in the JSF configuration file (faces-config.xml).
You can define the rules directly in the configuration file, or you can use the JSF Navigation
Modeler and the JSF Configuration Editor in JDeveloper. Oracle recommends that you use
Navigation Modeler and Configuration Editor, because these tools:
Provide a GUI environment for modeling and editing the navigation between application
pages
Enable you to map out your application navigation by using a visual diagram of pages and
navigation links
Update the faces-config.xml file for you automatically
Use the navigation modeler to initially create navigation rules from specific pages to one or
more other pages in the application. Use the configuration editor to create global or pattern-
based rules for multiple pages, create default navigation cases, and edit navigation rules.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 7
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Rules
Example:
/login.jsp is the navigation rule with two cases.
login.jsp is managed by the login backing bean.
loginAction() is the method that returns success or
failure:
If the method returns
success, forward the user to
/successPage.jsp.
If the method returns
failure, forward the
user to /failurePage.jsp.
JSF Navigation Rules (continued)
In this example, there is one navigation rule with two cases. The outcome is returned from the
loginAction() method in the login backing bean. The method checks the values of the
username and password. If the combination is valid, the method returns an outcome of
success. If the combination is not valid, the method returns failure. The appropriate
navigation case is then used by JSF to display the correct page. The following is the XML:
<navigation-rule>
<from-view-id>login.jsp</from-view-id>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/successPage.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/failurePage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 8
Copyright 2009, Oracle. All rights reserved.
faces-config Console
faces-config Console
This console provides a visual way to edit all elements of faces-config.xml, as opposed to
a navigation model.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 9
Copyright 2009, Oracle. All rights reserved.
faces-config.xml
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/successPage.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/failurePage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
faces-config.xml
You can use the action to further qualify the result of a particular outcome using a from-action
case. The following code shows how the from-action option is used:
<navigation-rule>
<from-view-id>login.jsp</from-view-id>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/successPage.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{Login.loginAction}
</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/failurePage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 10
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Modeler
You create a JSF Navigation Diagram by dragging elements
from the Component Palette. The faces-config.xml diagram is
automatically updated.
JSF Navigation Modeler
The JSF Navigation Modeler is the tool used for creating a navigation diagram. Notice in the
slide that the Component Palette automatically displays the JSF Navigation Modeler
components. You add components to the diagram by dragging them from the Component Palette
to the diagram.
When you first create a JSF Page Flow and Configuration file (faces-config.xml),
JDeveloper also creates a diagram file (faces.config.oxd_faces) to hold the diagram
details such as layout and annotations. JDeveloper always maintains this diagram file alongside
the faces-config.xml file, which holds all the settings needed by your application.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 11
Copyright 2009, Oracle. All rights reserved.
JSF Navigation Diagram
With the JSF Navigation Diagrammer, you can visually design
your application from a birds eye view.
JSF Navigation Diagram
The JSF Navigation diagram is your workbench for:
Planning out the pages and the navigation between them for your JSF application
Creating new pages for your application
Defining the navigation rules and cases for navigating around the application pages
Including existing pages in your application flow by dragging them
Annotating the diagram with general notes and notes attached to individual elements
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 12
Copyright 2009, Oracle. All rights reserved.
Navigation Elements
<navigation-rule>
<from-view-id>
<navigation-case>
<navigation-rule>
<from-view-id>/Main.jspx</from-view-id>
<navigation-case>
<from-outcome>addProduct</from-outcome>
<to-view-id>/addProduct.jspx</to-view-id>
</navigation-case>
</navigation-rule>
<from-action>
<from-outcome>
<to-view-id>
Navigation Elements
A navigation rule consists of the following elements:
<navigation-rule>: The wrapper element for the navigation cases
<from-view-id>: Contains either the complete page identifier (the context-sensitive
relative path to the page) or a page identifier prefix ending with the asterisk (*) wildcard
character. If you use the wildcard character, the rule applies to all pages that match the
wildcard pattern. To make a global rule that applies to all pages, leave this element blank.
<navigation-case>: The wrapper element for each case in the navigation rule. Each
case defines the different navigation paths from the same page.
<from-action>: An optional element that limits the application of the rule only to
outcomes from the specified action method. The action method is specified as an
Expression Language (EL) binding expressionfor example,
#{backing_addProduct.cancelButton_action}. JDeveloper displays a list of
valid binding expressions for you to choose from.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 13
Navigation Elements (continued)
<from-outcome>: Contains an outcome value that is matched against values specified
in the action attribute of UI components. Later in the lesson, you see how the outcome
value is referenced in a UI component either explicitly or dynamically through an action
method return.
<to-view-id>: Contains the complete page identifier of the page to which the
navigation is routed when the rule is implemented
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 14
Copyright 2009, Oracle. All rights reserved.
Global Rules
Global rules apply to all pages in an application.
Examples: Help page, Home page, Contact page
Define <from-view-id> with an asterisk (*) wildcard.
Define <from-outcome> (help).
Define <to-view-id> (help.jsp).
Any page in the application that returns help displays
help.jsp.
Global Rules
Global rules are navigation rules that can be accessed from any page in the application. JSF does
not force you to define every possible event. If you have common navigation eventsfor
instance, Logoutyou can use wildcards in the <from-view-id> definition to specify that
any page matching this pattern can implement this outcome.
An example of a good use of a global rule is a Help page. Any page in the application can access
the Help page. You define a global rule by setting the <from-view-id> to a wildcard (*).
You can also define a global rule by completely omitting the <from-view-id> tag.
In the following example, any page in the path /faces/ that returns an outcome of help is
forwarded to help.jsp.
...
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>help</from-outcome>
<to-view-id>/menu/help.jsp</to-view-id>
</navigation-case>
...
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 15
Copyright 2009, Oracle. All rights reserved.
Pattern-Based Rules
Pattern-based rules are similar to global rules.
Include a pattern for the <from-view-id> element:
<from-view-id>/staffPages/*
This rule is used by all pages in the /staffPages path.
<navigation-rule>
<from-view-id>/staffPages/*</from-view-id>
<navigation-case>
<from-outcome>help</from-outcome>
<to-view-id>/menu/staffHelp.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Pattern-Based Rules
You can also define rules that apply to a specific set of pages, by including a path and wildcard
in the <from-view-id> tag. The rule includes all the same elements as a global navigation
case. In this example, all the pages in the /staffPages path navigate to staffHelp.jsp
when the outcome from the page is help. This technique is useful where several pages should
navigate to a single common outcome page, such as a Help page. Rather than adding multiple
navigation cases, you add a single global navigation rule to the common page.
<navigation-rule>
<from-view-id>/staffPages/*</from-view-id>
<navigation-case>
<from-outcome>help</from-outcome>
<to-view-id>/menu/staffHelp.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 16
Copyright 2009, Oracle. All rights reserved.
JSF: Example
Sample JSF login application:
JSF: Example
This is an example of a simple JSF page. The page has two input fields and a button. As
discussed in the following slides, the page has an associated managed bean that has access to the
values entered on the page. When the user clicks the Login button, JSF calls the associated
action, which is a method in the bean. This method tests the values and determines whether the
user is valid. If the login values are valid, the user is directed to a success page. Otherwise, the
user is directed to a failure page.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 17
Copyright 2009, Oracle. All rights reserved.
JSF: Example
A simple example of a JSF Login Application:
loginAction
login.jsp
Success
success.jsp
Failure
failure.jsp
JSF: Example (continued)
This is the JSF Case Navigation for this application. The simple case is that the user input values
are valid, so navigation proceeds to the success page. If the values are not valid, navigation is to
the failure page.
If the values that the user entered fail a JSF Validator, the user stays on the login page to change
the values.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 18
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
UI components and value binding to a managed bean:
login.jsp
<h:InputText value="#{Login.userId}"/>
<h:InputSecret value="#{Login.password}"/>
<h:commandButton action="#{Login.login}"/>
Login: A managed bean with the userId and
password fields and the login()method
Submit
JSF Navigation: Example
Both the fields use value binding to associate the values on the page with the managed bean. The
command button has an action associated with Login.login, which is a method in the bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 19
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
A command UI component bound to an action:
login.jsp
<h:commandButton action="#{Login.loginAction}"/>
Login: A managed bean (Login.java) with an action
method called loginAction()
Returns string: failure or success
JSF Navigation: Example (continued)
In the example, a UI component (commandButton) has been bound to a managed bean,
Login.java, which contains the loginAction() method.
At run time, the JSF default implementation reads the navigation rules in the faces-
config.xml file and calls the NavigationHandler class, which evaluates the rules and
determines which page to display.
When evaluating which navigation rules to execute, the navigation handler looks at:
The ID of the current page
The action method used to handle the link. In this case, it is loginAction().
The outcome string value of the action attribute, or the string returned by the action
method. In this example, it is either failure or success.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 20
Copyright 2009, Oracle. All rights reserved.
JSF Navigation: Example
public String loginAction() {
String userId =
(String)this.getUserId().getValue();
String password =
(String)this.getPassword().getValue();
if (userId.equalsIgnoreCase("gary") &
password.equalsIgnoreCase("test")) {
return "success"; }
return "failure";
}
JSF Navigation: Example (continued)
The slide shows the code for the loginAction() method. The method checks the value of
the user ID and password. If they match the defined values, the method returns success;
otherwise it returns failure. JSF then checks for an outcome that matches the return string and
displays the view associated with that outcome.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 21
Copyright 2009, Oracle. All rights reserved.
Using the JSF Configuration Editor
Using the JSF Configuration Editor
You use the Navigation Modeler to initially create navigation rules from specific pages to one or
more other pages in the application. You then use the Configuration Editor to create global or
pattern-based rules for multiple pages, create default navigation cases, and edit navigation rules.
You invoke the editor by clicking the Overview tab at the bottom of the diagram page in the
Visual Editor. If you click the second option, Navigation Rules, in the list on the top left, you
can see rules that have been defined through the diagram. You can also add new rules here.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 22
Copyright 2009, Oracle. All rights reserved.
Managed Beans
Managed beans can:
Store state
Execute a Java routine
Define a handler for event listeners
They have no-argument constructors.
Lazy initialization is performed by JavaServer Faces.
Access scope may be none, request, application, or
session.
Backing beans:
Are special types of managed beans
Contain getter and setter methods for UI components
Managed Beans
If you want to code your own update routine, you can place the code in a managed bean.
Managed beans are objects that are defined in a configuration file (faces-config.xml, by
default). They can be Plain Old Java Objects (POJO), lists, or maps. The classes that can be used
as managed beans have constructors with empty arguments. The managed-bean element in
the faces-config.xml file represents a JavaBean of a particular class, which is
dynamically instantiated at run time (by the default VariableResolver implementation), if
it is referenced as the first element of a value-binding expression, and if no corresponding bean
can be identified in any scope. In addition to the managed bean creation and the optional storing
into the specified scope, the nested managed-property element can be used to initialize the
contents of settable JavaBeans properties of the created instance.
Managed bean configuration in faces-config.xml:
<!ELEMENT managed-bean (description*, display-name*, icon*,
managed-bean name, managed-bean-class, managed-bean-scope,
(managed-property* | map-entries | list-entries))>
A special type of managed bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 23
Managed Beans (continued)
A managed-bean element must contain the following elements:
- managed-bean-name: Specifies the name that is used to refer to the
JavaBean throughout the application
- managed-bean-class: Contains the fully qualified class name for the
JavaBean
- managed-bean-scope: Defines the scope of the JavaBean. Some possible
values are application, session, request, or none.
A managed-bean element can optionally contain any number of descriptions,
display-name, icon, and managed-property/map-entries/list-
entries elements.
If the value of the managed-bean-scope element is something other than none, the
JavaBean created is stored in the corresponding object. For example, if the value is
session, the JavaBean is stored in the session object of a given user.
If you define the bean with a scope of none, the bean is instantiated each time it is
referenced. You can use a scope of none when a managed bean references another managed
bean; if the referenced bean is supposed to be created only when it is referenced, it should be
defined with a scope of none.
Uses of Managed Beans
Managed beans are typically used to:
Store state (for example, information about the authenticated user)
Execute Java routines (for example, by clicking a button)
Define handlers for event listeners
Creating Managed Beans
There are three ways to create managed beans:
You can create Java classes in a project and then configure them as managed beans.
You can create managed beans when binding a Command button.
When you create a new page, you are given the opportunity to automatically expose UI
components in a new managed bean. If you select this option, JDeveloper creates a
managed bean, and accessors are automatically added for all components that you add
to the page. This type of managed bean for the UI components on a page is called a
backing bean.
Backing Beans
Backing beans are a special type of managed beans used to contain getter and setter methods
for UI components.
If you choose to automatically expose UI components in a managed bean when you design a
JSF page, JDeveloper automatically synchronizes the components that you add or modify
with the backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 24
Copyright 2009, Oracle. All rights reserved.
Creating Managed Beans
Entry in faces-config.xml:
<managed-bean>
<managed-bean-name>productBrowsingBean</managed-bean-name>
<managed-bean-class>ui.backing.ProductBrowsingBean
</managed-bean-class>
<managed-bean-scope> session </managed-bean-scope>
</managed-bean>
Creating Managed Beans
You configure managed beans in the faces-config.xml file.
1. Double-click the faces-config.xml file in the Navigator.
2. Click the Overview tab to display the JSF Configuration Editor.
3. In the element list on the left, select Managed Beans.
4. Click the New button on the right to open the Create Managed Bean dialog box.
5. Provide the name and fully qualified class path for the bean. Select a scope, select the
Generate Java File check box, and click OK.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 25
Copyright 2009, Oracle. All rights reserved.
Managed Bean: Example
Definition:
Usage on a page:
Usage in code:
<managed-bean>
<managed-bean-name>userbean</managed-bean-name>
<managed-bean-class>com.oracle.sample.User</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<h:inputText value="#{userbean.name}"/>
Application app =
FacesContext.getCurrentInstance().getApplication();
ValueBinding bind = app.createValueBinding("#{userbean}");
User user = (User)bind.getValue(ctx);
Managed Bean
The definition of a bean is simple. You provide the following information:
An alias (userbean in the example)
The class to instantiate (com.oracle.sample.User in the example)
The lifespan (request in this example)
Then the usage of that managed bean is through Expression Language (EL).
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 26
Copyright 2009, Oracle. All rights reserved.
Setting Managed Bean Scope
Each managed bean has a scope:
Application
Session
Request
None
Setting Managed Bean Scope
Application: The bean is available for the duration of the Web application. This is helpful for
global beans such as Lightweight Directory Access Protocol (LDAP) directories.
Session: The bean is available to the client throughout the clients session.
Request: The bean is available from the time it is instantiated until a response is sent back to the
client. This is usually the life of the current page.
None: The bean is instantiated each time it is referenced. This is helpful if the bean is referenced
within another bean.
Managed properties are any properties of the bean that you would like populated with a value
when the bean is instantiated. The set() method for each declared property is run after the
bean is constructed. When you configure a managed property for a managed bean, you declare
the property name, its class type, and its default value. If the default is null, you use a <null-
value> element. The value can also be another bean referenced in a JSF EL expression. When
the parent bean is initialized, the nested bean declared in the value is also created and initialized.
When nesting a bean, you must ensure that it exists in the faces-config.xml file and that
the scopes are compatible.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 27
Copyright 2009, Oracle. All rights reserved.
Relationships Between Managed Beans
Managed beans can access other beans:
Yes Yes Yes Yes request
No Yes Yes Yes session
No No Yes Yes application
No No No Yes none
request session application none
Access beans in scope Beans in
scope
Relationships Between Managed Beans
The table in the slide shows which scopes of managed beans can access other managed beans
with the same or a different scope. Note that request is the only scope that can access
managed beans of any scope.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 28
Copyright 2009, Oracle. All rights reserved.
Managed Properties
Managed bean variables that are exposed through getter
and setter methods
Configured in faces-config.xml
Possible values:
Null
Literal string
Lists and maps
Value binding expression (EL)
<!ELEMENT managed-property (description*, display-
name*, icon*, property-name, property-class?,
(map-entries|null-value|value|list-entries))>
Managed Properties
Managed properties are bean variables that are exposed through setter and getter methods for
write and read access. All variables not explicitly set as managed properties retain the default
values upon bean instantiation.
The managed-property element, nested within the <managed-bean> element,
represents an individual property of a managed bean. A managed property calls the equivalent
setter method of the bean on bean initialization.
Managed properties must have a name and a value. The optional property class does not need to
be mentioned for simple types because JSF can figure it out. The optional description, display
name, and icon attributes are for tools to display the property and have no meaning for the JSF
application at run time.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 29
Copyright 2009, Oracle. All rights reserved.
Managed Properties: Examples
Literal string:
EL accessing a managed bean:
<managed-bean>
<managed-property>
<property-name>label</property-name>
<value>Hello World</value>
</managed-property>
<managed-bean>
<managed-property>
<property-name>label</property-name>
<value>#{UserInfo['firstname']}</value>
</managed-property>
Managed Properties: Examples
Expression Language (EL) can be used within the faces-config.xml file to initialize the
value of a managed property. EL can reference any object that is in the scope, including
previously defined managed beans.
Managed beans and managed bean properties can also be initialized as lists or maps, provided
that the bean or property type is a List or Map, or implements java.util.Map or
java.util.List.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 30
Copyright 2009, Oracle. All rights reserved.
Managed Properties: Examples
Populating a list:
Use <map-entries> to specify managed properties that are
of the Map type.
<managed-bean>
<managed-property>
<property-name>bookmarks</property-name>
<list-entries>
<value>http://otn.oracle.com/products/jev</value>
<value>http://otn.oracle.com/products/ias</value>
</list-entries>
</managed-property>
<h:outputText value="#{Login.userId.value}"
binding="#{SuccessPage.outputText1}"
id="outputText1"
/>
successPage.jsp:
Using the Managed Bean on the JSF Page
After a managed bean is defined with the relevant properties and methods, you use JSF EL
expressions (such as <h:outputText value="#{Login.userId.value}" in the
slide) to bind a UI component attribute to the appropriate property (or method) in the bean. In
addition to value and method binding, you can also bind the UI components instance to a bean
property by using the binding attribute.
In the example above, successPage.jsp includes an outputText field with the ID of
outputText1. It retrieves its value from the Login managed bean property userId. It is also
bound to the outputText1 property of the SuccessPage backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 32
Copyright 2009, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Use a JSF Navigation Diagram to plan the pages of an
application and the navigation between them
Describe JSF Navigation
Define types of JSF Navigation cases
Create a backing bean for a JSF page
Summary
JSF Navigation is a set of rules that define how users navigate from one view to another. The
rules use outcomes that may be static or dynamic. Navigation rules may be global to the
application as a whole, or may apply to a specific set of pages. You can use the JSF Navigation
Diagrammer to visually plan the pages of an application and to define the navigation paths
between them. This diagram is a Visual Editor for the faces-config.xml file for pages and
navigation rules.
Managed beans are also defined in faces-config.xml and can be configured in the JSF
Configuration Editor. Backing beans are a special type of managed beans to interact with the UI
components and the model. You can create a managed bean automatically when you create a
page. You can create managed beans by associating class files with a named managed bean in
the JSF Configuration Editor. Because managed beans can have scope, you can use them to store
information for the duration of the request, application, or session.
Oracle Fusion Middleware 11g: Build Java EE Applications 12 - 33
Copyright 2009, Oracle. All rights reserved.
Practice: Overview
These practices covers the following topics:
Using a JSF Navigation Diagram to model page flow in an
application
Creating the JSF pages of the application
Binding components to a managed bean