OAS Tutorial For JavaEE Developers
OAS Tutorial For JavaEE Developers
September 2006
Oracle Application Server 10g Release 3: Tutorial for Java EE Developers (10.1.3.1.0)
Primary Authors: Pam Gamer, Dan Hynes, Raghu Kodali , Dana Singleterry
Contributors: Alfred Franci, Jonas Jacobi, Lynn Munsinger, Frank Nimphius, Chris Schalk
The Programs (which include both the software and documentation) contain proprietary information; they
are provided under a license agreement containing restrictions on use and disclosure and are also protected
by copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly,
or decompilation of the Programs, except to the extent required to obtain interoperability with other
independently created software or as specified by law, is prohibited.
The information contained in this document is subject to change without notice. If you find any problems in
the documentation, please report them to us in writing. This document is not warranted to be error-free.
Except as may be expressly permitted in your license agreement for these Programs, no part of these
Programs may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose.
If the Programs are delivered to the United States Government or anyone licensing or using the Programs on
behalf of the United States Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data
delivered to U.S. Government customers are "commercial computer software" or "commercial technical data"
pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As
such, use, duplication, disclosure, modification, and adaptation of the Programs, including documentation
and technical data, shall be subject to the licensing restrictions set forth in the applicable Oracle license
agreement, and, to the extent applicable, the additional rights set forth in FAR 52.227-19, Commercial
Computer Software--Restricted Rights (June 1987). Oracle Corporation, 500 Oracle Parkway, Redwood City,
CA 94065
The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently
dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup,
redundancy and other measures to ensure the safe use of such applications if the Programs are used for such
purposes, and we disclaim liability for any damages caused by such use of the Programs.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks
of their respective owners.
The Programs may provide links to Web sites and access to content, products, and services from third
parties. Oracle is not responsible for the availability of, or any content provided on, third-party Web sites.
You bear all risks associated with the use of such content. If you choose to purchase any products or services
from a third party, the relationship is directly between you and the third party. Oracle is not responsible for:
(a) the quality of third-party products or services; or (b) fulfilling any of the terms of the agreement with the
third party, including delivery of products or services and warranty obligations related to purchased
products or services. Oracle is not responsible for any loss or damage of any sort that you may incur from
dealing with any third party.
Preface
This preface outlines the contents and audience for the Oracle Application Server 10g R3: Tutorial
for Java EE Developers (10.1.3.1.0). The preface contains the following sections:
Intended Audience
Structure
Related Documents
Preface i
Intended Audience
Intended Audience
This tutorial is for Java EE developers who use Oracle JDeveloper and Enterprise JavaBeans
(EJBs) to build Web applications.
Structure
The tutorial consists of the following chapters:
Chapter 1: “Getting Started”
This chapter describes the Service Request scenario and installation of the schema.
This chapter describes how to build the pages to edit a service request. There is one page for
customers and a different page for staff (technicians and managers.)
Related Documents
For more information about building applications EJB 3.0, see EJB 3.0 Resources at
http://www.oracle.com/technology/tech/java/ejb30.html.
For information about building applications with Oracle ADF, see the following publications:
Oracle Application Development Framework Developer's Guide 10g Release 3 (10.1.3)
Oracle Application Development Framework Developer's Guide for Forms/4GL Developers 10g
Release 3 (10.1.3)
Preface iii
1
Getting Started
This tutorial describes how to design and build a Java EE customer relationship management application
that tracks customer service requests. The application has Web-based user interfaces and is deployed to
Oracle Application Server 10g. Data components are EJB3.0 objects.
This chapter contains the following topics:
ServiceCompany Overview
Using This Tutorial
Setting Up Your Environment
Summary
ServiceCompany Overview
ServiceCompany is a large appliance-servicing company that provides service support for household
appliances (dishwashers, washing machines, microwaves, and so on). The company supports a wide variety
of appliances and tries to solve most customer issues by providing answers to questions via service
requests. ServiceCompany has found that customers can eventually resolve most issues when they have the
correct information. This approach has proven to save time and money for both the company and its
customers.
A service request generally has the following flow:
1. A customer issues a request.
2. The company assigns the request to a service technician.
3. The service technician answers the request or asks the customer for more information.
4. The customer checks the request and either closes it or provides further information.
Business Problem
Currently this process is initiated by telephone and requires the services of a clerical staff to log and follow
up on service requests. As volume has increased, assignments to service technicians are sometimes delayed
until clerks can perform data entry of the service requests. It is difficult for managers to keep track of the
work that technicians do to ensure efficient performance. These factors have resulted in declining customer
satisfaction and increasing costs per request for the company.
ServiceCompany wants to implement a self-service application so that customers can log and track their
own requests, and so that managers can better monitor the work of technicians.
Goal
ServiceCompany has the following goals:
A customer interface that customers can use to add, update, and check the status of their
service requests
A business interface with which the company can create, update, and manage customer
service requests, which includes adding service information and assigning requests to the
appropriate service technician.
Various reporting tools to ensure timely resolution of service requests
Business Solution
ServiceCompany decides to use Oracle JDeveloper to create a Java EE customer relationship management
application. The technical aspects of the application include the following:
The user interfaces are Web-based to enable deployment of the application both externally to
customers and internally to employees.
The technology scope is Java EE compliant.
The application server is Oracle Application Server 10g. ServiceCompany uses the Oracle
Application Server platform to enable service-oriented architecture (SOA) in its enterprise, so
the application can be deployed there.
The data components are EJB3.0 objects. Enterprise JavaBeans (EJB) 3.0 provides the
business service layer of the application. An Enterprise JavaBean is a reusable, portable Java
EE component. The EJB 3.0 specification makes it easier than ever to develop Enterprise
JavaBeans, and JDeveloper enables wizard-driven creation of EJBs.
1-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
ServiceCompany Overview
Functions
The following functionality is required in the application:
Customer log-in validation
Service request creation
Service request maintenance
Service history maintenance (with the ability to hide internal notes from customers)
The following functions are not part of this tutorial but could be done as an optional exercise:
History of service request assignments: As an optional exercise, you could populate a
history row with each change of assignment.
History of service request status: As an optional exercise, you could populate a history row
with each change of status.
Pages
The application consists of the following pages:
Login page: Each user is a customer, service technician, or manager.
Service Request Insert page: Both customers and staff can use this page to create new
service requests (SRs).
Service Request List page (customer-facing): This is the page that customers use to view
existing SRs. This page shows all of the SRs that the customer has created and the status of
each. Customers can click an existing SR and be directed to an edit page where they can add
information to the request (Service Request page).
Service Request Edit page (customer-facing): This is the page that customers use to create
or update SRs. The history may include sensitive information that the company does not want
customers to see. These entries can be flagged as “internal only” and will be excluded from
customers’ view.
Triage page (company-facing): This page is used by management to display all SRs.
Management can assign or reassign SRs from this page. The page is dynamic to show all
requests, unassigned requests, or any other status.
Service Request List page (company-facing): This page displays all of the SRs assigned to
the logged-on service technician and the status of each request. The technician can click an
existing SR and be directed to a page to add information to the request (Service Request Edit
page).
Service Request Edit page (company-facing): This page is where the service technician
updates the SR with resolution information. The page will show the original request along
with the full SR history (master-detail).
The following graphic provides an overview of the page flow for the application:
1-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
ServiceCompany Overview
Schema
The initial schema has been designed to provide the needs of the business model. The schema consists of
five tables and three database sequences, diagrammed as follows:
Tables
USERS: This table stores all the users who interact with the system, including customers,
technicians, and managers. The e-mail address, first and last name, street address, city, state,
postal code, and country of each user are stored. An ID uniquely identifies a user.
SERVICE_REQUESTS: This table represents both internal and external requests for activity on a
specific product. In all cases, the requests are for a solution to a problem with a product. When an
SR is created, the name of the individual who opened it, the product it is for, and the date of the
request are all recorded, along with a short description of the problem. When the SR is assigned to
a technician, the name of the technician and date of assignment are also recorded. An artificial ID
uniquely identifies each SR.
SERVICE_HISTORIES: There may be many events recorded for each SR. The date the request
was created, the name of the individual who created it, and specific notes about the event are all
recorded. Any internal communications related to an SR are also tracked. The SR ID and the
service history sequence number uniquely identify each service history record.
PRODUCTS: This table stores all of the products handled by the company. For each product, the
name and description are recorded. If an image of the product is available, that too is stored. An
artificial ID uniquely identifies each product.
EXPERTISE_AREAS: To better assign technicians to SRs, each technician’s specific areas of
expertise are defined.
Sequences
USERS_SEQ: Populates the ID for new users
PRODUCTS_SEQ: Populates the ID for each product
SERVICE_REQUESTS_SEQ: Populates the ID for each new SR
1-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Setting Up Your Environment
To create the schema owner and schema, perform the following steps:
1. Navigate to the directory where you unzipped the SRSetups.zip file.
2. Invoke SQL*Plus from that directory and log on as SYS or another DBA-level user. You may
need to ask your DBA to run the scripts for you.
3. In the SQL*Plus window start the build.sql script:
SQLPLUS>start build.sql
The build.sql script calls the createSchema.sql script to create the SRDEMO user, and then it logs
on to the SRDEMO account. After connection, the script automatically calls the
createSchemaObjects.sql script to create all the tables, constraints, and database sequences. When
this operation is complete, the populateSchemaTables.sql script is called to insert sample data into
the tables.
When control returns to the build.sql script, a list displays the created objects and any potential invalid
objects. Running these scripts should take less than 30 seconds. You may rerun the build.sql script to
drop and re-create the SRDEMO owner and objects.
Note: If you have not already installed JDeveloper 10g Release 3, do so before
proceeding to the next tutorial steps.
1. In Windows Explorer, navigate to the directory where JDeveloper is installed and find the
jeveloper.exe file. Create a shortcut to it on the desktop by right-clicking the
jdeveloper.exe file and choosing Send To > Desktop from the context menu.
2. Double-click the Shortcut to JDeveloper icon on the desktop to invoke JDeveloper. If this is the
first time you are running JDeveloper, a “Do you wish to migrate?” window appears. Click No to
continue.
3. On startup, a “Tip of the Day” window is displayed. These tips are things you can do to make
development more productive. Click Close when you’ve finished looking at the tips.
Note: In this tutorial the database connection is named srdemo. The name of
the connection does not affect the ability to complete the tutorial. However, we
strongly recommend using the naming conventions described in all the steps. In
doing so, it is easier to follow along with the names used in the steps.
Field Value
Username srdemo
Password oracle
Deploy Password Select the check box.
6. On the Connection page, enter the following values. Then click Next.
Field Value
Host Name Type the name (or IP address) of the computer where the
database is located. If the database is on the same machine as
JDeveloper, the default value of localhost is fine.
JDBC Port Enter the port used for access to the database. The default value is
1521. If you do not know this value, check with your DBA.
SID Enter the SID used to connect to the database. The default value
is ORCL. If you do not know this value, check with your DBA.
7. Click Test Connection. If the database is available and the connection details are correct, you
can continue. Otherwise, click the Back button and check the values.
8. Click Finish. The connection now appears below the Database node in the Connection
Navigator.
9. Examine the schema from JDeveloper. In the Connection Navigator, expand Database >
SRDemo. Browse the database elements for the schema and confirm that they match the
following schema definition:
1-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Setting Up Your Environment
1. To create an application, click in the Applications Navigator, right-click the Application node,
and select New Application from the context menu.
2. In the Create Application dialog box, enter the following values. When finished, click OK.
Field Value
Application SRDEMO
Name
Directory D:\JDeveloper\jdev\mywork\SRDEMO
name Leave this field at its default value. If you used the recommended
directory structure, your path should match this one.
Application org.srdemo
Package Prefix This value becomes the prefix for all package names. You can
override it later if necessary.
Application Web Application [JSF, EJB]
Template In this tutorial, you access technologies related to Java
ServerFaces and Enterprise JavaBeans. New templates can be
created and added to restrict the technologies that are available
during development.
The application is created with two default projects: Model and ViewController.
3. The ViewController project has a dependency on the model because it needs to have access to
resources that are defined in the model. However, the model doesn’t need components coming
from the view side, so no dependency is required for the Model project.
To set the dependency, right-click the ViewController project and select Project Properties from
the context menu.
4. Select Dependencies from the tree at the left. In the Project Dependencies list at the right of the
dialog, select the check box next to Model.jpr, and then click OK.
Setting this dependency also determines the order in which projects are built. The view needs
certain classes that are contained in the model. Setting this dependency thus ensures that the model
is compiled before the view.
1-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
Summary
This chapter introduced you to ServiceCompany and its plan to implement a Web-based customer
relationship management application that meets the following requirements:
Customers can log and update their own service requests.
Technicians can keep track of and update service requests that are assigned to them.
Managers can query and assign service requests.
In this chapter, you carried out all of the prerequisite steps that you need to complete before starting to
build the application. You performed the following key tasks:
Downloaded the tutorial schema setup files
Created the SRDEMO schema owner and installed the ServiceCompany schema
Downloaded and installed JDeveloper
Created a JDeveloper database connection
Defined an application and projects for the tutorial
What Is EJB?
The Enterprise JavaBeans (EJB) architecture is suitable for the development and deployment of
component-based business applications. Applications written using the EJB architecture are scalable,
transactional, and multiuser secure.
An Enterprise JavaBean (EJB) is a server-side component that encapsulates business logic. The EJB
specification defines a server-side component model and programming interfaces for application servers.
Servers and containers built under this specification take care of the low-level application programming,
such as transaction management, security, and persistence. Because much of the difficult application
programming is taken care of by the server, the developer is free to work on the business logic of the
application.
Types of EJBs
An EJB can be an entity, a session bean, or a message-driven bean. With EJB 3.0, you no longer need to
implement the EntityBean, SessionBean, or MessageDrivenBean interfaces. Instead, you can
use annotations to define Java classes as one of the following types of EJBs:
An entity represents a business object that exists in the database.
A session bean performs a distinct, decoupled task such as checking credit history for a customer.
Session beans are classified based on the maintenance of the conversation state:
o Stateless session beans do not have an internal state and therefore do not keep track of
the information that is passed from one method to another. They are used for business
methods that are independent of previous invocations, such as calculating shipping
charges. After the shipping charge is calculated and returned to the calling method, there
is no need for the session bean to store its state for future invocations.
o Stateful session beans, in contrast, maintain conversational state across invocations and
thus can be used for applications such as online shopping carts.
A message-driven bean is used to receive asynchronous JMS messages.
2-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Reviewing the Objects That Have Been Created
Add All to shuttle all the tables from the Available list to the Selected list, and then click
Next.
6. On the Entities from Tables page of the wizard, enter org.srdemo.persistence as the
Package Name. The classes that you create in this package are responsible for persisting
application data.
In the Collection type for Relationship Fields drop down list, select java.util.List. Leave other
values at their defaults and click Next.
7. The Specify Entity Details page of the wizard enables you to change the names of the entities and
classes that map to each of the database tables that you selected. Accept the default mappings by
clicking Next.
8. Click Finish on the Summary page of the wizard to create the entities. This may take a few
moments. When done, a message appears in the log window to let you know that generation is
complete.
name of the package that you specified in the wizard, as in the following illustration:
What makes these objects different from other Java files are the annotations that identify them as EJB
entities and perform object-relational mapping to database tables. These metadata annotations specify to the
container how these entities should be managed.
You can open and examine the files to see the annotations by performing the following steps:
1. In the Applications Navigator, expand the Model project, and then also expand Application
Sources and the package org.srdemo.persistence. You are able to see all the objects that have
been created.
2. Double-click ServiceHistories.java to open it in the editor window.
3. You can see the following annotations in the file (you may need to scroll down to see some of
them):
Annotation Description
@Entity Identifies the file as an EJB 3.0 entity
@NamedQuery A query that can be used at run time to retrieve data
@Table Specifies the primary table for the entity
@IdClass Specifies the class for the composite primary key
@Id Can define which property is the identifier for the
entity
@Column Specifies a mapped column for a persistent property
or field
@ManyToOne Specifies a type of foreign key relationship between
tables
@JoinColumn Specifies the join column and referenced column for a
foreign key relationship
2-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Defining Named Queries
Notice that the first named query does not use parameters, while the second passes a parameter
(string preceded by a colon) to the WHERE clause of the query. These annotations are shown in the
following example:
bean instance may be detached and may be updated by a client locally and then sent back to the
EntityManager to be merged and synchronized with the database.
Cascading is used to propagate persistence operations to related entities. The default behavior is no
cascading.
There are four cascade types:
PERSIST cascades the persist (create) operation to associated entities.
MERGE cascades the merge operation to associated entities.
REMOVE cascades the remove operation to associated entities.
REFRESH cascades the refresh operation to associated entities.
These cascade types can be used alone or in combination with one another. An additional option, ALL, can
be used to signify a combination of all four cascade types.
Because the ServiceRequests entity has the associated entity ServiceHistories, you want to be sure that the
detail Service Histories records are persisted whenever the create operation is called on the master service
request. To do so, perform the following steps:
1. Open ServiceRequests.java in the editor window, or switch to it if it is already open by clicking
its tab.
2. Scroll to the @OneToMany annotation that establishes a relationship with the ServiceHistories
entity and add cascade={CascadeType.PERSIST} to the beginning of its attribute list
(enclosed in parentheses as shown below). Be sure to include the comma separator.
When prompted, press [Alt]+[Enter] to import javax.persistence.CascadeType.
2-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Setting Default Values
Now you have set the sequence generator for the SVR_ID column to use the sequence that has
been defined in the database, which is SERVICE_REQUESTS_SEQ.
{
for (ServiceHistories svh:histList)
{
//The collection may have empty nodes so
// we just skip those
final Long testLineNo = svh.getLineNo();
if (testLineNo != null){
if (testLineNo > maxLineNo) {
maxLineNo = testLineNo;
}
}
}
}
}
return ++maxLineNo;
}
11. Call that method when setting the line number. Modify the setLineNo() method by changing
the line this.lineNo = lineNo; to the following:
this.lineNo = (lineNo==null )?getNextLineItem():lineNo;
2. Now scroll to the mapping for the CREATED_BY column. If the attribute that is mapped to that
column is named users1, then change its name to users, as shown in the following screenshot:
3. Click Rebuild to compile the project. The Messages tab of the log window should show
successful compilation.
Summary
You have now built a persistent model that uses EJB 3.0 entities. You performed the following key tasks:
2-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
Used the Create CMP Entity Beans from Tables wizard to create EJB 3.0 entities for all tables in
the SRDEMO schema
Examined the resulting POJOs to see the annotations that identify them as entities and perform
object-relational mapping to database tables
Used annotations to add named queries, cascade types, and an ID-generation strategy
Defaulted null date fields to the current date and null line numbers to the next line item
Ensured that attributes are mapped to match the code in the remainder of this tutorial
This chapter of the tutorial describes how to develop session facade beans and interfaces.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh02.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Creating a Data Model Session Facade
Modifying the Query Method to Return a Single Record
Adding a Method to Return Related Records
Summary
3. If the Welcome page of the Create Session Bean wizard appears, read the information and then
click Next.
3-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating a Data Model Session Facade
4. On the EJB Name and Options page of the wizard, enter ServiceRequestFacade as the EJB
Name.
Ensure that Session type is Stateless and Transaction Type is Container. By specifying Container
as the Transaction Type, you enable the container to manage transactions so that you do not have
to code transaction mechanisms. You should change this only if you want to write your own
transaction mechanisms.
Ensure that the check box next to Generate Session Facade Methods is selected.
Leave the other values on this page at their defaults. Then click Next.
5. On the Select EJB 3.0 Entity Methods page of the wizard, clear all check boxes except the one
next to <Core Facade Methods>. These are core CRUD methods to support transactions.
Expand Users and select the check box next to findUserByEmail, as shown. Then click Next.
Note: If you do not see the findUserByEmail named query, then cancel the Create Session Bean
wizard, click Rebuild , and invoke the wizard again.
6. On the Class Definitions page of the wizard, change the Bean Class to
org.srdemo.business.ServiceRequestFacadeBean (as shown in the screenshot),
and then click Next.
7. On the EJB Component Interfaces page, ensure that both Implement a Remote Interface and
Implement a Local Interface are selected (as shown in the following screenshot) and then click
Next.
You implement the remote interface so that you will be able to use a command line test client. The
local interface is needed for clients that run in the same Java Virtual Machine (JVM), such as
JSPs.
8. On the Summary page, click Finish. The org.srdemo.business package is created.
3-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating a Data Model Session Facade
10. Compile the project by selecting the Model node in the Applications Navigator and clicking
Rebuild . The Messages Log window should display a message that compilation was
successful, as shown in the following screenshot:
4. In the editor, scroll to the end of the file and make changes in the following lines:
3-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding a Method to Return Related Records
Field Value
Name findSRbyUser
4. In the editor, locate the method that you just added and change the line:
return null;
to
return findUserByEmail(email).getServiceRequestsList();
Summary
You have now developed session facade beans and interfaces. You performed the following key tasks:
Used the Create Session Bean wizard to create an EJB 3.0 session bean, along with remote and
local interfaces
Modified the session bean’s call to a named query to return a single Users object rather than a list
of users
Added a method to the session bean to return a list of related service requests that were created by
the specified user
3-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
4
Deploying and Testing the Data Model
This chapter of the tutorial describes how to start OC4J and deploy the session bean that you created in the
preceding chapter. It also shows you how to test the data model by creating and running a sample client that
inserts records into the database.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh03.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Starting OC4J and Deploying the Application
Adding a Named Query
Creating a Sample Client
Testing the Data Model
Summary
2. Be sure that the log window displays no errors and that OC4J is successfully initialized, as shown
in the following screenshot. (If you have previously run the session bean, OC4J is reinitialized, so
you do not receive the message about it being initialized.)
4-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding a Named Query
4-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding a Named Query
6. Now that you have added a named query to the entity, you must modify the session bean. First you
must compile Products.java so that the added named query is available to the session bean.
Click Make .
7. In the Applications Navigator, right-click ServiceRequestFacadeBean.java and select Edit
Session Facade from the context menu.
8. In the Session Façade Options dialog box, expand Products. Select the findProductById method
and click OK. JDeveloper generates code in the session façade bean and interfaces to access the
new named query.
9. In the Structure window, right-click the findProductById method and select Properties from the
context menu. When you set properties on the method, the bean and its local and remote interfaces
pick up the changes and remain synchronized.
10. In the Bean Method Details dialog box, change the Return Type to
org.srdemo.persistence.Products and the Parameters to Long prodId, and then
click OK.
11. In the editor, scroll to the end of the file and change the following line:
return
em.createNamedQuery("findProductById").setParameter("prodId",
prodId).getResultList();
4-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating a Sample Client
create a new ServiceRequest object and set its Status, RequestDate, Products,
ProblemDescription, and Users properties.
In the main() method, locate the following line:
ServiceRequestFacade serviceRequestFacade =
(ServiceRequestFacade)context.lookup("ServiceRequestFacade");
After this line, add the following code:
System.out.println("Creating a service request");
ServiceRequests sr = new ServiceRequests();
System.out.println("setting the status");
sr.setStatus("Open");
8. Now that you have created an instance of the ServiceHistories object, you can set the
serviceHistoriesCollection property of the ServiceRequests object, first creating
a collection to use to set this property. Add the following code just below the code that you
previously added:
System.out.println("adding history to collection");
List<ServiceHistories> historyList = new
ArrayList<ServiceHistories>();
historyList.add(historyNotes);
System.out.println("setting the history list in the " +
" ServiceRequest object");
sr.setServiceHistoriesList(historyList);
9. Press [Alt]+[Enter] to import:
java.util.List
java.util.ArrayList
10. Call a method from the facade to create the service request in the database. Because of the
CascadeType (PERSIST) that you set on the ServiceRequest entity in a previous chapter
of this tutorial, the persist() operation is cascaded to the associated ServiceHistories
entity. Add the following code just below the code that you previously added:
System.out.println("calling the persistEntity() facade " +
"method");
serviceRequestFacade.persistEntity(sr);
System.out.println("check the db now");
4-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
2. Check the database to see that records were inserted. Click the Connections Navigator tab to
view the Connections Navigator.
3. In the Connections Navigator, expand Database, SRDemo, SRDEMO, and Tables.
4. Double-click the SERVICE_REQUESTS table to open it in the editor.
5. In the editor, click the Data tab. You should see the record that has been added, as shown in the
following screenshot (the record may not be the last one in the list).
Note that SVR_ID was generated by a database sequence, as you specified in the
ServiceRequest entity bean.
6. In a similar fashion, examine the database records for the SERVICE_HISTORIES table. You
should see the new record that was inserted, as shown in the following screenshot (again, it may
not be last in the list):
Summary
You have now deployed and tested the application. You performed the following key tasks:
Ran the session bean, which automatically started the embedded OC4J server
Created a sample EJB Java client and modified it to insert data into the database
Tested the data model by running the sample client and checking the database to see that records
were inserted
4-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
5
Planning the User Interface
In this chapter of the tutorial, you plan the user interface for the application.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh04.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Planning Pages
Specifying Navigation Rules
Planning a Standard Look and Feel
Summary
Overview
Now that the data model has been implemented, you can begin to develop the user interface for the
application. So far you have been working in the Model project; now you begin to work on the other
project that you set up initially.
You can use a JSF Navigation (page flow) Diagram to plan the pages that the application should have and
the navigation rules that define how users navigate between pages. When you add the JSF technology scope
to your project, JDeveloper creates an empty navigation diagram, faces-config.xml, for you.
Although you can create pages without using this diagram, it is helpful to plan the pages and navigation
right from the start. You can design the entire application and then add pages as needed.
In this section of the tutorial, you create the pages for the application and then you specify navigation rules
between the pages.
Note: If you already have existing pages, you can add them to the diagram by dragging them from the
Applications Navigator.
5-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Planning the Pages
2. To assist in laying out the pages in the diagram, you can display grid lines. Right-click in the
diagram and select Visual Properties from the context menu. Select the Show Grid check
box and click OK.
3. In the Component Palette, click JSF Page:
4. Click in the diagram where you want the page to appear. An icon representing a page appears
on the diagram with the title /untitled1.jsp, as shown below. Notice that the icon has a yellow
warning attached to it because you have not yet defined the page but merely created it on the
diagram. In this chapter, you create the pages that you define in later chapters. After you
define the page, the yellow warning disappears.
5. Click the icon label and change its name to /app/SRWelcome.jsp (the leading forward
slash and the .jsp extension are parts of the name; if you omit them, JDeveloper
automatically adds them). This is the first page that all users see when they invoke the
application.
6. Add the following additional JSP pages, arranged as shown in the screenshot:
/app/SRCreate.jsp
/app/SRList.jsp
/app/SREdit.jsp
These are pages that can be accessed by all users of the application (customers, managers, and
technicians).
7. Add the following page that only managers can access (arranged as shown in the screenshot):
/app/management/SRTriage.jsp
8. Add the page that can be accessed by all employees (managers and technicians), arranged as
shown in the following screenshot:
/app/staff/SRTEdit.jsp
5-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Specifying Navigation Rules
3. Modify the label by clicking it and typing newSR over the default label. Alternatively, you
can change the label by modifying the From Outcome property in the Property Inspector.
Note that JDeveloper adds a preceding hyphen and space automatically on the diagram.
4. Now that you have created a navigation case, examine the XML code that has been generated.
Click the Overview tab at the bottom of the editor, and then click Navigation Rules in the list
at the left of the window. The rule that you just created in the diagram is listed in the
Navigation Rules box, and the navigation case is listed in the Navigation Cases box, as shown
5. Click the Source tab to see the XML code for the selected rule.
The <from-view-id> tag identifies the source page, and the <to-view-id> tag
identifies the destination page. The wavy lines under the page names remind you that the
pages have not yet been fully defined.
6. You can also see the navigation rule in the Structure window, located in the lower left of the
JDeveloper window below the Applications Navigator, as shown in the following screenshot.
Click the Source tab.
Note: If you do not see the Structure window, select View > Structure from the menu.
5-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Specifying Navigation Rules
7. Repeat the steps to create more navigation cases on your diagram. The following table shows
how users can navigate between pages. For example, a user can click a link on the
SRWelcome page to navigate to the SRList page.
To make a bend in the line on the diagram, click the intermediate point where you want the
line to bend before clicking the destination page. To bend an existing line, shift-click the line
where you want it to bend and drag the bend to the desired position.
Note: For the label, you can simply type the word and JDeveloper adds a preceding hyphen
and space automatically.
8. Click Save All to save your work. The diagram should be similar to the following
screenshot.
5-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
Applying the JDeveloper style sheet changes the page to look like this:
To achieve a uniform look and feel, you instruct developers to use standard heading styles and apply the
JDeveloper style sheet to all pages. You apply the style sheet when you create the actual pages in later
chapters of this tutorial.
Summary
To plan the user interface for the application, you performed the following key tasks:
Created pages in a JSF Navigation Diagram
Defined navigation rules that specify how pages in the JSF Navigation Diagram are linked
Planned to use the JDeveloper style sheet to apply a standard look and feel to pages
Before creating pages, you decide to address how users log in to the application (authentication) and how
they are allowed to access certain functionality (authorization). In this chapter, you define the security and
login logic for the application.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh05.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Defining Security for the Application
Creating Classes to Manage Roles
Summary
A realm is the general component of security. It is a security domain that represents a security
policy and a specific set of users. You can use the same realm for many different applications.
Within a realm, applications participate in browser-based single sign-on, so that being
authenticated in one application in a realm means that you do not have to be authenticated again in
another application in the same realm, as long as you do not close the browser between requests.
If there is already a jazn.com realm under the Realms node, do not create a new one. Instead,
proceed to step 6.
6-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Defining Security for the Application
5. If there is no jazn.com realm under the Realms node, select the Realms node and click New. In
the Create Realm dialog box, enter the name jazn.com and click OK, as shown in the following
screenshot. The default realm in jazn-data.xml is jazn.com, but you can create your own
default realm if desired.
6. Under the jazn.com node, select the Users node in the tree and click Add.
7. Add each of the following users, entering welcome for the Credentials of each:
ghimuro
nkochhar
bernst
daustin
sking
These are not all of the users in the database, but they are enough to test the application. For
production, you must add all users who should have access to the application. In reality, you
would use OID or LDAP providers for production systems that have more than just a few users.
8. Select the Roles node in the tree (under the jazn.com node) and click Add.
9. In the Create Role dialog box, enter user and click OK.
Select the following users in the Available list and click Add to move them to the Selected
list to grant the user role to them:
ghimuro
nkochhar
12. In a similar fashion, grant the manager role to sking. Grant the technician role to bernst
and daustin.
13. Click OK to dismiss the Embedded OC4J Server Preferences dialog box.
6-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Defining Security for the Application
14. All of the data that you entered is kept in a file at the root directory of the application. The
convention used to name the file is <applicationName>-jazn-data.xml. In this tutorial, the
file is named SRDEMO-jazn-data.xml. If desired, you can open this file in Wordpad to see the
XML that you declaratively created. Passwords in the files are encrypted.
6. Select each of the other two navigation cases in turn (those with assign and srlist From Outcomes)
and set the Redirect property to true for each.
7. Select each of the other navigation rules from the upper list and set the Redirect property for each
of its navigation cases to true.
6-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Defining Security for the Application
4. Select the Security Roles node in the tree at the left, and then click Add.
5. In the Create Security Role dialog box, enter user as the Security Role Name. Then click OK.
6. In a similar fashion, add the other two roles: technician and manager.
Note: For authorization to be successful, you must use the same role names as the role names that
you used when configuring the realm in OC4J preferences. If you choose different names, you
need to define mappings in the orion-web.xml file to map the Java EE security role that you
define in web.xml to the role name in OC4J.
7. Now that you have defined the security roles, they need to be assigned to security constraints to
enforce the authorization. Select the Security Constraints node and click New.
8. On the Web Resources tab, click Add and specify ALL Manager as the Web Resource Name.
Click OK.
9. With the ALL Manager collection selected, click the Add button in the lower section of the
window, to the right side of the URL Patterns tab. In the Create URL Pattern dialog box, enter
faces/app/management/* and click OK.
10. With the ALL Manager collection selected, click the Authorization tab and select the manager
check box.
11. Create two more security constraints by again selecting Security Constraints in the tree at the left
and then clicking New. Use the values in the following table:
12. There should be three constraint entries under the Security Constraints node. Click OK to dismiss
the Web Application Deployment Descriptor dialog box.
13. In the Applications Navigator, double-click web.xml to open it in the editor. Notice that there is a
Component Palette at the right of the editor. The Component Palette enables you to declaratively
edit the web.xml file in the editor as an alternative to editing it from its Properties window. You
can see that all of the entries after the <jsp-config/> line show the security constraints, login
configuration, and security roles that you specified.
6-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
14. With the web.xml file open in the editor, the Structure window also shows all of the elements that
you specified.
Expression Value
#{UserInfo.userName} Returns the login ID or the string Not Authenticated
#{UserInfo.userRole} Returns a string with the current user’s role (for example, manager)
#{UserInfo.staff} Returns true if the user has the technician or manager role
You also create another utility class, ServiceLocator.java, which is used to get a handle to session
facade. The locator also caches instances of the facade so that it doesn’t have to look up the bean again.
Using the service locator class implements a core Java EE design pattern.
To create a set of utility classes to validate users and determine available roles, perform the following steps:
1. In the Applications Navigator, right-click the ViewController project and select New from the
context menu.
2. In the New Gallery, select the Java Class item from the General category and click OK.
3. In the Create Java Class dialog box, set the Name of the class to UserInfo and the Package to
org.srdemo.view.util. Click OK.
6-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating Classes to Manage Roles
4. In a similar fashion, create in the same package an additional class named ServiceLocator.
5. From your \setup directory (see the section “Setting Up Your Environment” in Chapter 1 for
instructions on creating a \setup directory) open the ServiceLocatorJava.txt file from
the \files subdirectory. Copy all the text in this file and then replace the code in the
ServiceLocator.java class with the copied text. You can then close
ServiceLocatorJava.txt.
6. In a similar fashion, replace the code in the UserInfo.java class with the code that is
contained in \setup\files\UserInfoJava.txt.
4. In the Create Managed Bean dialog box, set the property values to those in the following table:
Field Value
Name UserInfo
Class org.srdemo.view.util.UserInfo
Scope session
5. Click OK.
6. Click the Source tab. Near the end of the file, you can see the managed bean that you just defined.
6-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
You have now added users and a bean to access user information so that the pages can run and be
populated with data. In the next chapter, you create the pages that enable a user to log in and access the
functionality designated for that user’s role.
Summary
In this chapter, you provided security for the SRDemo application. To accomplish this, you performed the
following key tasks:
Configured container security by defining users and roles
Enforced container-managed security by setting JSF navigation to use HTTP redirect
Set up application access by defining the pages that each role can access
Created a class to manage roles
Created classes that enable you to access information about users and roles from the application
In the preceding chapter, you defined how users log in to the application (authentication) and are allowed to
access certain functionality (authorization). You specified this login logic at the application level.
Now you create pages that implement the login logic. You also create a page to conditionally display links
enabling users to navigate to the pages that they are authorized to use.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh06.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Creating the Index Page
Creating the Error Page
Login Page Overview
Creating the Login Page
Specifying Where to Save Application State
Welcome Page Overview
Creating the Welcome Page
Adding Navigation and Display Logic
Testing the Login, Navigation, and Display Logic
Summary
7-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Error Page
This scriptlet ensures that when the index page is invoked, the user is redirected to the
SRWelcome page.
8. Now you need to set index.jsp as the entry point of the application. In the Applications
Navigator, right-click web.xml (ViewController > Web Content > WEB-INF > web.xml) and
select Properties from the context menu.
9. In the tree at the left side of the page, select Welcome File Lists and click New.
10. On the right portion of the page, click Add.
11. In the Create Welcome File dialog box, enter index.jsp and click OK.
12. Click OK to dismiss the Web Application Deployment Descriptor window (for web.xml).
To the existing directory name, add \infrastructure and then click Next.
5. On the Error Page Options page of the wizard, select the option Create This File as an Error
Page, and then click Finish.
6. The Errors.jsp file opens in the visual editor. Locate the following text:
An error occured:
Change it to:
A login error occurred
7. From the Block Format drop-down list at the top-left portion of the editor, select Heading 2.
8. In the Component Palette, select CSS from the drop-down list and then click JDeveloper. Your
page should now look like the following screenshot:
7-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Login Page Overview
1. Each page that is displayed to users contains a title, which is different for each page.
2. The Login page contains an HTML table to arrange the input and output components in a tabular
format.
3. The left cells of the table contain output text components with static values to serve as labels for the
cells in the right columns.
4. The top right cell of the table contains an HTM text input component for entering the user name.
5. The bottom right cell of the table contains an HTL password input component for entering a password.
6. The action that is specified for the Sign On button authenticates the user, displaying an error page if
unsuccessful. If the login is successful, the first page of the application displays.
5. On the Error Page Options page of the wizard, select the option Use an Error Page to Handle
Uncaught Exceptions in This File, and then click Next.
6. On the Use Error Page page of the wizard, select Errors.jsp and click Finish.
7. The Login.jsp file opens in the visual editor. Enter the text Login to SRDEMO.
8. From the Block Format drop-down list in the top-left portion of the editor, select Heading 1.
9. In the Component Palette, select CSS from the drop-down list and then click JDeveloper.
10. Place your cursor on the line under the heading. From the Component Palette drop-down list,
select HTML Forms.
11. From the component list, click Form.
12. In the Insert Form dialog box, enter an Action of j_security_check and select post from the
Method drop-down list, as shown in the following screenshot. Then click OK.
13. In the Component Palette, select HTML Common from the drop-down list. Select the Table
component and drag it to the form that you created previously, as shown here:
7-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Login Page
14. In the Insert Table dialog box, set both Rows and Columns to 2. Set Width to 250 and select the
pixels option, and then click OK.
15. Enter the field labels Username and Password in the left column of the table.
16. Place the cursor in the upper-right cell of the table. Hold down the [Shift] key and click in the
lower-right cell of the table. In the Property Inspector, set the Width property for the column to
150. The page should look similar to the following screenshot:
17. Switch back to forms components by selecting HTML Forms from the Component Palette drop-
down list.
18. Select the Text Field component and drag it to the top-right cell of the table. In the Insert Text
Field dialog box, enter the Name j_username as shown and click OK.
19. Select the Password Field component and drag it to the bottom-right cell of the table. In the Insert
Password Field dialog box, enter the Name j_password and click OK.
20. Place your cursor to the right of the table and press [Enter] to create a blank line within the form,
and then click the Submit Button component.
21. In the Insert Submit Button dialog box, enter the Name logon and the value Sign On. Then
click OK.
22. Click the Source tab and examine the code. You can see that you have defined the elements that
are necessary for form-based authentication as described at the beginning of this section, as shown
in the following screenshot:
7-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Welcome Page Overview
1. Each application page contains a title, information about the logged in user, and a Logout link:
The title is different for each page.
Information about the logged in user is derived from the UserInfo managed bean by
using Expression Language.
The Logout link logs out the user and returns to the Login page by executing a method from
the Logout managed bean.
2. The View Your Service Requests link navigates to the SRList page to display service requests that
were either created by or assigned to the logged in user. This link is visible to all users.
3. The Create a New Service Request link navigates to the SRCreate page, where users can create a
new service request. This link is visible to all users.
4. The Triage Service Requests link navigates to the SRTriage page, where managers assign service
requests to technicians. This link is visible only if the logged-in user has the role of manager.
To display the links conditionally based on the role of the logged-in user, you add code to the backing bean
for the page to set the Rendered property of the link. You also specify an action for each link that
corresponds to a From outcome in a navigation rule that you defined earlier.
7-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Welcome Page
6. The new page opens in the editor. Enter the text Welcome to Service Request Demo and
then select Heading 1 from the Block Format drop-down list.
7. On the next line, enter the text This demo uses Enterprise JavaBeans (EJB) 3.0 and
JavaServer Faces (JSF). Ensure that the Block Format is set to None. Press [Enter] twice
to skip a line.
8. Enter the text You are logged in as, and press [Space]. From the Block Format drop-down
list, select Heading 5.
9. From the Component Palette drop-down list, select JSF HTML and then click Output Text.
10. An output text field is created in the editor. In the Property Inspector for the output text, select the
the right arrow to add it to the expression on the right. Then click OK.
This causes the application to display the name of the authenticated user at run time. If you
examine the Value property, you can see that it uses Expression Language to obtain the name of
the user from the UserInfo managed bean that you defined in the previous chapter.
12. Place the cursor on the next line in the editor and select Messages from the Component Palette.
This provides a placeholder for run-time messages to be displayed.
13. Select CSS from the Component Palette drop-down list and then select JDeveloper. Your page
should now look similar to the following screenshot (instead of “Not Authenticated” you may see
“#{UserInfo.userName}”):
7-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Navigation and Display Logic
4. The SRLogout.java file is created and opened in the editor. Switch to it by clicking its tab, and
then add the following method to log out the current user and redisplay the SRWelcome page, as
shown here:
public String logoutButton_action() throws IOException {
ExternalContext ectx =
FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response =
(HttpServletResponse)ectx.getResponse();
HttpSession session = (HttpSession)ectx.getSession(false);
session.invalidate();
response.sendRedirect("SRWelcome.jsp");
return null;
}
As you add the method, you are prompted several times to add import statements. Press
[Alt]+[Enter] to import each one when prompted.
5. Add a component to the SRWelcome page to call this code. Switch to that page in the editor by
clicking its tab.
Position your cursor on the blank line above the “You are logged in as” text. In the Component
Palette, select JSF HTML from the drop-down list and click Command Hyperlink. In the Insert
Command Hyperlink dialog box, enter the Value Logout and click OK.
6. In the Property Inspector for the command hyperlink, enter the Action #{} and press [Enter], and
then click back into the Action property. Click the ellipsis at the end of the field.
7. In the Action dialog box, ensure that the Method Binding option is selected. Select Logout from
the Managed bean drop-down list, and then select logoutButton_action from the Method drop-
down list, as shown. Click OK.
7-14 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Navigation and Display Logic
the manager role because only managers are allowed to triage (assign) service requests.
You first add actions to all of the links that correspond to the From outcomes that you defined when setting
up navigation rules in the JSF Navigation Diagram (see Chapter 5), as shown in the following screenshot.
To implement the link that displays conditionally, you add the conditional logic to the SRWelcome
managed bean and then call that code from the link that you place on the SRWelcome page.
8. Add the following code that obtains the role of the current user:
7-16 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Navigation and Display Logic
public SRWelcome() {
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
ValueBinding curUser =
app.createValueBinding("#{UserInfo.userRole}");
Object obj = curUser.getValue(ctx);
roleString = obj.toString();
}
11. Change the method (as shown below) to conditionally display the viewSR output text.
Note: Although all of these conditions produce the same result of rendering the output text for all
roles (the default behavior), this provides a structure for easily changing to conditional logic later
if needed.
public void setViewSR(HtmlOutputText viewSR) {
if (roleString.equals("user")) {
viewSR.setRendered(true);
}
else if (roleString.equals("technician")) {
viewSR.setRendered(true);
}
else {
viewSR.setRendered(true);
}
this.viewSR = viewSR;
}
12. In the SRWelcome.jsp page in the editor, select the command hyperlink that you just created (be
sure that h:commandLink is highlighted in the Structure window). In the Property Inspector,
select srlist from the Action drop-down list.
This is the name of the From outcome for the navigation rule that you created previously on the
JSF Navigation Diagram, thus ensuring that when the link is clicked at run time, navigation
proceeds to the SRList page.
7-18 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Navigation and Display Logic
2. In the Insert Command Hyperlink dialog box, enter the Value Create a New Service
Request and click OK.
3. In the Property Inspector, change the ID of the output text component to srCreate (be sure that
h:outputText is selected in the Structure window).
6. Change the method as shown below to conditionally display the srCreate output text
Note: Although all of these conditions produce the same result of rendering the output text for all
roles (the default behavior), this provides a structure for easily changing to conditional logic if
needed later.
public void setSrCreate(HtmlOutputText srCreate) {
if (roleString.equals("user")) {
srCreate.setRendered(true);
}
else if (roleString.equals("technician")) {
srCreate.setRendered(true);
}
else {
srCreate.setRendered(true);
}
this.srCreate = srCreate;
}
7. In the SRWelcome.jsp page in the editor, select the command hyperlink that you just created (be
sure that h:commandLink is highlighted in the Structure window). In the Property Inspector,
select newSR from the Action drop-down list.
This is the name of the From outcome for the navigation rule that you created previously on the
JSF Navigation Diagram, thus ensuring that when the link is clicked at run time, navigation
proceeds to the SRCreate page.
7-20 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Login, Navigation, and Display Logic
4. Open or switch to SRWelcome.java in the editor. (ViewController > Application Sources >
org.srdemo.view > backing > SRWelcome.java)
5. In the Structure window, double-click the setSrTriage() method to find it in the editor.
6. Change the method to the following code to conditionally display the srTriage output text
(note that the Rendered property is set to true only for those users whose role is manager):
public void setSrTriage(HtmlOutputText srTriage) {
if (roleString.equals("manager")) {
srTriage.setRendered(true);
}
else if (roleString.equals("user")) {
srTriage.setRendered(false);
}
else if (roleString.equals("technician")) {
srTriage.setRendered(false);
}
else {
srTriage.setRendered(false);
}
this.srTriage = srTriage;
}
7. In the SRWelcome.jsp page in the editor, select the command hyperlink that you just created (be
sure that h:commandLink is highlighted in the Structure window) and, in the Property Inspector,
select assign from the Action drop-down list.
This is the name of the From outcome for the navigation rule that you created previously on the
JSF Navigation Diagram, thus ensuring that when the link is clicked at run time, navigation
proceeds to the SRTriage page.
4. The Errors page displays a message that a login error occurred. Click the browser’s Back button.
5. Now enter the following (for a customer) and click Sign On:
Username Password
ghimuro welcome
6. The SRWelcome page appears in the browser displaying the user’s name and only the two links
that customers (user role) are allowed to access. Click Logout.
7-22 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Login, Navigation, and Display Logic
7. The Logon page is once again invoked. Enter login information for a technician:
Username Password
bernst welcome
8. The SRWelcome page appears in the browser displaying the user’s name and the two links that
technicians are allowed to access, which are the same as the links that display for customers. Click
Logout.
9. The Logon page is once again invoked. Enter login information for a manager:
Username Password
sking welcome
10. The SRWelcome page appears in the browser displaying the user’s name and all links, because a
manager has access to all of the pages.
11. Now that you have access to all of the links, click each of them in turn to test the navigation.
Remember that you have not yet created the pages, so you should receive a 404 Not Found error
when attempting to navigate, but you can see from the error message which page is being invoked.
Click the browser’s Back button to return to the welcome page.
12. Close the browser when you are finished testing.
Summary
In this chapter, you created the pages that provide the entry point of the application, implementing login
logic and conditional authorization based on roles. To accomplish this, you performed the following key
tasks:
Created an index page that redirects users to the welcome page
Created an error page to be displayed when the login is incorrect
Created a login page where users can log in to the application with one of the user
ID/password combinations that you defined in the previous chapter
Specified that application state should be saved on the client
Created a welcome page that displays the name of the current user along with a link
enabling users to log out and links to other pages in the application
Added logic to the welcome page to display links conditionally based on roles and to use
the navigation rules that you set up previously
Tested the security and logon logic and the display and navigation logic.
7-24 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
8
Developing a Page to List Records
In the preceding chapter, you implemented the login, display, and navigation logic. You now create the
page that lists a user’s service requests. There is one page in this application for all users: SRList.jsp.
A user accesses the list page from the welcome page by clicking a link. This accesses the data pertaining to
the user’s service requests and displays it on the list page.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh07.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
List Page Overview
Creating the List Page for Users
Adding a Named Query
Exposing the New Named Query
Updating the Backing Bean to Retrieve the Data
Displaying Data
Passing Data Between Pages
Specifying the Location of the Session Facade
Testing the Update Logic and the UI Components
Summary
1. Each application page contains a title, information about the logged in user, and a Logout link:
The title is different for each page.
Information about the logged in user is derived from the UserInfo managed bean by using
Expression Language.
The Logout link logs out the user and returns to the Login page by executing a method from the
Logout managed bean.
2. The list of service requests is a JSF data table component to display service requests that were either
created by or assigned to the logged in user. The data table is bound to a new attribute that you create
in the page’s backing bean. The accessor method for this attribute calls a named query, which you add
to the ServiceRequests entity, to retrieve the list of service requests.
3. In addition to listing the requests, SRList enables users to drill into a particular service request, passing
data to the page where they can edit their service request. The Svr Id column of the data table is a JSF
command link component that executes one of two navigation cases that you defined earlier. You add
code to the backing bean to determine if the logged in user is a customer or an employee (manager or
technician). If the user is a customer, navigation to the edit page for customers (SREdit) occurs.
Otherwise, navigation proceeds to the SRTEdit page for employees. In either case, the code passes the
current row of data to the appropriate edit page.
4. The Back to Home link executes a navigation rule that returns the user to the SRWelcome page.
In this and subsequent pages in this application, you expose UI components in a managed bean. Managed
8-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the List Page for Users
beans that handle the data exchange between the business model and the UI component are called backing
beans. JavaServer Faces uses its own EL value binding to associate a UI component to a property on the
backing bean. A backing bean can have a connection to the data model to retrieve and store data, thus
handling the interaction between the View and the Model. Code in the backing bean is automatically
synchronized with design changes to the UI components.
In a production application, you would probably not want to expose all UI components in a backing bean,
because this generates a lot of extra code that may not be used. Instead, you could create the backing bean,
add attributes to it, and wire attributes to UI components only as needed.
To define the SRList page, perform the following steps:
1. Open faces-config.xml in the editor if it is not already open, or click its tab at the top of the editor
if it is open. (To open the file, right-click the ViewController project and select Open JSF
Navigation from the context menu.) Click the Diagram tab.
2. Double-click the /app/SRList.jsp icon to invoke the Create JSF JSP wizard.
3. If the Welcome page of the wizard appears, click Next.
4. On the JSP File page of the wizard, click Next.
5. On the Component Binding page of the wizard, select the option Automatically Expose UI
Components in a New Managed Bean. Change the Name of the managed bean to SRList and
the Package to org.srdemo.view.backing. Click Finish.
6. The new page opens in the editor. Enter the text My Service Requests and then select
Heading 1 from the Block Format drop-down list.
7. On the next line, enter the text You are logged in as and then press [Space]. From the Block
Format drop-down list, select Heading 5.
8. In the Component Palette, select JSF HTML from the drop-down list and then click the
Output Text component.
9. An output text field is created in the editor. In the Property Inspector for the output text, select the
10. In the Value dialog box, expand JSF Managed Beans and UserInfo. Select userName and click
the right arrow to add it to the expression on the right. Click OK. This causes the
application to display the name of the authenticated user at run time.
11. In the visual editor, place the cursor on the next line. Then click the Command Hyperlink
component in the Component Palette.
12. In the Insert Command Hyperlink dialog box, enter the Value Logout and click OK as shown.
13. In the Property Inspector for the command hyperlink, enter an Action of #{} and press [Enter],
and then click back into the Action property. Click the ellipsis at the end of the field.
14. In the Action dialog box, ensure that the Method Binding option is selected. Select Logout from
the Managed bean drop-down list, and select logoutButton_action from the Method drop-down
list. Click OK.
This ensures that the Logout link executes the code in the Logout managed bean that you created
in a previous chapter.
15. Now you add a link to return the user to the welcome page. Press [Enter] three times to insert
three blank lines after the Logout link. From the Component Palette drop-down list, select JSF
HTML and then click the Command Hyperlink component to create it on the page.
16. In the Insert Command Hyperlink dialog box, enter the Value Back to Home and click OK.
8-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding a Named Query
17. Check the Structure window to be sure that the h:commandLink component is selected. In the
Action attribute within the Property Inspector for the command link, select welcome from the
drop-down list.
18. Select CSS from the Component Palette drop-down list and then click JDeveloper. Your page
should now look similar to the following screenshot:
The ServiceRequestFacadeBean.java file opens in the editor. Scroll to the end of the
file to see the new method that was added to expose the new named query. In the method
findServiceRequests(), locate the following line:
8-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Updating the Backing Bean to Retrieve the Data
return
em.createNamedQuery("findServiceRequests").setParameter("user",
user).setParameter("user1", user1).getResultList();
Replace this line with the following four lines (be sure to retain the opening and closing curly
brackets):
Query query = (Query)em.createNamedQuery("findServiceRequests");
query.setParameter("user",user);
query.setParameter("user1",user1);
return query.getResultList();
The data for this variable is retrieved from the session facade, and its accessors can be used by
components in the page.
6. In the Generate Accessors dialog box, select the check box next to the requestList variable that
you just added, and then click OK.
You can scroll to the bottom of the file to see the accessors that were created. In the
getRequestList() method, locate the following line:
return requestList;
Replace this line with the following lines:
// Get the Service Locator's instance
ServiceLocator serviceLocator = null;
try {
serviceLocator = serviceLocator.getInstance();
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)serviceLocator.
getFacadeService("java:comp/env/ejb/ServiceRequestFacade");
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
ValueBinding curUser =
app.createValueBinding("#{UserInfo.currentUser}");
8-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Displaying Data
The // TODO comment in the code creates a task that is listed in the Tasks window that you can
display by selecting View Tasks Window. You can add to code a line that begins with //
TODO when you need to complete a task later (such as, in this case, adding an exception handler
for the naming exception). Any text that you enter after the comment appears as a description in
the Tasks window. In this tutorial, you do not actually go back and add the exception handler. But
in a real development situation, this would serve as a reminder to do so.
7. Press [Alt]+[Enter] when prompted to add several import statements (for Application,
choose to import javax.faces.application.Application).
Displaying Data
Now that you have added the named query and the backing bean code, you can add data components to the
JSP to utilize this code to retrieve the applicable data. To add components to display this read-only data,
perform the following steps:
1. In the Applications Navigator, expand ViewController, Web Content, and app.
2. Double-click SRList.jsp to open it in the editor and then click the Design tab.
3. From the Component Palette drop-down list, select JSF HTML and then drag the Data Table
component to the line just above the Back to Home link on the page in the visual editor.
4. If the Welcome page of the Create Data Table wizard appears, click Next.
5. Select Bind the Data Table Now in the Binding window of the wizard, and then click Next.
6. In the Bind Data Table page of the wizard, click Bind.
7. In the Expression Builder window, expand SRList, select requestList, and click the right arrow
to add it to the Expression. Then click OK.
8. Continuing in the Bind Data Table page of the wizard, enter the following values and then click
Next:
Field Value
Class org.srdemo.persistence.ServiceRequests
Var sr
8-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Displaying Data
9. On the Header and Row Data page of the wizard, select the table column with the header value
Service Histories List and click Remove.
10. In a similar fashion, remove the table columns with the header values Users, Users1, and
Assigned Date.
11. By using the buttons at the right of the window, arrange the remaining table columns in the
following order:
Svr Id
Status
Request Date
Products
Problem Description
12. Change the Component Value for the Products row to #{sr.products.name}, and then click
Finish.
if (roleString.equals("user")) {
ValueBinding binding =
ctx.getApplication().createValueBinding("#{SREdit.serviceRequest}");
binding.setValue(ctx,editSR);
return "update";
}
else {
8-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Passing Data Between Pages
ValueBinding binding =
ctx.getApplication().createValueBinding("#{SRTEdit.serviceRequest}");
binding.setValue(ctx,editSR);
return "techupdate";
}
}
The value bindings that are created by this method are used in the next chapter when you define
the SREdit and SRTEdit pages. Also note that the method returns either update or
techupdate, depending on whether or not the user has the user role. These strings correspond
to navigation cases that you defined in the JSF Navigation Diagram to navigate to the SREdit and
SRTEdit pages, respectively.
4. Return to the SRList.jsp by clicking the tab for the page (or opening it as previously described).
Click the Design tab for the page.
5. Change the svrId field to a link that passes the selected row to another page for editing. To
accomplish this, either in the visual editor or the Structure window, right-click the output text
component #{sr.svrId} and select Surround With… from the context menu.
6. In the Surround With dialog box, select Command Hyperlink and click OK.
7. In the Insert Command Hyperlink dialog box, leave the Value blank and click OK.
8. In the Structure window, remove the extra outputText component that was created (in front of the
#{sr.svrId} output text) by selecting it and pressing [Delete].
9. In the Structure window, select the h:commandLink that you just created. In the Property
Inspector select the Action attribute and then select editLinkAction() from the drop-down list.
8-14 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Update Logic and the UI Components
4. In the Create EJB Local Reference dialog box, enter the following values:
Field Value
ejb/ServiceRequestFacade
Name
org.srdemo.business.ServiceRequestFacadeLocal
Local Interface
Click OK and then click OK again to dismiss the Web Application Deployment Descriptor
window.
Username Password
sking welcome
5. The SRList page displays all service requests that were created by or assigned to the user.
Note that “Svr Id” is a link. This passes the selected object to either the SREdit.jsp page or the
SRTEdit.jsp page to be defined in the next chapter. At this point, you’ve defined the method to
pass the Service Request object. If you click the link now, you receive an error indicating that the
page does not yet exist. You can click the Back to Home link to return to the Welcome page.
Summary
In this chapter, you created the page that enables users to view their service requests. To accomplish this,
you performed the following key tasks:
Created the list page that contains components that:
8-16 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
You have created the page that lists a user’s service requests. Now you create pages that enable the user to
edit service requests. There are two such pages in this application: SREdit for customers and SRTEdit for
technicians and managers.
Users access the edit pages from the list page by clicking a link that passes the data pertaining to the
selected service request to the edit page. When you created the SRList page, you defined the logic for
passing that data, along with the logic to determine which edit page to display based on roles.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh08.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Edit Page Overview
Creating the Edit Page for Customers
Adding Components to Display Data
Adding Data Entry Components
Persisting or Canceling an Update
Displaying Detail Records
Conditionally Hiding Records
Developing the Edit Page for Staff
Testing the Update Logic and the UI Components
Summary
9-1
Edit Page Overview
1. Each application page contains a title, information about the logged in user, and a Logout link.
2. An HTML table is used to lay out the JSF components.
3. Labels are plain text that is entered into the left column of the HTML table.
4. Output text components display four of the Service Request fields. You bind these fields to the
data by adding a ServiceRequests object to the page’s backing bean and then accessing the
9-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Edit Page for Customers
data by using Expression Language. Users cannot edit data that is displayed in output text
components.
5. A JSF Listbox component displays hard-coded values for the status of the service request. You use
Expression Language to bind this component to the status attribute of the backing bean’s
ServiceRequests object. The user can select a new status to update the request.
6. A JSF Input Textarea component enables the user to enter multiple lines of text. You define
backing bean code to take the value in the input text area and assign it to the notes attribute of an
associated ServiceHistories entity.
7. A Save button calls code that you add to the backing bean to persist the data to the underlying
database tables. The bean is set to session scope so that the data is available for all pages in the
session. This code in the bean returns a string value that corresponds to one of the From outcomes
in a navigation rule that you defined earlier.
8. A Cancel button has an action set to one of the From outcomes in a navigation rule that you
defined earlier. This enables navigation to occur without executing the code to persist the data.
9. Associated service history records are displayed in a JSF Data Table that is bound to the list of
service histories associated with the backing bean’s ServiceRequests object.
6. The new page opens in the editor. Enter the text Update Service Request and then select
Heading 1 from the Block Format drop-down list.
7. From the Component Palette, select JSF HTML from the drop-down list and drag the Messages
component to the next line on the page in the visual editor.
8. Place the cursor after the Messages component and press [Enter], and then click the Command
Hyperlink component in the Component Palette.
9. In the Insert Command Hyperlink dialog box, enter the Value Logout and click OK:
9-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Edit Page for Customers
10. In the Property Inspector for the command hyperlink, enter #{} in the Action property and press
[Enter]. Then click back into the Action property. Click the ellipsis at the end of the field.
11. In the Action dialog box, ensure that the Method Binding option is selected. Select Logout from
the Managed bean drop-down list, and select logoutButton_action from the Method drop-down
list. Click OK.
This ensures that the Logout link executes the code in the Logout managed bean that you created
in a previous chapter.
12. In the Structure window, select the paragraph node that contains the commandLink that
you just defined.
13. In the Property Inspector, set the Align property of the paragraph to right by selecting that value
from the drop-down list.
14. In the editor, on the next line enter the text You are logged in as, and then press [Space].
From the Block Format drop-down list, select Heading 5.
15. In the Component Palette, click the Output Text component.
16. An output text field is created in the editor. In the Property Inspector for the output text, select the
the right arrow to add it to the expression on the right. Click OK. This causes the application
to display the name of the authenticated user at run time.
18. Select HTML Common from the Component Palette drop-down list and then drag the Table
component to the next line in the editor to create a table on the page.
19. In the Insert Table dialog box, set the number of rows to 6, the number of columns to 2, and the
width to 100 with the percent option selected. Then click OK.
20. In the left column, enter the following phrases in each of the rows:
SR ID
Request Date
Description
Product
Status
Notes
21. Select CSS from the Component Palette drop-down list and then select JDeveloper. Your page
should now look similar to the following screenshot:
9-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Displaying Data
Displaying Data
The SREdit page has some fields that are not editable; they only display data. To add output text
components to display this read-only data, perform the following steps:
1. Add a new attribute to the backing bean for the service request. In the Applications Navigator,
expand ViewController, Application Sources, org.srdemo.view, and backing.
2. Double-click SREdit.java to open it in the editor.
3. Add the following attribute:
ServiceRequests serviceRequest;
7. Now that you have added code to the backing bean to access service request data, you can add
databound components to the SREdit page. Switch to SREdit.jsp by clicking its tab in the editor.
Select JSF HTML from the Component Palette drop-down list and drag the Output Text
component to the top-right cell of the table in the visual editor.
8. In the Property Palette, select the Value property and then click Bind to Data .
9. In the Value dialog box, expand JSF Managed Beans, SREdit, and serviceRequest. Select svrId
and click the right arrow to add it to the Expression. Then click OK.
9-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Displaying Data
10. In a similar fashion, add the following to the next three cells beneath the svrId cell:
11. Click Save All to save your work. Your page should now look like the following screenshot:
9-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Data Entry Components
This associates this list item’s value with the status of the serviceRequest variable in the
SREdit managed bean.
7. Click OK to dismiss the Insert Listbox dialog box.
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)
serviceLocator.getFacadeService
("java:comp/env/ejb/ServiceRequestFacade");
srLocal.mergeEntity(serviceRequest);
return "saved";
} catch (NamingException e) {
// TODO
9-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Persisting or Canceling the Update
e.printStackTrace();
}
return "saved";
}
Note that this method returns the string saved, which is the name of the navigation case (pointing
from this page to the SRList page) that you defined earlier in the JSF Navigation Diagram.
3. Press [Alt]+[Enter] when prompted to import:
javax.faces.context.FacesContext
javax.faces.application.Application
javax.faces.el.ValueBinding
org.srdemo.persistence.Users
org.srdemo.persistence.ServiceHistories
org.srdemo.view.util.ServiceLocator
org.srdemo.business.ServiceRequestFacadeLocal
javax.naming.NamingException
4. Switch to SREdit.jsp in the editor. Place the cursor after the table and press [Enter] to create a
blank line.
5. In the Component Palette, select JSF HTML from the drop-down list and click Command Button.
6. In the Property Palette, set the Value property to Save.
7. Double-click the Save button in the editor, and in the Bind Action Property dialog box, select
updateSR from the Method drop-down list. Click OK.
Note: The updateSR() method in the SREdit managed bean returns the string saved, which is
the name of the navigation case that you defined in the faces-config.xml file to navigate to
the SRList page.
8. In the editor for SREdit.jsp, drag the Command Button component from the Component Palette to
the right of the Save button on the page.
9. In the Property Palette, set the Value property to Cancel and set the Action property to saved so
that the user navigates to the SRList page, but without executing the update code in the backing
bean.
10. Now you change the scope of the managed bean to session so that changes can be seen on other
pages of the application. Open (right-click ViewController and select Open JSF Navigation) or
switch to the faces-config.xml file in the editor.
11. Click the Overview tab, select SREdit, and click Edit.
12. In the managed-bean Properties dialog box, select session from the Scope drop-down list and click
OK.
13. Classes for bean with session scope must implement the Serializable interface if they are
part of a distributable Web application. Open or switch to SREdit.java and locate the following
line:
public class SREdit {
Change it to:
public class SREdit implements Serializable{
Press [Alt]+[Enter] when prompted to import java.io.Serializable.
9-14 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Displaying Detail Records
2. Place the cursor at the end of the horizontal line under the Request History heading and press
[Enter] to create a new line.
3. In the Component Palette, select JSF HTML from the drop-down list, and then drag Data Table
to the blank line that you just created to place a data table on the page.
4. If the Welcome page of the Create Data Table Wizard appears, click Next.
5. On the Binding page of the wizard, select the option Bind the Data Table Now and click Next.
6. On the Bind Data Table page of the wizard, click Bind next to the Value field.
7. In the Expression Builder window, select All Types from the Filter By drop-down list.
8. In the tree at the left, expand JSF Managed Beans, SREdit, and serviceRequest.
9. Select serviceHistoriesList and click the right arrow to shuttle it to the Expression field, and
then click OK.
10. On the Bind Data Table page of the wizard, change the Class to
org.srdemo.persistence.ServiceHistories. In the Var field, enter history, and
then click Next.
11. On the Header and Row Data page of the wizard, you specify the columns of the data table. You
need only three columns in the data table: Users, Notes, and Svh Date. Remove all of the other
columns by selecting each in turn and clicking Remove. Change the Header Value Users to
Submitted By, and change Svh Date to Date. Change the Component Value Submitted
By to #{history.users.firstName}. By using the buttons at the right of the window,
rearrange the data in the following order, and then click Finish:
9-16 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Conditionally Hiding Records
1. Perform all steps as in “Creating the Edit Page for Customers,” except that you double-click
/app/staff/SRTEdit (rather than /app/SREdit) in the JSF Navigation Diagram and you create
seven rows in the table (rather than six). The last row should still be labeled Notes, but label the
sixth row Hidden. The page should look similar to the following screenshot:
2. Follow all steps as in “Displaying Data,” except that you edit SRTEdit.java and SRTEdit.jsp
(rather than SREdit.java and SREdit.jsp), and all references are to SRTEdit (rather than SREdit).
When you are finished with this section, the page should look similar to the following screenshot:
9-18 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Developing the Edit Page for Staff
3. Perform all steps in “Adding Data Entry Components,” except that you edit SRTEdit.jsp (rather
than SREdit.jsp), and all references are to SRTEdit (rather than SREdit). When you are finished
with this section, the page should look similar to the following screenshot:
4. Add the check box to indicate that comments should be hidden from customers. Drag the
Checkbox component from the Component Palette to the right cell of the row labeled Hidden.
5. Now add code to the backing bean for the page to hold the value of the check box. Open or switch
to SRTEdit.java in the code editor (ViewController > Application Sources > org.srdemo.view
> backing).
6. Add the following private variable: private boolean hideComments = false;
7. Right-click in the editor and select Generate Accessors from the context menu.
8. In the Generate Accessors dialog box, select the check box next to hideComments and then click
OK.
9. Switch to SRTEdit.jsp in the editor and select the check box component that you just created. In
the Property Palette, click the Value field and then click Bind to Data .
10. In the Value dialog box, expand JSF Managed Beans and SRTEdit in the Variables tree. Select
hideComments, click the right arrow to add it to the Expression, and then click OK.
11. Follow all steps in “Persisting or Canceling the Update,” except that you edit SRTEdit.java and
SRTEdit.jsp (instead of SREdit.java and SREdit.jsp), and you add the following code to update
the service request (instead of the updateSR() method):
public String updateTSR(){
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
ValueBinding curUser = app.createValueBinding
("#{UserInfo.currentUser}");
Users currentUser = (Users)curUser.getValue(ctx);
ServiceHistories historynotes = new ServiceHistories();
historynotes.setServiceRequests(serviceRequest);
historynotes.setNotes(getInputTextarea1().
getValue().toString());
historynotes.setLineNo(null);
if (hideComments) {
historynotes.setSvhType("Hidden");
}
else {
historynotes.setSvhType("Technician");
}
historynotes.setSvhDate(null);
historynotes.setUsers(currentUser);
serviceRequest.addServiceHistories(historynotes);
9-20 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Developing the Edit Page for Staff
return "techsaved";
} catch (NamingException e) {
// TODO
e.printStackTrace();
}
return "techsaved";
}
Note that this method returns the string techsaved, which is the name of the navigation case
(pointing from this page to the SRList page) that you defined earlier in the JSF Navigation
Diagram.
Press [Alt]+[Enter] when prompted to add several import statements. When you are given a
choice of Application packages to import, select
javax.faces.application.Application.
Continue with creating the command buttons as in “Persisting or Canceling the Update,” except
that you define the Action for the Cancel button as techsaved (rather than saved). You also
need to change the scope of the managed bean to session and implement the Serializable
interface for the SRTEdit backing bean class, as you did for the SREdit backing bean.
12. Follow all steps in “Displaying Detail Records,” except that you edit SRTEdit.java and
SRTEdit.jsp (instead of SREdit.java and SREdit.jsp).
13. Do not conditionally hide detail records as you did for the customers’ edit page. All of the notes
should be visible to staff, even those marked as hidden.
14. Click Save All to save your work. The page should look like the following screenshot:
9-22 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Update Logic and the UI Components
3. A browser opens to display the Logon page. Enter the following logon information and click Sign
On:
Username Password
ghimuro welcome
5. On the List page, click the link for one of the service requests.
6. On the Edit page, click Cancel. You should return to the List page.
7. Click a link for a different service request. On the Edit page, change the status and enter a note,
and then click Save.
9-24 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Update Logic and the UI Components
8. You should return to the List page. Click the same link again to see that the detail section on the
edit page shows the new note entry.
9. Click Logout to redisplay the Logon page. Enter the following logon information, and then click
Sign On:
Username Password
sking welcome
12. You are returned to the list page. Notice the changed status. Click the link to SR ID 110 again. In
the details section, you should see the note that you just entered.
13. Click Logout, and then log back in with the following:
Username Password
ghimuro welcome
Note: If you get an error at this point, restart the application and log in as ghimuro, then
continue with the remaining steps.
14. Click View Your Service Requests. On the List page, click the SR ID 110 link. The detail section
shows none of the hidden notes.
Summary
In this chapter, you created the page that enables users to edit service requests. To accomplish this, you
performed the following key tasks:
Created the edit pages for customers and staff that contain:
o Display components for read-only data
o Components to facilitate data entry
o Buttons to persist or cancel the update
o Display of detail service history records
Added logic to the customer edit page to conditionally hide certain detail records
Added logic to the staff edit page to mark certain detail records as hidden from customer view
Tested the update logic and the UI components
9-26 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
10
Creating the Triage Page
This chapter describes how to create the SRTriage page that enables managers to triage (assign) service
requests to technicians.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh09.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Triage Page Overview
Creating the Page Outline
Adding Named Queries to the Data Model
Exposing the New Named Queries in the Session Facade
Updating the Backing Bean to Retrieve the Data
Adding the Data Table to the Page
Persisting or Canceling the Update
Testing the Functionality of the Page
Summary
10-1
Triage Page Overview
Here are some key points to note about the SRTriage page:
This page is available only to managers.
The manager accesses the SRTriage page from the welcome page by clicking a link that is visible
to only those users with the role of manager.
When the manager clicks the Triage Service Requests link, the SRTriage page shows the current
list of unassigned and open service requests.
The manager can select a technician from the list of technicians for each request, and then click
Assign Technicians to update the service requests.
The following screenshot depicts the features of the SRTriage page:
10-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Page Outline
1. Each application page contains a title, information about the logged in user, and a Logout link.
2. A JSF Data Table component displays a list of open and unassigned service requests. The data
comes from a named query that you add to the ServiceRequests entity. You add code to the
backing bean for the page to retrieve this list of service requests, and you use EL to bind the data
table to this code.
3. A JSF ListBox component displays all users with the technician role. The data comes from a
named query that you add to the Users entity. You add code to the backing bean for the page to
retrieve this list of technicians, and you use EL to bind the list box to this code. If the service
request has already been assigned to a technician, you also use EL to set the value of the list box to
the technican who is already assigned to that service request.
4. An Assign Technicians button calls code that you add to the backing bean to persist the data to the
underlying database tables. The bean is set to session scope so that the data is available for all
pages in the session. This code in the bean returns a string value that corresponds to one of the
From outcomes in a navigation rule that you defined earlier.
5. A Cancel button has an action set to one of the From outcomes in a navigation rule that you
defined earlier. This enables navigation to occur without executing the code to persist the data.
6. The SRTriage page is created and opens in the editor. Enter the text Assign Service
Requests to Technicians and then select Heading 1 from the Block Format drop-down
list.
7. From the Component Palette, select JSF HTML from the drop-down list and drag the Messages
component to the next line in the visual editor.
8. Place the cursor after the Messages component and press [Enter], and then click the Command
Hyperlink component in the Component Palette.
9. In the Insert Command Hyperlink dialog box, enter the Value Logout and click OK.
10. In the Property Inspector for the command hyperlink, enter an Action of #{} and press [Enter],
and then click back into the Action property. Click the ellipsis at the end of the field.
11. In the Action dialog box, ensure that the Method Binding option is selected.
10-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Page Outline
Select Logout from the Managed bean drop-down list, and select logoutButton_action from the
Method drop-down list. Click OK.
This ensures that the Logout link executes the code in the Logout managed bean that you created
in a previous chapter.
12. In the Structure window, select the paragraph node that contains the commandLink that
you just defined.
13. In the Property Inspector, set the Align property of the paragraph to right by selecting that value
from the drop-down list.
14. In the editor, on the next line enter the text You are logged in as, and press [Space]. From
the Block Format drop-down list, select Heading 5.
15. In the Component Palette click the Output Text component.
16. An output text field is created in the editor. In the Property Inspector for the output text, select the
the right arrow to add it to the expression on the right. Then click OK. This causes the
application to display the name of the authenticated user at run time.
18. In the Component Palette, select CSS from the drop-down list and then select JDeveloper.
10-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Update the Backing Bean to Retrieve the Data
1. The classes containing the named queries must be compiled in order for them to be visible to the
facade editor, so click Rebuild to compile all.
2. In the Applications Navigator, expand Model > Application Sources > org.srdemo.business.
3. Right-click ServiceRequestFacadeBean.java and select Edit Session Facade.
4. In the Session Facade Options dialog box, expand the ServiceRequests and Users nodes and
select the check boxes next to the queries that you just added: findTriageRequests and
findUsersByRole. Click OK.
5. The ServiceRequestFacadeBean.java file opens in the editor. Scroll to the end of the file to see the
new methods that were added to expose the new named queries.
following steps:
1. In the Applications Navigator, expand the ViewController project and the Application Sources,
org.srdemo.view, and backing nodes.
2. Double-click SRTriage.java to open it in the editor.
3. Add the following private variables:
private List<ServiceRequests> srTriageList = new ArrayList();
private List<SelectItem> techniciansList = new ArrayList();
private HashMap usersMap = new HashMap();
private List<String> assignedUsers;
The data for these variables is retrieved from the session façade, and their accessors can be used
by components in the page.
4. Press [Alt]+[Enter] when prompted to add import statements, being sure that the List class that
you import is java.util.List.
5. Right-click within the code editor window and select Generate Accessors from the context menu.
6. In the Generate Accessors dialog box, select the check boxes next to all of the variables that you
just added, and then click OK.
10-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Update the Backing Bean to Retrieve the Data
7. You can scroll to the bottom of the file to see the accessors that were created.
8. In the SRTriage.java backing bean class, add a constructor that populates an array with all the
technicians. You use an ArrayList, which has javax.jsf.SelectItem objects so that it
can be displayed in a list box.
The constructor gets an instance of the ServiceLocator class that caches the session facade
instances and calls the findUsersByRole method in the session facade. This method returns a
List of Users. The retrieved list is then populated into techniciansList, which has
SelectItem objects to store userid and username. Each of the retrieved Users is also
stored in a hashMap in order to match it with the user selected in the list box of the page.
Add the following method to SRTriage.java:
public SRTriage(){
// Get the Service Locator's instance
ServiceLocator serviceLocator = null;
try {
serviceLocator = serviceLocator.getInstance();
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)serviceLocator.getFacadeService("java:
comp/env/ejb/ServiceRequestFacade");
List usersList =
srLocal.findUsersByRole("technician");
techniciansList.add(new SelectItem("", "Not
Assigned"));
Iterator it = usersList.iterator();
while(it.hasNext()){
Users user = (Users)it.next();
String userID = user.getUserId().toString();
usersMap.put(userID, user);
String userName = user.getFirstName() +
" " + user.getLastName();
techniciansList.add(new SelectItem(userID,
userName));
}
} catch (NamingException e) {
e.printStackTrace();
}
}
11. Update the getSrTriageList() method to retrieve the service requests that need to be
triaged. The method gets an instance of the ServiceLocator class, which caches the session
facade instances and calls the findTriageRequests() method in the session facade. This
method returns a list of service requests that need to be triaged (those that have a status of “Open”
or are not assigned to any technician).
public List<ServiceRequests> getSrTriageList() {
// Get the Service Locator's instance
ServiceLocator serviceLocator = null;
try {
serviceLocator = serviceLocator.getInstance();
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)serviceLocator.getFacadeService("java:
comp/env/ejb/ServiceRequestFacade");
List<ServiceRequests> srList =
srLocal.findTriageRequests("Open");
if (assignedUsers == null) {
assignedUsers = new ArrayList();
}
else {
assignedUsers.clear();
}
for (ServiceRequests sr : srList) {
String userId = (sr.getUsers1() == null) ? "" :
sr.getUsers1().getUserId().toString();
assignedUsers.add(userId);
}
return srList;
} catch (NamingException e) {
// TODO
e.printStackTrace();
}
10-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding the Data Table to the Page
return srTriageList;
}
7. On the Header and Row Data page of the wizard, select Users and click Remove.
10-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding the Data Table to the Page
10. Now that you have created the data table, you need to add another column to show the list of
technicians that the manager can choose. Select SRTriage.jsp in the Applications Navigator or in
the editor. In the Structure window, right-click the h:dataTable component and select
Insert inside h:dataTable and Column from the context menu.
13. In the Expression dialog box, expand the SRTriage node, select techniciansList, and click the
right arrow to add the expression #{SRTriage.techniciansList}. Click OK.
14. In the Insert Listbox dialog box, click the Advanced Properties tab.
15. Select the Value property and enter the following value:
#{SRTriage.assignedUsers[SRTriage.dataTable1.rowIndex]}
Click OK to dismiss the Insert List box dialog box.
10-14 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Persisting or Canceling the Update
if (
usersMap.containsKey(assignedUserId))
{
Users techUser =
(Users)usersMap.get(assignedUserId);
assignTechToSR.setUsers1(techUser);
assignTechToSR.setAssignedDate(null);
ServiceLocator serviceLocator = null;
try {
serviceLocator =
serviceLocator.getInstance();
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)serviceLocator.getFacadeService("java:
comp/env/ejb/ServiceRequestFacade");
srLocal.mergeEntity(assignTechToSR);
} catch (NamingException e) {
// TODO
e.printStackTrace();
}
}
}
return "triaged";
}
This method processes the service request updates after the manager has selected technicians for
each service request that should be assigned. The method iterates over each row of the data table
to see if the manager has selected a user from the list. If so, it gets an instance of
ServiceLocator, finds the service request facade bean, and calls the mergeEntity method,
passing the updated ServiceRequests object to be committed to the database.
Note: This method returns the string triaged, which is the name of the navigation case
(pointing from this page to the SRList page) that you defined earlier in the JSF Navigation
Diagram.
3. Switch to SRTriage.jsp in the editor. Place the cursor after the data table within the form (red
dotted line) and press [Enter] to create a blank line.
4. In the Component Palette, select JSF HTML from the drop-down list and click Command
Button.
5. In the Property Palette, set the Value property to Assign Technicians.
6. Double-click the Assign Technicians button in the editor, and in the Bind Action Property dialog
box, select triageRequests from the Method drop-down list. Click OK.
Note: The triageRequests() method in the SRTriage managed bean persists the updated
records and returns the string triaged, which is the name of the navigation case that you
defined in the faces-config.xml file to navigate to the SRList page.
7. In the editor for SRTriage.jsp, place the cursor to the right of the Assign Technicians button and
click Command Button in the Component Palette.
8. In the Property Palette, set the Value property to Cancel and set the Action property to triaged
so that the user navigates to the SRList page without executing the update code in the backing
bean.
9. Change the scope of the managed bean to session so that changes can be seen in other pages of
the application. Open (right-click ViewController and select Open JSF Navigation) or switch to
the faces-config.xml file in the editor.
10. Click the Overview tab, select SRTriage, and click Edit.
11. In the managed-bean Properties dialog box, select session from the Scope drop-down list and click
OK.
12. Classes for beans with session scope must implement the Serializable interface if they
are part of a distributable Web application. Because you intend to deploy this application to a
cluster (a group of OC4J instances), you must perform this step.
Open or switch to SRTriage.java and locate the following line:
public class SRTriage {
Change it to:
public class SRTriage implements Serializable{
Press [Alt]+[Enter] when prompted to import java.io.Serializable.
10-16 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Functionality of the Page
Username Password
sking welcome
4. On the Triage page, click Cancel. You should then navigate to the List page, where you can click
Back to Home to return to the Welcome page.
5. On the Welcome page, again click Triage Service Requests.
6. On the Triage page, select a technician for one or more of the unassigned service requests and
click Assign Technicians.
7. In JDeveloper, click the Connections tab. In the Connections Navigator, expand the Database,
SRDemo, SRDEMO, and Tables nodes. Double-click the SERVICE_REQUESTS table to open
it in the editor.
8. Click the Data tab. You should see that the update was committed to the database.
Note: If the table is open in the editor, you need to select View > Refresh to see the update.
Summary
In this chapter, you created a service requests triaging page that uses JavaServer Faces components. Those
components display data coming from the EJB 3.0 data model. You also added an action that processes the
service requests displayed in the data table and assigns a technician based on the manager selection.
In short, here are the key tasks that you performed in this chapter:
Created the page outline with the heading, a Messages component, a Logout link, and a message
displaying the name of the logged-in user
Added named queries to display the service requests and a list of technicians
Exposed the new named queries by editing the session facade
Updated the backing bean for the page to get the data from the session facade
Added a data table component to the page to display a list of open or unassigned service requests,
along with a list of technicians to whom they can be assigned
Added command button components to persist or cancel the update
Tested the functionality of the page
10-18 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
11
Developing a Page to Insert Records
All of the pages to perform DML that you have created so far have enabled users to update existing data.
Now you create an insert page that enables users to insert new service request records into the database.
The page contains UI components that ensure data accuracy and facilitate data entry.
If you did not successfully complete the previous section of the tutorial, you may access the solution for the
previous section in the \solutions subdirectory of your \setup directory (see the section “Setting Up
Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh10.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Creating the Insert Page
Adding Data Entry Components
Persisting or Canceling the Insert
Testing the Insert Logic and the UI Components
Summary
11-1
Creating the Insert Page
6. The new page opens in the editor. Enter the text Create a new service request and then
select Heading 1 from the Block Format drop-down list.
7. In the Component Palette, select JSF HTML from the drop-down list and drag the Messages
component to the next line on the page in the visual editor.
11-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Insert Page
8. Place the cursor after the Messages component and press [Enter]. Then click the Command
Hyperlink component.
9. In the Insert Command Hyperlink dialog box, enter the Value Logout and click OK.
10. In the Property Inspector for the command hyperlink, enter the Action #{} and press [Enter], and
then click back into the Action property. Click the ellipsis at the end of the field.
11. In the Action dialog box, ensure that the Method Binding option is selected. Select Logout from
the Managed bean drop-down list, and select logoutButton_action from the Method drop-down
list. Click OK.
This ensures that the Logout link executes the code in the Logout managed bean that you created
in a previous chapter.
12. In the Structure window, select the paragraph node that contains the commandLink that
you just defined.
13. In the Property Inspector, set the Align property of the paragraph to right by selecting that value
from the drop-down list.
14. On the next line, enter the text You are logged in as, and then press [Space]. From the Block
Format drop-down list, select Heading 5.
15. In the Component Palette, click the Output Text component.
16. An output text field is created in the editor. In the Property Inspector for the output text, select the
the right arrow to add it to the expression on the right. Click OK. This causes the application
to display the name of the authenticated user at run time.
18. Select HTML Common from the Component Palette drop-down list, and then drag Table to the
next line on the page in the visual editor to create a table on the page.
19. In the Insert Table dialog box, set the number of rows to 3 and click OK.
20. In the left column, enter the following three phrases in each of the three rows:
11-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Data Entry Components
Select a Product
Problem Description
Notes
21. Select CSS from the Component Palette drop-down list, and then select JDeveloper. Your page
should now look similar to the following screenshot:
When you change the method properties in this manner, the local and remote interface code
remains synchronized with that of the session bean.
11-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Data Entry Components
6. You can scroll to the end of the ServiceRequestFacadeBean.java file in the editor to see the
method that was added.
10. Press [Alt]+[Enter] when prompted to add import statements, choosing java.util.List for
the List class.
11. Right-click in the editor window and select Generate Accessors from the context menu.
12. In the Generate Accessors dialog box, select the check boxes next to the prodList,
productKey, and productMap variables and then click OK.
13. Toward the end of the file, modify the accessor methods for prodlist.
First, modify the signature for the setter method. Locate the following line:
public void setProdList(List prodList) {
Change it to:
public void setProdList(List<Products> prodList) {
Then press [Alt]+[Enter] to accept the suggested import statement.
14. Change the signature for the getter method. Locate the following line:
public List getProdList() {
Change it to:
public List<Products> getProdList() {
15. Change the body of the getter method. Locate the following line:
return prodList;
Replace it with the following lines:
ServiceLocator serviceLocator = null;
try {
serviceLocator = serviceLocator.getInstance();
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)
serviceLocator.getFacadeService
("java:comp/env/ejb/ServiceRequestFacade");
List productsList = srLocal.findAllProducts();
Iterator it = productsList.iterator();
while(it.hasNext()){
Products product = (Products)it.next();
SelectItem sItem = new SelectItem();
String pId =
product.getProdId().toString();
productMap.put(pId, product);
String prodName = product.getName();
sItem.setLabel(prodName);
sItem.setValue(pId);
prodList.add(sItem);
11-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Adding Data Entry Components
}
} catch (NamingException e) {
e.printStackTrace();
}
return prodList;
16. Press [Alt]+[Enter] after each prompt to accept all of the suggested import statements.
This appears in the list item of the list of products from the SRCreate managed bean.
21. Click the Advanced Properties tab.
22. Click into the Value property and click Bind to Data .
23. In the Value dialog box, expand JSF Managed Beans and SRCreate. Select productKey and
click the right arrow to shuttle it to the Expression, and then click OK.
This sets the value of the list item to the product ID of the product that the user selects from the
list.
24. Click OK to dismiss the Insert Listbox dialog box.
11-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Persisting or Canceling the Insert
//sr.setProducts(getProduct());
sr.setProducts(product);
sr.setProblemDescription
(getInputText1().getValue().toString());
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
ValueBinding curUser =
app.createValueBinding("#{UserInfo.currentUser}");
Users currentUser = (Users)curUser.getValue(ctx);
sr.setUsers(currentUser);
sr.setRequestDate(null);
// sr.addToServiceHistoriesList(svh);
List<ServiceHistories> svhList = new
ArrayList<ServiceHistories>();
svhList.add(svh);
sr.setServiceHistoriesList(svhList);
ServiceLocator serviceLocator = null;
try {
serviceLocator = serviceLocator.getInstance();
ServiceRequestFacadeLocal srLocal =
(ServiceRequestFacadeLocal)
serviceLocator.getFacadeService
("java:comp/env/ejb/ServiceRequestFacade");
srLocal.persistEntity(sr);
return "created";
} catch (NamingException e) {
// TODO
e.printStackTrace();
}
return "created";
}
3. Press [Alt]+[Enter] after each prompt to accept import statements, choosing to import
javax.faces.application.Application for the Application class.
4. Switch to SRCreate.jsp in the editor. Place the cursor after the table within the red dotted line of
the form and press [Enter] to create a blank line.
5. In the Component Palette, select JSF HTML from the drop-down list and click Command
Button.
6. In the Property Inspector for the command button, set the Value property to Create.
7. Double-click the Create button in the editor, and in the Bind Action Property dialog box, select
CreateSR from the Method drop-down list. Click OK.
Note: The CreateSR() method in the SRCreate managed bean persists the data and returns the
string created, which is the name of the navigation case that you defined in the faces-
config.xml file to navigate to the SRList page.
8. From the Component Palette, drag a Command Button to the right of the Create button in the
editor for SRCreate.jsp.
9. In the Property Palette, set the Value property to Cancel. Select created from the Action
property drop-down list so that the user navigates to the SRList page without executing the code in
the managed bean that creates and saves the record.
Username Password
11-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Insert Logic and the UI Components
Username Password
sking welcome
6. The SRList page should display without showing the data that you entered because you did not
commit it. Click the Back to Home link.
11-14 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Testing the Insert Logic and the UI Components
9. The SRList page should appear and show the service request that you just created.
10. To confirm that the data has been committed to the database, in JDeveloper click the Connections
Navigator tab and then expand the SRDemo, SRDEMO, and Tables nodes.
11. Double-click the SERVICE_HISTORIES table to open it, and then click the Data tab. You
should see the service request that you just created. (If you already had the table open, you may
need to select View > Refresh to see the new data.)
11-16 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
12. Now double-click the SERVICE_HISTORIES table in the Connections Navigator and click the
Data tab. You should see the newly created record.
Summary
In this chapter, you created the page that enables users to create a new service request in the database. To
accomplish this, you performed the following key tasks:
Created the SRCreate page with standard logic for displaying the user ID and for logging out
Added a table to lay out the components
Added data entry UI components to the page
Added logic to the managed bean for the page to display the UI and to insert the records in the
database
Bound the UI components to the logic in the managed bean
Tested the insert logic and the UI components
The first part of this tutorial showed you how use Oracle JDeveloper to build a Java EE application and
deploy it to the embedded OC4J container that is part of JDeveloper. In a production environment,
however, you must deploy to an application server. The last two chapters of this tutorial pertain to
deploying the SRDEMO application into Oracle Application Server 10g (10.1.3.1).
This chapter contains the following topics:
Introduction
Downloading Oracle Application Server
Installing the First Oracle Application Server Instance
Installing the Second OC4J Instance
Launching the Application Server Control Console
Summary
12-1
Introduction
Introduction
Before you begin to install and deploy to Oracle Application Server, it is helpful to understand how Oracle
Application Server enables you to deploy your EJB 3.0 application. In this introductory section, you learn
answers to the following questions:
What is Oracle Application Server?
What are the benefits of using OC4J?
How are requests routed to the application?
In this chapter, you perform the following key tasks:
Download Oracle Application Server 10g
Install two instances of Oracle Application Server, ideally on a single host machine
Cluster the two instances together
Deploy the application across the cluster
Configure HTTP session state replication between the application instances running within the
cluster
In this tutorial, you install two instances of Oracle Application Server 10g so that you can see such features
as clustering, state replication, and rolling application upgrades.
Ideally, you should install both Oracle Application Server instances on the same physical host machine.
Benefits of OC4J
At the core of Oracle Application Server is Oracle Application Server Containers for J2EE (OC4J). The
latest release, OC4J 10g Release 3 (10.1.3), provides a fully Java EE-compliant environment for creating
and hosting secure, portable, high-performing applications. It provides all the containers, APIs, and
services mandated by the Java EE specification, including:
A Web container providing a run-time environment for JavaServer Pages (JSPs) and servlets
12-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Downloading Oracle Application Server
An Enterprise JavaBeans (EJB) container that supports the EJB 2.1 specification as well as the
new EJB 3.0 specification
A complete design and run-time environment for Web services
In addition, OC4J provides full implementations of the standard Java EE services, including:
A feature-rich implementation of the Java Message Service (JMS), which enables components
running within the container to send and receive messages
Data access and persistence through the Java Database Connection API (JDBC). You learn how to
create data sources for connecting to databases in this tutorial.
Transaction management through an implementation of the Java Transaction API
Component lookup via the Java Naming and Directory Interface (JNDI)
Application security—authorizing and authenticating application users—through implementation
of the Java Authentication and Authorization Service (JAAS)
Connectivity with legacy systems through the Java EE Connector Architecture (JCA)
Note: The appearance of the Web page may not be identical to what is shown in the screenshot
because content on OTN may change.
3. On the download page, click the link for Oracle Application Server SOA Suite (10.1.3.1.0).
4. After accepting the license terms and export restrictions, click the link that is applicable to your
platform (Windows or Linux). The examples in this chapter use the Windows version; instructions
for the Linux version may differ. You should consult the installation guide before installing.
5. When the download has finished, extract the files to a directory of your choosing.
12-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Installing the First Oracle Application Server Instance
2. On the Installation screen of the installer, click Browse to navigate to the Oracle home directory
where the application server should be installed. Be sure to also indicate a new subdirectory for
this application server version. This entire path is referred to elsewhere in this tutorial as the
application server home directory, or <AS_HOME>. Select the Advanced Install option and click
Next.
3. On the Select Installation Type screen of the installer, select the option J2EE Server and Web
Server. Click Next.
4. On the Specify Port Configuration Options screen of the installer, select the Automatic option and
click Next.
This enables the OPMN component to dynamically select the ports to use upon installation.
5. On the Administration Settings screen of the installer, specify the Oracle Application Server
instance name. Because this is the administration instance, you may want to use admin (as the
example does).
Specify an Administrator Account Password (at least one numeric character is required) to be
associated with the default oc4jadmin administrator account. The example uses welcome1 as
the password.
Select the Configure this as an Administration OC4J Instance check box.
For convenience, you can accept the default name home for the OC4J instance that runs within
this Oracle Application Server instance. Click Next.
6. On the Cluster Topology Configuration screen of the installer, select the Configure this instance
to be part of an Oracle Application Server cluster topology check box. Then provide a
multicast address and port combination to be used to add the OHS and OC4J instances to a cluster.
The multicast address must be within the valid address range, which is 224.0.1.0 to
239.255.255.255.
In this step, you are enabling the dynamic discovery mechanism, which allows Oracle Application
Server components to dynamically discover and communicate with one another via multicast
messages. The cluster is essentially able to manage itself, as each Oracle Application Server node
is updated when other nodes broadcasting on the same address:port combination are added or
removed from the cluster via the multicast broadcasts.
Note that clustering does not have to be required at installation time, nor is multicast-based
dynamic discovery the only clustering option supported. However, because this is the simplest
clustering scheme to implement, we are using it here. See the Oracle Containers for J2EE
Configuration and Administration Guide for complete details on cluster configuration:
http://download-west.oracle.com/docs/cd/B25221_02/web.1013/b14432.pdf.
The example uses an IP address of 225.0.0.1 and a port of 6789.
12-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Installing the First Oracle Application Server Instance
Click Next.
7. On the Summary screen of the installer, click Install to install the instance.
8. When installation is complete, you should see a Succeeded status on the Configuration Assistants
screen of the installer for the two configuration assistants. Click Next.
<AS_HOME>/opmn/bin/opmnctl status
Here is an example:
C:\oracle\product\10.1.3.1\AS10g\opmn\bin\opmnctl status
If the components are running, you should see output similar to the following:
Processes in Instance: admin.<host.domain>
-------------------+--------------------+---------+---------
ias-component | process-type | pid | status
-------------------+--------------------+---------+---------
OC4J | home | 7108 | Alive
HTTP_Server | HTTP_Server | 596 | Alive
Note: You must be connected directly to the network, rather than through a virtual private
network (VPN), in order to use the multicast type of clustering that is described in this chapter.
If you are connected via VPN, you can use peer-to-peer clustering as described in the OC4J
Configuration and Administration Guide (http://download-
west.oracle.com/docs/cd/B25221_02/web.1013/b14432.pdf) in the section “Configuring Static
Discovery Servers.” This tutorial uses multicast (not peer-to-peer) clustering.
12-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Installing the Second OC4J Instance
2. On the Select Installation Type screen of the installer, select the J2EE Server option. Click Next.
3. On the Specify Port Configuration Options screen of the installer, select the Automatic option and
click Next.
4. On the Administration Settings screen of the installer, specify the Oracle Application Server
instance name. Because this is the second instance, you may want to use instance2 (as the
example does).
Specify the same Administrator Account Password that you specified for the administrator
account. This is required to enable you to install across all nodes in the cluster. The example uses
welcome1 as the password.
This time do not select the “Configure this as an Administration OC4J Instance” check box.
Because this OC4J is managed by the other instance hosting Application Server Control, you
disable this application on the new instance.
Specify the same OC4J instance name that you specified in the first instance. The example uses
home as the OC4J instance name. This enables you to install your application to the same named
instance group within the cluster.
Click Next.
5. On the Cluster Topology Configuration screen of the installer, select the Access this OC4J
Instance from a separate Oracle HTTP Server check box to enable the local Web listener of
this OC4J instance to receive requests routed from your OHS instance.
Select the Configure this OC4J instance to be part of an Oracle Application Server cluster
topology check box. Then provide the same multicast address and port combination as you set for
the first instance.
6. Click Next.
7. On the Summary screen of the installer, click Install to install the instance.
8. When installation is complete, you should see a Succeeded status on the Configuration Assistants
screen of the installer for the two configuration assistants. Click Next.
9. The End of Installation screen lists a variety of valuable information; this information is also
contained in the file <AS2_HOME>\install\readme.txt. Click Exit when finished to exit
the installer.
10. If you want to see details of the actions performed by the installer, after closing the installer you
can open the C:\Program
Files\Oracle\Inventory\logs\installActions<datetime>.log file.
11. The OC4J instance is started at the end of the installation process. To verify this, open a command
prompt and type the following command:
<AS2_HOME>/opmn/bin/opmnctl status
Here is an example:
C:\oracle\product\10.1.3.1\AS10g2\opmn\bin\opmnctl status
12-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Installing the Second OC4J Instance
You have effectively clustered your two Oracle Application Server instances.
3. The top-level Cluster Topology page provides you with a view of your clustered environment. The
top of the page shows an overview of the hosts, servers, and instances.
Note the “Groups” section at the bottom of the page. A group is a synchronized set of OC4J
instances that belong to the same cluster topology. Because the OC4J instances you created are
members of the same cluster, they implicitly belong to the default_group of instances. You
will see how operations can be performed on groups in the next chapter of this tutorial.
12-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary
Summary
In this chapter, you prepared for deployment of the application by installing Oracle Application Server 10g.
In short, here are the key tasks that you performed in this chapter:
Downloaded Oracle Application Server
Installed an Oracle Application Server instance that includes Oracle HTTP Server and OC4J
Installed a second application server instance that includes only OC4J to be managed by the first
instance in a cluster
Launched the Application Server Control console and viewed the installed instances
You are now ready to deploy the application to the default-group group of OC4J instances within the
cluster (if you have not configured a cluster, you can deploy to a single OC4J instance). You use
JDeveloper to package the application for deployment, and you use Application Server Control to complete
the deployment.
If you did not successfully complete creating all the pages of the application, you may access the solution
for the previous section in the \solutions subdirectory of your \setup directory (see the section
“Setting Up Your Environment” in Chapter 1 for instructions on creating a \setup directory). Extract the
SRDEMOCh11.zip file into a directory of your choosing and open the SRDEMO.jws workspace in
JDeveloper to continue working on it.
This chapter contains the following topics:
Deployment Overview
Making the Application Distributable
Creating a Deployment Project
Creating Deployment Profiles
Creating Deployment Descriptors
Creating the Data Sources
Deploying the Application
Testing the Application
Using Application Server Control to Explore the Application
Clustering and Rolling Upgrade (optional)
Summary
13-1
Deployment Overview
Deployment Overview
Deploying an application essentially consists of the following:
Uploading the archive
Binding the Web modules within the application to the Web site within OC4J that will receive
requests from Oracle HTTP server.
Configuring the application by modifying the OC4J-specific deployment descriptors through
Application Server Control
Deploying the archive
In the browser that is displaying Application Server Control, notice the Groups section at the bottom of the
page, as shown in the following screenshot:
OC4J instances that share the same name—in this case, home—form a “group” of instances. Operations
such as start, stop or deploy applications can be performed simultaneously across all of the instances within
a group.
13-2 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating a Deployment Project
4. Select the Web Application is Distributable check box, and then click OK.
5. Click Save All to save your work. The Applications Navigator should now look like the
following screenshot:
13-4 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating Deployment Profiles
5. Click Save All to save your work. The Applications Navigator should now look like the
following screenshot:
In the assembly part of deployment, you create a deployment profile that includes any .jar and .war files
you need for your application, along with other server configuration files that may be required. Two
configuration files that are required are:
The data-sources.xml file that contains the configuration for the installed data sources of
an application server. Data sources are actual Java objects that represent the physical data
storage systems, such as databases. From these objects a Java EE application can retrieve
JDBC connections to the databases being represented. This layer of abstraction provides
benefits such as connection pooling, configuration flexibility and application portability.
JDeveloper automatically creates an OC4J data source for each database connection in your
JDeveloper installation; you can view these by selecting Tools Embedded OC4J Server
Preferences.
The jazn-data.xml file, previously described in Chapter 6 of this tutorial, that defines the
realms (users and roles) for container-managed application security
To create this deployment profile, perform the following steps:
1. In the Applications Navigator, right-click the Deployment project and select New.
2. In the New Gallery, expand General and select Deployment Profiles from the Categories list.
Select EAR File in the Items list and click OK.
3. Change the profile name to SRDEMO and click OK.
4. In the EAR Deployment Profile Properties dialog box, select the Application Assembly category,
and then select the following Java EE modules to include in the .ear file:
ViewController.jpr SRDEMO-WEB.deploy
Model.jpr SRDEMO-EJB.deploy
Click OK to accept the other defaults.
13-6 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating Deployment Profiles
5. Click Save All to save your work. The Applications Navigator should now look like the
following screenshot:
3. If the Welcome page of the Create Deployment Descriptor wizard displays, click Next.
4. On the Select Descriptor page of the wizard, select application.xml and click Next.
5. On the Select Version page of the wizard, select 5.0 and click Finish.
6. Right-click the Deployment project and select New from the context menu.
7. In the New Gallery, select Deployment Descriptors from the Categories list. In the Items list,
select OC4J Deployment Descriptor Wizard and click OK.
8. If the Welcome page of the Create Deployment Descriptor wizard displays, click Next.
9. On the Select Descriptor page of the wizard, select jazn-data.xml and click Next.
10. On the Select Version page of the wizard, select 10.0 and click Finish.
11. Invoke the OC4J Deployment Descriptor wizard once again, this time selecting the
orion-application.xml deployment descriptor and version 10.0. When you are finished, the
Applications Navigator should look like the following screenshot:
13-8 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating Deployment Profiles
Next you insert two modules into the application: the Web module and the EJB module.
3. To insert the Web module, perform the following steps:
In the Structure window, right-click the application node and select Insert inside
application module from the context menu.
Right-click the module node and select Insert inside module web from the context menu
and enter an id of srdemo.
Right-click the web node and select Insert inside web web-uri, and then in the Property
Inspector change the web-uri to SRDEMO-WEB.war.
Again right-click the web node and select Insert inside web context-root, and then in the
Property Inspector enter SRDemo as the value for context-root, as shown in the following
screenshot:
4. Now you insert the EJB module by performing the following steps:
In the Structure window, right-click the application node and select Insert inside
application module from the context menu.
Right-click the module node and select Insert inside module ejb from the context menu.
In the Property Inspector, enter SRDEMO-EJB.jar as the value for the ejb property.
13-10 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating Deployment Profiles
5. The orion-application.xml file should point to the location of the jazn-data.xml file
and specify the data source to use. Switch to orion-application.xml in the editor by clicking its
tab, or double-click it in the Applications Navigator to open it in the editor.
6. To make the file easier to read, right-click in the editor and select Reformat from the context
menu.
7. Add the following attribute to the opening orion-application tag:
default-data-source="jdbc/SRDemoDS"
The entire file should now read (with the added portion in bold):<?xml version = '1.0'
encoding = 'windows-1252'?>
<orion-application xmlns:xsi=http://www.w3.org/2001/XMLSchema-
instance
xsi:noNamespaceSchemaLocation=
"http://xmlns.oracle.com/oracleas/schema/orion-application-
10_0.xsd"
default-data-source="jdbc/SRDemoDS">
<jazn location="./jazn-data.xml" provider="XML"/>
</orion-application>
Ensure that the right margin does not contain any red areas indicating any errors in the XML.
8. Switch to jazn-data.xml in the editor by clicking its tab, or double-click it in the Applications
Navigator to open it in the editor.
9. When you were creating the Service Request application, you created users and roles in a file
named SRDemo-jazn-data.xml. Because you have already defined this for the embedded OC4J
data, you can copy the definitions into the Java EE deployment descriptor. Right-click in the editor
and select Compare With Other File from the context menu.
10. In the Select File to Compare With dialog box, navigate to the main application directory
SRDEMO, select SRDEMO-jazn-data.xml, and click Open.
11. In the Compare files, select in the view of SRDEMO-jazn-data.xml all the text beginning
with the line <jazn-realm> and press [Ctrl]+[C] to copy the text. You can then close the
Compare if you wish.
12. In jazn-data.xml, delete the closing </jazn-data> tag. If there is not a complete closing
</jazn-data> tag, then just delete the forward slash (/) prior to the closing bracket. The file
should now look like this:
<?xml version = '1.0' encoding = 'windows-1252' standalone =
'yes'?>
<jazn-data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation=http://xmlns.oracle.com/oracleas/
schema/jazn-data-10_0.xsd
filepath="" OC4J_INSTANCE_ID="">
13-12 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating Deployment Profiles
Ensure that the right margin does not contain any red areas indicating any errors in the XML.
You have now created the EAR file that you need to successfully deploy your application to a Java EE
server. Make note of the location of the EAR file that is shown in the log window.
13-14 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Data Sources
5. On the Group: default_group Administration page, click Go to Task for the JDBC
Resources task.
Field Value
Name SRDemoConnectionPool
Connection Factory oracle.jdbc.pool.OracleDataSource
(the default value)
JDBC URL jdbc:oracle:thin:@//localhost:1521/orcl
(your host, port, and database)
Credentials: srdemo
Username
Credentials: oracle
Cleartext Password
13-16 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Data Sources
10. In the Test Connection window, click Test. If successful, you return to the Create Connection
Pool page, where you should see this message:
Connection established successfully for all OC4J instances in the
Group.
Click Finish.
The new connection pool is shown under the Connection Pools section.
2. On the “Create Data Source – Application & Type” page, in the Application section of the page
select default from the Application drop-down list. The data source should be available to the
default application and all of its child applications, including SRDEMO. Select the Managed
Data Source option and click Continue.
13-18 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Creating the Data Sources
3. On the “Create Data Source – Managed Data Source” page, set Name to SRDemoDS. The data
source must be named the same as the data source that you used during development. Set JNDI
Location to jdbc/SRDemoDS. Select SRDemoConnectionPool from the Connection Pool drop-
down list. You do not need to specify credentials because those were set in the connection pool
definition. Click Finish.
4. On the JDBC Resources page, click Test Connection to test the SRDemoDS data source.
13-20 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Deploying the Application
JDeveloper that is invoked when you deploy to an application server from JDeveloper. This means that you
can edit the packaged descriptors prior to deployment, and then when you deploy the application, new
OC4J descriptors are generated that use this data.
Notice the Groups section at the bottom of the Cluster Topology page in Application Server Control (if you
are on a different page, you can navigate to the Cluster Topology page by clicking its link in the
breadcrumbs at the top of the page). OC4J instances that share the same name—in this case, home—form a
group of instances. Operations such as starting, stopping or deploying applications can be performed
simultaneously across all of the instances within a group.
To deploy the application, perform the following steps:
1. In the Cluster Topology page (you can return to this by clicking its link in the breadcrumbs at the
top of the page), click the default_group link under Groups.
2. On the “Group: default_group” page, click the Applications tab and then click Deploy.
3. On the Select Archive page of the Deployment wizard, click Browse in the Archive section to
navigate to the location of your EAR file, which is in the \Deployment\deploy subdirectory
of your SRDEMO application.
For example: C:\JDeveloper\jdev\mywork\SRDEMO\Deployment\deploy
Select the SRDEMO.ear file and click Open. On the Select Archive page of the wizard, click
Next.
4. On the Application Attributes page of the deployment wizard, enter the Application Name of
SRDEMO. This name identifies this application in the list of applications on the OC4J Applications
page.
Verify that the context root is set for each Web module in the application (in this case, there is
only one Web module). This value is read from the Java EE standard application.xml
deployment descriptor. Users access the Web module by appending this value to the URL. Note
that you bind the Web module to default-web-site, which defines the internal Web listener
that receives requests from OHS.
It is possible to create additional Web sites within an OC4J instance for use by applications. For
example, you may want to create a Web site to be used exclusively by Application Server Control,
effectively dividing management and general application Web access. Or you may need to create a
secure Web site for receiving HTTPS requests. For purposes of this tutorial, however, the
default Web site is sufficient.
Click Next.
5. Now you are ready to perform install-time configuration. On the Deployment Settings page of the
13-22 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Deploying the Application
6. On the Configure Clustering page, select the Override parent application clustering settings
option and select Enable from the Clustering drop-down list to enable clustering.
You can now see the various clustering configuration options.
Select the Peer-to-Peer Replication option to enable dynamic peer-to-peer clustering. You do not
need to specify a bind address.
7. At the bottom of the Configure Clustering page, expand Replication Properties. You can use
these properties to define such parameters as what data is replicated and when replication occurs.
Ensure that the Allow Colocation check box is selected, which enables data to be replicated to
OC4J instances running on the same physical machine.
Do not change the Replication Trigger setting; leave it blank to use the default value of
onRequestEnd.
You don’t need to set Replication Scope, since the default configuration will cause all modified
attributes on the session to be replicated.
8. Scroll to the bottom or the top of the page and click OK. The Deployment Settings page displays
the message:
Deployment plan has been updated successfully.
Click Deploy. A Processing page displays progress messages during deployment.
Here’s what happens:
OC4J copies the EAR file to the master deployment directory on the OC4J instance running in
the administration (admin) Oracle Application Server instance. The default location is the
<OC4J_HOME>/j2ee/home/applications/ directory.
OC4J opens and parses the Java EE standard application.xml descriptor packaged
within the EAR file. This file lists all of the modules contained within the EAR file. OC4J
notes these modules and initializes the EAR environment.
OC4J reads the module deployment descriptors for each module type — Web module
(WAR), EJB module, connector module, or client module — into memory. The JAR and
WAR file environments are also initialized.
The archive and the deployment plan are sent to the OC4J server. OC4J uses the contents of
the deployment plan to generate the various OC4J-specific descriptors within the
<OC4J_HOME>/j2ee/home/application-deployments directory.
OC4J reacts to the configuration details contained in both the Java EE deployment descriptors
and any OC4J-specific deployment descriptors. OC4J notes any Java EE component
configurations that require action by OC4J, such as wrapping EJBs with their interfaces.
OC4J writes out new OC4J-specific configuration files to the
<OC4J_HOME>/j2ee/home/application-deployments/<app_name> directory,
according to the contents of the deployment plan. Note that if one or more OC4J-specific
deployment descriptors were supplied, you may notice that OC4J added additional elements
to the generated files.
13-24 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Deploying the Application
Any generated classes, such as EJB interface wrapper classes, are compiled and put into new
subdirectories of this directory. For example, EJB wrapper classes are generated within an
archive named deployment-cache.jar within the
<OC4J_HOME>/j2ee/home/application-
deployments/<app_name>/<jar_name.jar>/ directory, where
<jar_name.jar> corresponds to the name of a deployed EJB JAR.
The same process is then repeated on the second OC4J instance (instance2 in the
example).
You can watch this progress in the Application Server Control Console. Note that deployment
continues even if you close your browser.
After successful deployment, a confirmation page displays the message:
Application "SRDEMO" successfully deployed to all applicable OC4J
Instances in Group "default_group".
10. Click the Cluster Topology link in the breadcrumbs to return to the Cluster Topology page. You
should now be able to drill down on each OC4J instance and see that the application has been
deployed and started on each.
Field Value
Username sking
Password welcome
3. Click the links on the Welcome page to explore the pages of the application. Leave the browser
open when you finish exploring the application.
13-26 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Using Application Server Control to Explore the Application
5. Expand the SRDEMO application and click the link to one of the deployed SRDEMO
applications.
6. You can use Enterprise Manager to explore a number of aspects of the application, such as the
following:
Click the Home tab to view specifics about the application you just deployed.
8. Click the Administration tab to see all of the deployment aspects of the application, including
details of the JAZN security implementation.
13-28 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Clustering and Rolling Upgrade
Note: If you have not configured the Application Server for clustering, then you cannot perform this
exercise.
13-30 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Clustering and Rolling Upgrade
Parameter Value
For example:
C:\oracle\product\10.1.3\AS10g\j2ee\home>java -jar
admin_client.jar
deployer:cluster:opmn://localhost:6003/default_group oc4jadmin
welcome1 -redeploy -file
c:\JDeveloper\mywork\SRDEMO\Deployment\deploy\SRDEMO.ear
-deploymentName SRDEMO –sequential -keepsettings
Note: As the command executes, continue with Step 8.
The SRDEMO application is now stopped, undeployed, redeployed, and then restarted to each
of your Oracle Application Server instances.
Note that the deployment plan you created the first time the application was deployed is
reused during the redeployment. As such, your previous configuration is automatically
applied to the redeployed application.
8. Continue to reload the application in your Web browser as the redeploy command is executing.
You should continue to see the same login name displayed with each click, eventually noting the
change in application appearance as the modified version is deployed, as shown in the following
screenshot:
This illustrates that state has effectively been maintained during the deployment of the new,
modified version of the application.
Summary
In this chapter, you deployed the application and performed a rolling upgrade of the application.
You performed the following key tasks in this chapter:
Made the application distributable so that it can run simultaneously in multiple Web
containers
Created a Deployment project to contain deployment details
Created deployment profiles for the Model (.jar file), ViewController (.war file), and
Deployment (.ear file) projects
13-32 Oracle Application Server 10g R3: Tutorial for Java EE Developers (10.1.3.1.0)
Summary