Vous êtes sur la page 1sur 256

Oracle JDeveloper 10g: Build

Applications with ADF


Instructor Guide Volume 2

D16975GC10
Production 1.0
May 2004
D39415

Authors

Copyright 2004, Oracle. All rights reserved.

Gary Williams
Lynn Munsinger
Patrice Daux

This documentation contains proprietary information of Oracle Corporation. It is


provided under a license agreement containing restrictions on use and disclosure and
is also protected by copyright law. Reverse engineering of the software is prohibited.
If this documentation is delivered to a U.S. Government Agency of the Department of
Defense, then it is delivered with Restricted Rights and the following legend is
applicable:

Technical Contributors
and Reviewers

Restricted Rights Legend

Jeff Gallus
Pam Gamer
Duncan Mills

Use, duplication or disclosure by the Government is subject to restrictions for


commercial computer software and shall be deemed to be Restricted Rights software
under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013,
Rights in Technical Data and Computer Software (October 1988).

Publisher

This material or any portion of it may not be copied in any form or by any means
without the express prior written permission of Oracle Corporation. Any other copying
is a violation of copyright law and may result in civil and/or criminal penalties.

Joseph Fernandez

If this documentation is delivered to a U.S. Government Agency not within the


Department of Defense, then it is delivered with Restricted Rights, as defined in
FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).
The information in this document is subject to change without notice. If you find any
problems in the documentation, please report them in writing to Education Products,
Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065.
Oracle Corporation does not warrant that this document is error-free.
All references to Oracle and Oracle products are trademarks or registered trademarks
of Oracle Corporation.
All other products or company names are used for identification purposes only, and
may be trademarks of their respective owners.

Contents
Preface
I

Introduction
Objectives I-2
Course Overview I-3

Oracle Application Development Framework


Objectives 1-2
J2EE Platform 1-3
Benefits of the J2EE Platform 1-5
J2EE Platform: Architecture Details 1-6
Building J2EE Applications 1-7
What Is Framework-Based Application Development? 1-8
Understanding Framework-Based Application Development 1-9
Oracle Application Development Framework 1-10
Visual and Declarative Development 1-11
Design Patterns 1-12
Model-View-Controller Architecture 1-13
MVC Structure 1-14
What Is the Model? 1-15
The Model Layer 1-16
Components of the Model Layer 1-17
What Is the Controller? 1-18
Struts in JDeveloper 1-19
Controller: Summary 1-20
What Is the View? 1-21
View Concept 1-22
View Technologies in Oracle JDeveloper 10g 1-23
View: Summary 1-24
ADF Technology Stack 1-25
ADF: Summary 1-26
Summary 1-27

ADF Development Process


Objectives 2-2
Project Technology Scopes 2-3
ADF Technology Stack 2-4
A Sample Application 2-5
Building an Application 2-6
Application Workspaces 2-7
Application Workspace Templates 2-8

iii

Creating an Application Workspace 2-9


New Application Workspace 2-10
Design the Business Services for the Model: ADF Business Components 2-11
Design the Application Page Flow 2-13
Create the Page Flow 2-14
Create JSP Pages 2-15
Using the Visual Editors 2-16
Databinding: Example 2-17
Adding HTML to Enhance the User Interface 2-18
Results 2-19
Summary 2-20
Practice 2-1: Overview 2-21
3 Getting Started with ADF Business Components
Objectives 3-2
ADF Technology Stack 3-3
What Are ADF Business Components? 3-4
ADF Business Components 3-5
Benefits of ADF Business Components 3-6
Business Components 3-7
Business Domain Components 3-8
Data Model Business Components 3-9
Business Components Model 3-10
Building a Business Components Model 3-11
Creating a Database Connection 3-12
Creating ADF Business Components: Entity Objects 3-13
Creating ADF Business Components: View Objects 3-16
Creating Custom Views 3-18
Selecting the Attributes 3-19
Creating an Application Module 3-20
Testing the Business Components 3-21
Summary 3-22
Practice 3-1: Overview 3-23
4 Building Business Logic
Objectives 4-2
Business Logic Validation 4-3
Implementing Validation in the Business Services Tier 4-4
Entity Object: Overview 4-5
Entity Object 4-6
Creating an Entity Object 4-7
Entity Object Wizard 4-8
Files Generated for the Customers Entity Object 4-9

iv

Optional Files Generated for the Customers Entity Object 4-10


Using the Business Components Modeler for Entity Objects 4-11
Assigning an Initial Value to an Entity Attribute 4-13
Mapping an Attribute to a Database Sequence 4-14
Practice 4-1: Overview 4-15
Practice 4-1 4-16
Adding Validation 4-19
Declarative Validation Rules 4-20
ListValidator: Example 4-21
Adding UniqueKeyValidator to an Entity 4-22
Domains 4-23
Domains: Example 4-24
How to Create a Domain 4-25
How to Use a Domain 4-26
Summary 4-27
Practice 4-2: Overview 4-28
5

Exposing Business Data


Objectives 5-2
View Object in the ADF Architecture 5-3
Overview 5-4
View Objects 5-5
Interaction Between Views and Entities: Retrieving Data 5-6
Interaction Between Views and Entities: Updating Data 5-7
Synchronization of View Objects 5-8
Creating a View Object Using the View Object Wizard 5-9
Classes Related to View Objects 5-10
Files Generated for the LineItemView View Object 5-11
Example of a View Object 5-12
Practice 5-1: Overview 5-13
Practice 5-1 5-14
Calculated Attributes in Views 5-17
View Links 5-18
Traversing Links 5-19
Using the Business Components Modeler for View Objects (I) 5-20
Using the Business Components Modeler for View Objects (II) 5-21
Application Module in the ADF Architecture 5-22
Application Modules 5-24
Creating an Application Module Using the Application Module Wizard 5-25
Using the Business Components Modeler for an Application Module (I) 5-26
Using the Business Components Modeler for an Application Module (II) 5-27
Summary 5-28
Practice 5-2: Overview 5-29

Adding Custom Validation


Objectives 6-2
Overview 6-3
Adding Validation to an Entity 6-4
Validating Attributes 6-5
Creating a MethodValidator for an Attribute 6-6
Utilizing Typesafe Methods 6-8
Validating Entity Objects 6-9
Call EntityImpl Methods 6-11
Validation Order 6-12
Associations 6-13
Association Example 6-15
Accessor Methods 6-16
Association Types 6-17
Determining the Association Type 6-18
Creating Entity Associations 6-19
Traversing Associations: Destination to Source 6-23
Traversing Associations: Source to Destination 6-24
Summary 6-25
Practice 6-1: Overview 6-26

Providing for Efficient Queries


Objectives 7-2
Overview 7-3
Expert Mode View Objects 7-4
Mapping Attributes in Expert Mode 7-5
Maintaining Attribute Mappings in Expert Mode 7-6
SQL-Based View Objects 7-7
Creating a SQL-Based View Object 7-8
Implementing Custom Methods 7-9
Expose Methods to the Client Application 7-10
Creating a Test Client 7-11
Instantiating an Application Module 7-12
Instantiate a View Object and Output Data 7-13
Calling Custom Methods 7-14
Setting Parameters for the Where Clause 7-15
Assigning Values to Queries with Parameters at Run Time 7-17
Creating a Test Client Sample Code 7-18
Creating a View Object at Run time 7-20
Finding Data by a Row Key 7-22
Summary 7-23
Practice 7-1: Overview 7-24

vi

Making the Model Secure


Objectives 8-2
Goals of J2EE Security Architecture 8-3
Overview of J2EE Security Architecture 8-4
Java Authentication and Authorization Services 8-5
JDeveloper, JAAS, and Securing the ADF Model 8-8
Enabling JAAS Authentication for ADF Business Components 8-9
The jbo.security.enforce Application Property 8-10
Setting Entity Permissions 8-11
Entity Privileges 8-12
Attribute Permissions 8-13
Using the Business Components Browser 8-14
Testing Entity and Attribute Authorization 8-15
Summary 8-16
Practice 8-1: Overview 8-17

Controlling an Application with Struts


Objectives 9-2
The Controller 9-3
ADF Implements MVC Using the Struts Controller 9-4
Purpose of a Controller 9-5
Example: Page Flow Without a Controller 9-6
Example: Page Flow with a Controller 9-10
What Is Struts? 9-12
Struts Components 9-13
Struts Components Flow 9-15
Struts Components: The Controller Servlet 9-16
Struts Components: The Configuration file 9-17
Struts Components: Actions 9-18
Struts Components: ActionForms (Form Beans) 9-19
Struts Components: Tag Libraries 9-20
Application Resources File 9-21
Internationalizing Your Application 9-22
Struts in Oracle JDeveloper 10g 9-23
Struts Configuration File 9-24
Defining the struts-config.xml File Content 9-25
Creating a Page Flow Diagram 9-28
Struts Components: Actions 9-29
Struts Components: Pages and Page Forwards 9-30
Struts Components: Forwards and Links 9-31
ADF Components: DataAction and DataPage 9-32
Summary 9-33
Practice 9-1: Overview 9-34

vii

10 Building ADF View Components


Objectives 10-2
What Is a JSP? 10-3
JavaServer Pages in ADF 10-4
Example: JSP 10-5
Basic JSP Elements 10-6
JSP Directives 10-7
JDeveloper and JSPs 10-10
The Visual Editor 10-11
What Are Custom Tags? 10-12
Utilizing Tag Libraries 10-13
JSP Standard Tag Library 10-14
Struts Tags 10-15
Data Binding Tags 10-16
Utilizing the Data Control Palette 10-17
How Data Is Displayed 10-18
View Object Control Types 10-19
View Object Item Control Types 10-20
Operations 10-21
Customizing Controls 10-22
JSP Versus UIX 10-23
Summary 10-24
Practice 10-1: Overview
11 Customizing Actions
Objectives 11-2
Struts Configuration File 11-3
Creating the Action Class 11-4
Default Code of an Action 11-5
Forwards 11-6
ActionForward of an Action Class 11-7
Creating Global Forwards 11-8
Form Beans 11-9
Creating a Static Form Bean 11-11
Example: Static Form Bean 11-12
Dynamic Form Beans 11-13
Creating a Dynamic Form 11-14
Using the Bean in an Action 11-15
Sample Page Flow 11-16
Sample Page Flow: Struts Elements 11-17
Sample Page Flow: Form Bean 11-19
Sample Page Flow 11-21
Sample Page Flow: Action Class 11-22

viii

Sample Page Flow 11-23


Form Beans, Data Actions, and Data Pages 11-24
Summary 11-25
Practice 11-1: Overview 11-26
12 Using ADF Struts Components
Objectives 12-2
What Are Data Actions? 12-3
What Are Data Pages? 12-4
Utilizing Data Pages 12-5
Creating Data Pages 12-6
Creating the View Component 12-7
Displaying Data 12-8
Modifying the Iterator 12-10
Adding Methods to Data Actions 12-11
Adding Methods to Data Pages 12-12
Navigating in Data Pages 12-13
Data Action Life Cycle 12-14
The Data Action Lifecycle 12-15
Customizing Data Actions 12-16
Data Action Events 12-17
on<Event> Example: Built-in Events 12-19
on<Event> Example: Custom Events 12-20
Forwards and Events in ADF Applications 12-21
Summary 12-22
Practice 12-1: Overview 12-23
13 Adding Validation and Error Handling
Objectives 13-2
Overview of Validation 13-3
Need for Validation 13-4
Client-Side Validation 13-5
Form Bean Validation Method 13-6
Creating the Error Message 13-7
Printing Errors in the JSP 13-8
Validating Actions 13-9
Creating a Validation Class 13-10
The execute() Method 13-11
Validation Results 13-12
Struts Validator 13-13
Setting Up the Struts Validator 13-14
Utilizing the Struts Validator 13-15
validation.xml: Example 13-17

ix

Struts Validator Output 13-18


Exception Handling 13-19
JavaScript 13-20
Enhancing the View 13-21
Summary 13-22
Practice 13-1: Overview 13-23
14 Enhancing the User Interface
Objectives 14-2
Modifying Visual Component Properties 14-3
Using the Toolbar to Format Objects 14-4
Using the Property Inspector 14-5
Adding Images to JSPs 14-6
Using Style Sheets 14-7
Editing Default Style Sheets 14-8
Creating a New Style Sheet 14-9
Editing Style Sheets 14-10
Adding a Style Sheet to the
Component Palette 14-11
Applying a Style Sheet to a Page 14-12
Adding Buttons to a JSP 14-13
Adding Data Control Buttons 14-14
Adding Navigation Buttons 14-15
Adding Form Action Buttons 14-16
Supplementing Button Functionality 14-17
Using Expression Language 14-18
Using EL Attributes 14-19
Using EL Literals and Operators 14-20
Using EL Implicit Objects 14-21
Using EL to Customize a Page 14-22
Summary 14-23
Practice 14: Overview 14-24
15 Adding JAAS Security to the Client
Objectives 15-2
JAAS Provider 15-3
Defining Security Needs 15-4
Oracle JAAS Implementation: JAZN 15-5
Client Authentication 15-6
Client Authorization 15-7
Basic Authentication Scenario 15-8
Adding JAAS Security to an Application 15-9
Adding Authorization Information to Struts 15-10

web.xml Properties 15-11


web.xml Results 15-12
Adding Users and Roles 15-13
Adding Users 15-14
Managing Roles 15-15
Selecting a Specific jazn-data.xml File 15-16
Running the Application 15-17
Summary 15-18
16 Building ADF UIX View Components
Objectives 16-2
Why ADF UIX Technologies? 16-3
What are ADF UIX Technologies? 16-4
How Do ADF UIX Technologies Work? 16-5
UIX XML Page Layout 16-6
Interface Nodes 16-7
How Is It coded? 16-8
Support for Internationalization 16-9
User Interface Components 16-10
Modular Declarative Design 16-11
Creating a UIX XML Page 16-12
Company and Product Branding 16-13
Page Tabs 16-14
Global Buttons 16-15
Page Footers 16-16
Designing with the Visual Editor 16-17
Coding with the XML Editor 16-18
UIX XML Page at Run Time 16-19
Adding Data to the Page 16-20
Design Time Data Components 16-21
Data Binding in the Visual Editor 16-22
Run-Time UIX XML Page with Data Binding 16-23
Summary 16-24
Practice 16: Overview 16-25
17 Deploying an ADF Application
Objectives 17-2
Overview 17-3
Overall Considerations for Deployment 17-4
J2EE Archive Format 17-5
Deploying to a Web Server 17-6
Deploying to OC4J 17-7
Install OC4J 17-8

xi

Start the OC4J Server 17-9


Creating an OC4J Connection 17-10
Creating a Deployment Profile 17-12
Deploying to OC4J 17-13
Running Applications 17-14
Customizing Deployment 17-15
Summary 17-16
Practice 17-1: Overview 17-17
Appendix A: Course Schema
Appendix B: Practice Solutions

xii

Customizing Actions

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Practice
Total

Timing
60 minutes
30 minutes
90 minutes

Objectives

After completing this lesson, you should be able to


do the following:
Describe the Struts XML elements and structure
Describe the anatomy of an action
Use the execute method to enhance the behavior
of an action
Describe the use of form beans
Use a dynamic form bean

11-2

Copyright 2004, Oracle. All rights reserved.

Objectives
In this lesson, you learn more about Struts components in order to create applications that use the
Struts framework to validate user input from an HTML form. You also learn how to create
applications that contain label references, so that labels can be populated at run time based on the
language settings of the clients browser.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-2
Oracle10g
Forms Developer:
Build
Internet Applications
11-2

Struts Configuration File

Is XML type file


Is the application resource descriptor
Is used by the servlet to determine actions to
perform
<struts-config>
<action-mappings>
<action path="/action1"/>
<forward name="success" path="/page1.do"/>
</action>
</action-mappings>
<message-resources
parameter="view.ApplicationResources"/>
</struts-config>

11-3

Copyright 2004, Oracle. All rights reserved.

Struts Configuration File


As you have already learned, the Struts Configuration file is the road map of the application.
This is where the logical flow of the application is defined by using XML syntax. It describes
Form Beans, Actions, ActionMappings, resource bundles, data sources, and other parameters.
Note that you can create one or more configuration files per application. However, by default,
JDeveloper creates one configuration file named struts-config.xml. The name and
location of the file are specified in the web.xml file for the application.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-3
Oracle10g
Forms Developer:
Build
Internet Applications
11-3

Creating the Action Class

In the context menu, select Go to Code.


Or, double-click the action.
Specify a name for the action.

/auth

11-4

Copyright 2004, Oracle. All rights reserved.

Creating an Action
An action is an adapter between the contents of an incoming HTTP request and the
corresponding business logic that should be executed to process this request. The action package
is the core of the Struts framework, representing the controller layer of a Model-View-Controller
(MVC) model. All actions are subclassed from org.apache.struts.action.Action.
The XML definition of an action in the struts-config.xml file is:
<action path="/authUser" type="view.AuthUserAction"/>
The path name appearing on the Page Flow Diagram is a logical name, where the name specified
in the Create Struts Action dialog box is the physical name.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-4
Oracle10g
Forms Developer:
Build
Internet Applications
11-4

Default Code of an Action

public class AuthUserAction extends Action


{
/* This is the main action called from the Struts
framework.*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
return mapping.findForward("success");
}
}

11-5

Copyright 2004, Oracle. All rights reserved.

Default Java Code of an Action


When creating an action, JDeveloper generates Java code as shown above.
In this example, AuthUserAction extends the Struts action class. The execute()
method is where you add your own code for customization, and then return an
ActionForward (also called a page forward) to continue the flow of the application.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-5
Oracle10g
Forms Developer:
Build
Internet Applications
11-5

Forwards
success

Forwards can be defined:


By using the Page Flow
Diagram
/authUser
In the XML file
failure
In the Structure pane

/page1

/page2

<action path="/authUser"
type="view.AuthUserAction">
<forward path="/page1.do" name="success"/>
<forward path="/page2.do" name="failure"/>
</action>

11-6

Copyright 2004, Oracle. All rights reserved.

Forwards
Forwards control the flow of an application. One or more forwards are generally defined within
the <action> element in the XML and these, along with any global forwards (defined in the
<global-forwards> section of the XML), are valid places for that action to forward to.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-6
Oracle10g
Forms Developer:
Build
Internet Applications
11-6

ActionForward of an Action Class

The return parameter from ActionForward


specifies where to send control.
The default naming of a single forward is
success.
The execute() method can be customized:
Additional code can be added.
Other forwards can be specified.
Appropriate forward is done on conditional testing.

The forward name represents a logical name.


A forward can also be a global forward.

11-7

Copyright 2004, Oracle. All rights reserved.

ActionForward
The programmer has to return a reference to a forward from the execute() method in the
action. This is done by using the findForward() method, which accepts the name of the
forward to return to.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-7
Oracle10g
Forms Developer:
Build
Internet Applications
11-7

Creating Global Forwards

A global forward is just like any forward, but it can


be accessed by any action.
The global forward is defined in the config file.
<global-forwards>
<forward name="help" path="/help.do"/>
</global-forwards>

The global forward is specified in the action class.


return mapping.findForward("help");

11-8

Copyright 2004, Oracle. All rights reserved.

Global Forwards
A global resource, such as a global forward or a global exception, can be used at any time by any
resource.
The links to a global forward are not represented on the page flow.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-8
Oracle10g
Forms Developer:
Build
Internet Applications
11-8

Form Beans

Logon

User Name
Password
Logon

Submit
authUser
Populates

logonBean
menu

11-9

Copyright 2004, Oracle. All rights reserved.

Form Beans
Form beans are associated with one or more actions. When a page is submitted to the action, the
Struts controller matches parameters from the request object with fields in the form bean class
and populates the bean.
The developer is passed the form bean reference as a parameter to the execute() method of
the action class, and the values are accessible through get() methods. This saves the developer
from having to query the request. More importantly, the bean can be populated before a page is
displayed and the fields in the page are prepopulated with the relevant fields from the bean that
match the field names in the HTML formso the process works both ways.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-9
Oracle10g
Forms Developer:
Build
Internet Applications
11-9

Form Beans

A form bean is used to transport data between a


page and an action.
Can be static:
Is defined in a FormBean class
Contains set(), get(), and reset() methods for
each field
Contains a validate() method for verifying user
input

Can be dynamic:
Each field specified in struts.config.xml
Does not require Java code

11-10

Copyright 2004, Oracle. All rights reserved.

Form Beans (continued)


You can create static beans, which are your own JavaBeans that extend the ActionForm
class and have getters and setters for each field that you want to support. Or, you can do the
declaration in the Struts XML by using a dynamic bean called DynaActionForm, and without
writing code.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-10
Oracle10g
Forms Developer:
Build
Internet Applications
11-10

Creating a Static Form Bean

Create an action in the Page Flow Editor.


Right-click and select Go to Form Bean.
Specify a name (suffix the name with Form).

/authUser

A new icon is displayed.


/authUser

11-11

Copyright 2004, Oracle. All rights reserved.

Creating a Form Bean


The example above illustrates the creation of a static form bean. This is specified in the
struts-config.xml file as:
<form-bean name="DataForm" type="view.AuthUserActionForm"/>
The main advantage of using the static form bean is that you can write custom validation code to
check the user input and reset code to initialize the bean. If you do not need these features, then a
dynamic bean is the best.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-11
Oracle10g
Forms Developer:
Build
Internet Applications
11-11

Example: Static Form Bean

public class AuthUserActionForm extends ActionForm


{
String username;
public String getUsername()
{ return username; }
public void setUsername(String newUsername)
{ username=newUsername; }
public void reset(
public ActionErrors validate(
}

11-12

Copyright 2004, Oracle. All rights reserved.

Example: Static Form Bean


In this example, the static bean contains an attribute named username, and contains a get and
set method for the attribute. Note that if the validate() method throws an error, the error is
automatically displayed in the JavaServer Page (JSP) that called the page, assuming that the
Struts tag <html:errors/> exists in the page.
The developer is passed the form bean reference as a parameter to the execute() method of
the action class. The values are accessible through get() methods. This saves the developer
from having to query the request. More importantly, the bean can be populated before a page is
displayed, and the fields in the page are prepopulated with the relevant fields from the bean that
match the field names in the HTML formso the process works both ways.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-12
Oracle10g
Forms Developer:
Build
Internet Applications
11-12

Dynamic Form Beans

11-13

This is an alternative way for an action to have


access to incoming fields from a page.
The form bean class is not needed.
There is no need for getter and setter methods.
The field names are specified in the strutsconfig.xml file.
New fields can be added dynamically.

Copyright 2004, Oracle. All rights reserved.

Dynamic Form Beans


The dynamic version of a form bean is defined by using the correct type
(org.apache.struts.action.DynaActionForm) in the struts-config.xml file
and then creating one <form-property/> tag per field in the dynamic bean class. You can
also define an initial value for each of these fields. There is no bean-level validation with a
dynamic bean. To include bean-level validation, use the execute() method of the action.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-13
Oracle10g
Forms Developer:
Build
Internet Applications
11-13

Creating a Dynamic Form

1. Create a form bean from the Structure pane.


2. Specify
org.apache.struts.action.DynaActionForm
as the type for the bean.
3. Create a new form property for each field.
<form-bean name="logonBean"
type="org.apache.struts.action.DynaActionForm">
<form-property name="username" type="java.lang.String"/>

11-14

Copyright 2004, Oracle. All rights reserved.

Creating a Dynamic Form


To create a dynamic action form from the Page Flow Diagram, right-click the action, select Go
to Code, and specify a name. Then, specify the type for the bean as
org.apache.struts.action.DynaActionForm, and create a <form-property>
element for each field in the form.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-14
Oracle10g
Forms Developer:
Build
Internet Applications
11-14

Using the Bean in an Action

Using a static bean:


Create and cast the ActionForm type
Use the getXxx() method
AuthUserActionForm authForm = (AuthUserActionForm) form;
String username=authForm.getUsername();

Using a dynamic bean:


Cast the form object passed to the execute()
method to a DynaActionForm type
String
username=(String)((DynaActionForm)form).get("username");

11-15

Copyright 2004, Oracle. All rights reserved.

Using the Bean in an Action


The bean allows your action class to have access to the input fields. In the static bean, the
username is retrieved by using the getUsername() method. In the dynamic bean, the
username is retrieved by casting the username object to a DynaActionForm type.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-15
Oracle10g
Forms Developer:
Build
Internet Applications
11-15

Sample Page Flow

Logon

failure
authUser
success

<action-mappings>
<action path="/logon
forward="/logon.jsp"/>
<action path="/authUser"
name="logonBean"
type="view.AuthUserAction">
<forward
path="/logon.do
name="failure"/>
<forward
path="/menu.do
name="success"/>
</action>
<action path="/menu"
forward="/menu.jsp"/>
</action-mappings>

menu

11-16

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow


The next few slides illustrate the flow between two page forwards and an action, which validates
a user.
The information from the logon page is submitted to the authUser action. If the password is
invalid, the user is redirected to the logon page. If the password is valid, the menu page for the
application is displayed.
The XML for these three actions is shown here. (Each page in this case is being represented by a
PageForward. Note that the two forwards success and failure are the possible routes out of
the authUser action.)

Oracle JDeveloper
10g: Build
Applications
with ADF 11-16
Oracle10g
Forms Developer:
Build
Internet Applications
11-16

Sample Page Flow: Struts Elements


<action-mappings>
<action path="/logon
forward="/logon.jsp"/>

Logon

failure
authUser
success

menu

11-17

<action path="/authUser"
name="logonBean"
type=" view.AuthUserAction ">
<forward
path="/logon.do
name="failure"/>
<forward
path="/menu.do
name="success"/>
</action>

<action path="/menu"
forward="/menu.jsp"/>
</action-mappings>

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow: Struts Elements


There are three main Struts components in this application:
1. logon: The logon action points to logon.jsp for the page definition. The forward
attribute points to the page. Thus, this component is a PageForward.
2. authUser: The logon page submits to the authUser action. This is defined in
logon.jsp by using the <html:form> tag. There are three attributes in the action
mapping:
- path: the name of the action
- name: the name of the form bean that is used
- type: the class for the action, which must subclass
org.apache.struts.action.Action
3. menu: The menu action points to menu.jsp for the page definition and is also a
PageForward component.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-17
Oracle10g
Forms Developer:
Build
Internet Applications
11-17

Sample Page Flow: Struts Elements


<action-mappings>
<action path="/logon
forward="/logon.jsp"/>

Logon

<action path="/authUser"
name="logonBean"
type=" view.AuthUserAction ">

failure
<forward
path="/logon.do
name="failure"/>

authUser
success

menu

11-18

<forward
path="/menu.do
name="success"/>
</action>
<action path="/menu"
forward="/menu.jsp"/>
</action-mappings>

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow: Struts Elements (continued)


The authUser action has two <forwards> that represent the possible flows from the action.
These forwards have a path attribute, which can point to another action or to an actual page or
some other URL.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-18
Oracle10g
Forms Developer:
Build
Internet Applications
11-18

Sample Page Flow: Form Bean


User Name

Logon

Password
Logon

failure

Submit

authUser
success
logonBean
menu

11-19

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow: Form Bean


When the user clicks the Logon button, the controller resolves that the target of the form on the
page is authUser.do (the .do extension tells the servlet container that this is a Struts
Action). Because the authUser action has an associated bean called logonBean (defined by
the name attribute), the controller looks for the bean class (static) or bean definition (dynamic)
named logonBean.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-19
Oracle10g
Forms Developer:
Build
Internet Applications
11-19

Sample Page Flow: Form Bean

Logon

failure

<form-beans>
<form-bean
name="logonBean
type="org.apache.struts.
action.DynaActionForm">

authUser
success

menu

11-20

<form-property
name="username"
type="java.lang.String"/>
<form-property
name="password"
type="java.lang.String"/>
</form-bean>
</form-beans>

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow: Form Bean (continued)


In this case, logonBean is a dynamic form bean. Thus, there is no class for the bean. Instead,
the bean is defined in the struts-config.xml file.
Here, the names of the <form-property> elements (which represent the fields in the bean)
match the names used for the input elements on the page. Thus, the controller can automatically
create the bean and populate it with the contents of those fields from the request.
Instructor Note
Ask the class how they can tell that this is a dynamic form bean. Answer: There are form
properties specified for the fields.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-20
Oracle10g
Forms Developer:
Build
Internet Applications
11-20

Sample Page Flow


User Name

Logon

Password
Logon

failure
authUser

Passed to

Submit

Populates

success
logonBean
menu

11-21

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow


The Struts servlet reads the request and looks at the metadata to create a bean populated with the
data out of the input fields in the page. Next, it calls the AuthAction class, which is defined
by the type attribute in the action definition, and passes the populated form bean to the
execute() method.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-21
Oracle10g
Forms Developer:
Build
Internet Applications
11-21

Sample Page Flow: Action Class

public ActionForward execute(ActionMapping mapping,


ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException
{
DynaActionForm LAF = (DynaActionForm) form;
String un = (String)LAF.get("username");
String pw = (String)LAF.get("password");
if (un.equals("Scott")) {
return mapping.findForward("success");
} else
return mapping.findForward("failure");
}

11-22

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow: Action Class


Generally, when you write a Struts action, you simply extend the base action and implement a
custom execute() method. The framework passes everything you need into that method,
including:
A reference to the Struts metadata (ActionMapping), so that you can resolve forwards
The populated form bean (static or dynamic)
A reference to the request (and, therefore, the session as well)
A reference to the response object, so that you can save further data, such as errors, for the
response.
In this case, the bean with the user-supplied username and password is passed into the
execute() method. The checkAuth method (not shown) performs the custom validation.
If the validation succeeds, findForward() is used to look up the next place to go based on
the success forward name. The reference to the failure forward is returned if the validation
fails.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-22
Oracle10g
Forms Developer:
Build
Internet Applications
11-22

Sample Page Flow


User Name

Logon

Password
Logon

failure
authUser

Passed to

Submit

Populates

success
logonBean
menu

11-23

Copyright 2004, Oracle. All rights reserved.

Sample Page Flow


Lastly, the Struts controller forwards the user to the required page or action, and the new page is
displayed in the browser. The simple page flow example is complete.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-23
Oracle10g
Forms Developer:
Build
Internet Applications
11-23

Form Beans, Data Actions, and Data Pages

ADF creates a form bean automatically when you


create:
Data actions
Data pages

The ADF Form Bean is called a DataForm.


DataForms do not require custom code:
No static form bean class is needed.
No dynamic form bean declaration is needed.

11-24

ADF uses these objects to manage form data.

Copyright 2004, Oracle. All rights reserved.

Form Beans, Data Actions, and Data Pages


Data actions and data pages use a specialized form bean for managing form data. This bean is
created automatically when you create a data action or data page. No further coding or
declaration is required, because ADF builds the form bean for you. This specialized form bean is
named DataForm.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-24
Oracle10g
Forms Developer:
Build
Internet Applications
11-24

Summary

In this lesson, you should have learned how to:


Describe the Struts XML elements and structure
Describe the anatomy of an action
Use the execute method to enhance the behavior
of an action
Describe the use of form beans
Use a dynamic form bean

11-25

Copyright 2004, Oracle. All rights reserved.

Summary
In this lesson, you should have learned the XML syntax for the content of the strutsconfig.xml file. Additionally, you should have learned about advanced Struts components,
such as actions and form beans, and how to support internationalization of a Struts application.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-25
Oracle10g
Forms Developer:
Build
Internet Applications
11-25

Practice 11-1: Overview

This practice covers the following topics:


Using the Page Flow Diagram
Adding data actions
Adding data pages
Creating form beans

11-26

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-26
Oracle10g
Forms Developer:
Build
Internet Applications
11-26

Practice 11-1
In this practice, you create a form bean to hold logon information. That logon information is
passed to an action that performs authentication and returns a customer name if the validation
succeeds.
Start JDeveloper, and open the practice11 workspace.
1. Create form beans.
a. Open the Page Flow Diagram.
b. In the Structure pane, create a new Form Bean.
c. In the Property pane, specify logonBean as the name and set the type to
org.apache.struts.action.DynaActionForm.
d. In the Structure pane, select the logon bean and create a new Form Property.
e. In the Property Inspector, set the name property to lastName and leave it as a
String.
f. Create a second Form Property for customerId (leave it as a String).
2. Create a new view object that validates the customer logon. This view object will accept
two parameters and query the customers table for a combination of both
customerLastName and customerId.
a. Create a view object. Name it AuthenticateView. Remember to create the view
object in the Model project.
b. Select customers as the entity object.
c. Select customerId, custFirstName, and custLastName as the attributes.
d. Add a WHERE clause that compares the upper of custLastName with the upper of
a parameter AND compares customerId with a second parameter.
SELECT Customers.CUSTOMER_ID,
Customers.CUST_FIRST_NAME,
Customers.CUST_LAST_NAME
FROM CUSTOMERS Customers
WHERE upper(Customers.CUST_LAST_NAME)= upper(?)
and Customers.CUSTOMER_ID= ?

e. Make sure to select the Use ? Style parameters check box if you are using the above
syntax.
f. In step 6 of 6, select the Generate Java File option for the View Row class.
g. Click Finish to validate.
h. Add the view to SalesAppModule and remove 1 from the instance name.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-27
Oracle10g
Forms Developer:
Build
Internet Applications
11-27

Practice 11-1 (continued)


3. Create a data action.
a. Open the Struts Page Flow Diagram.
b. Drag the Data Action icon next to the logon page.
c. Change the name to /authenticateUser.
4. Create a new method to validate customers logon by using the view you just created.
a. Select the SalesAppModule node in the Applications Navigator.
b. In the Structure pane, double-click the SalesAppModuleImpl.java node.
c. In the Source Editor, create a new method that has the following characteristics:
Its signature is:
public String

findCustomers(String lastName, String customerId)

(The return parameter is a string of FirstName and LastName concatenated.)


Note: The code for this method is at the end of this practice.
d. Import any classes necessary.
e. Compile the class, and correct any errors that you may have.
5. Make the method available to client applications.
a. Double-click SalesAppModule to open the Module Properties Wizard.
b. Select the Client Interface node.
c. Move the findCustomers method from Available to Selected, and click OK.
6. Add the method to the AuthenticateUser data action.
a. Open the Page Flow Diagram.
b. From the Data Control Palette, open the SaleAppModuleDataControl node.
c. Open the Operations node and select the findCustomers() method.
d. Drag the method to the authenticateUser data action.
7. Set the parameter properties of the data action.
a. In the Structure pane, open the /authenticateUser pane.
b. Select the paramNames[0] node.
c. In the Property Inspector, change the value key to
${sessionScope.lastName}.
d. Select the paramNames[1] node.
e. In the Property Inspector, change the value key to
${sessionScope.customerId}.
f. Select the resultLocation node.
g. In the Property Inspector, change the value key to
${sessionScope.customerName}.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-28
Oracle10g
Forms Developer:
Build
Internet Applications
11-28

Practice 11-1 (continued)


8. Associate the logon page to the data action.
a. Open the logon page.
b. Select the Source Editor.
c. Above the <table> tag, insert the following:
<form action="authenticateUser.do">
d. Close the form tag </form> after the </table> tag.
e. Remove the link to the categories page that you added in an earlier practice.
f. Right-click the logon page on the Page Flow Diagram, and select the Refresh
Diagram from Page option. A page link should appear between logon and
authenticateUser.
g. Create a forward going from authenticateUser to categories. The Struts diagram
should look something like the diagram below:

9. Run the application starting at the welcome page. Try to log on with the following values
of CustomerLastName and CustomerId:
Welles
101
Pacino
102
Taylor
103
10. You will enhance this validation in a later practice.

Oracle JDeveloper
10g: Build
Applications
with ADF 11-29
Oracle10g
Forms Developer:
Build
Internet Applications
11-29

Practice 11-1 (continued)


SalesAppModuleImpl.java
public String findCustomers(String lastName, String
customerId)
{
ViewObjectImpl vo = this.getAuthenticateView();
vo.setWhereClauseParam(0,lastName);
vo.setWhereClauseParam(1,customerId);
vo.executeQuery();
AuthenticateViewRowImpl row =
(AuthenticateViewRowImpl)vo.first();
String customerName = null;
if (row != null)
{
customerName = row.getCustFirstName() + " " +
row.getCustLastName();
}
return customerName;
}

Oracle JDeveloper
10g: Build
Applications
with ADF 11-30
Oracle10g
Forms Developer:
Build
Internet Applications
11-30

Using ADF Struts Components

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Practice
Total

Timing
30 minutes
45 minutes
75 minutes

Objectives

After completing this lesson, you should be able to do


the following:
Describe data actions and data pages
Customize data actions and data pages to
enhance the behavior of an application
Use data actions to access multiple types of
business services
Describe the relationship between databound
pages and data pages

12-2

Copyright 2004, Oracle. All rights reserved.

Objectives
Databound applications that contain Oracle ADF business services are created by using data
actions. This lesson discusses how data actions are created, customized, and utilized in a
databound application.

Oracle JDeveloper 10g: Build Applications with ADF 12-2

What Are Data Actions?

Data actions are an extension of the action class,


which:
Are provided with Oracle ADF
Provide access to business services, such as
business components
Prepare the data and make it available for pages to
consume

12-3

Copyright 2004, Oracle. All rights reserved.

What Are Data Actions?


Data actions are an extension of the Struts Action class. By default, they provide access to
business services, such as view object business components. Data actions are created in the
Struts Page Flow Diagram and customized by using the Data Control Palette, Structure pane, and
Property Inspector.

Oracle JDeveloper 10g: Build Applications with ADF 12-3

What Are Data Pages?

Data pages are an extension of the DataAction class,


which:
Are provided with Oracle ADF
Combine a data action and a page forward
Do not rely on forwards to forward application
data
Simplify the Page Flow Diagram

12-4

Copyright 2004, Oracle. All rights reserved.

What Are Data Pages?


Data pages are an extension of the DataAction class. They are a combination of a data action
and page forward. For example, if you have a customer view object and want to create a new
customer, you can create a data action based on Customers and a page forward based on the
same Customers view. Alternatively, you can create a data page based on the Customers
view and you have all the benefits of having the data controlled by a Struts controller
component, but with half the number of components.

Oracle JDeveloper 10g: Build Applications with ADF 12-4

Utilizing Data Pages

To use a data page, perform these steps:


1. Create the data page in the Page Flow Diagram.
2. Double-click to create the corresponding view
object (JSP, HTML, and UIX).
3. Define the Struts page flow as necessary.
4. Add business service methods to the data page as
necessary.

12-5

Copyright 2004, Oracle. All rights reserved.

Utilizing Data Pages


To utilize a data page, create it in the Page Flow Diagram. Next, create the corresponding view
component by double-clicking the data page. Next, define the Struts page flow further if
necessary. For example, a browse form may have a link to an insertion form. Then, add methods
as necessary to the data page. These steps are discussed in detail in the slides that follow.

Oracle JDeveloper 10g: Build Applications with ADF 12-5

Creating Data Pages

Drag a data page to /browseCustomer


the Page Flow
Diagram.
The strutsconfig.xml file is
updated with the
data action.
<action-mappings>
<action path="/browseCustomers"
className="oracle.adf.controller.struts.actions.DataActi
onMapping"
type="oracle.adf.controller.struts.actions.DataForwardAc
tion" name="DataForm" parameter="unknown"/>
</action-mappings>

12-6

Copyright 2004, Oracle. All rights reserved.

Creating Data Pages


To create a data page in your application, drag a data page from the Component Palette to the
Page Flow Diagram. The struts-config.xml file is updated automatically. Note that the
data page extends
oracle.adf.controller.struts.actions.DataForwardAction. In this case, a
data action for browsing the customers view object has been created. The page has not been
associated with a JavaServer Page (JSP) yet, so the data page icon has a caution symbol on the
Page Flow Diagram, and the parameter attribute is unknown. The name parameter is not the
name of the data page, but the name of the form bean used to transport data between the
controller and the view. The DataForm bean specified is the generic ADF bean that is
automatically generated. The next step is to create the JSP that displays the data.

Oracle JDeveloper 10g: Build Applications with ADF 12-6

Creating the View Component

Double-click the data page to create


the view component.
/browseCustomer
<action-mappings>
<action path="/browseCustomers"
className="oracle.adf.controller.struts.actions.DataActi
onMapping"
type="oracle.adf.controller.struts.actions.DataForwardAc
tion" name="DataForm" parameter="/browseCustomers.jsp">
<set-property property="modelReference"
value="browseCustomersUIModel"/>
</action></action-mappings>

12-7

Copyright 2004, Oracle. All rights reserved.

Creating the View Component


Double-click to create the view component. By default, the name of the data page is used as the
file name, with a .jsp extension, but this can be any view component. The parameter attribute is
updated to show the corresponding view component /browseCustomers.jsp. Additionally,
the modelReference property is set to browseCustomersUIModel, which is the name of the
file that the data page uses to initialize data and methods. The file is not created until data
controls are added to the view component.

Oracle JDeveloper 10g: Build Applications with ADF 12-7

Displaying Data

To display data from the data page, add elements from


the Data Control Palette:
Bound Data
Navigation
Operations
The data controls associated with the data action are
defined in DataBindings.cpx (created automatically).

12-8

Copyright 2004, Oracle. All rights reserved.

Displaying Data
The next step in utilizing data pages is to develop the JSP that contains the bound data. Utilize
the Data Control Palette to add data, navigation, and operations to the JSP. Note that the first
time you add a data control to the page, the mappings for all data controls are automatically
generated and contained in DataBindings.cpx.

Oracle JDeveloper 10g: Build Applications with ADF 12-8

Displaying Data

Select elements from the Data Control Palette and drag


them to the page:

Generated code
<c:forEach var="Row"
items="${bindings.CustomersView1.range
Set}">
<tr><td>
<c:out value="${Row.CustomerId}">
</c:out></td>
12-9

Copyright 2004, Oracle. All rights reserved.

Displaying Data (continued)


To display data bound to a view object, select the view or attribute that you want to add to the
page, and select the appropriate Drag and Drop As value. In this example, a table for browsing is
desired, so the CustomersView data control is dragged as a read-only table to the
browseCustomers.jsp. This is exactly the same procedure as you have seen in a previous
lesson. Note that for each page you bind data to, a UIModel.xml file is created to map the
attributes. This uses the name defined in the modelReference property value for the data
page.

Oracle JDeveloper 10g: Build Applications with ADF 12-9

Modifying the Iterator

Click the UIModel icon in the Structure pane to locate


the iterator for the model. Then use the Property
Inspector to change the range size.

12-10

Copyright 2004, Oracle. All rights reserved.

Modifying the Iterator


To modify the range size of the iterator, locate it by using the UIModel tab of the Structure pane.
You can then set the range size of the iterator as necessary in the Property Inspector. The iterator
provides access to a set of rows within a view object.
Instructor Note
If you set the range size to 1, the iterator returns the entire rowset. The default value is 10.

Oracle JDeveloper 10g: Build Applications with ADF 12-10

Adding Methods to Data Actions

To perform DML with data actions, add methods to the


data action:
Drag to
data page icon
/browseCustomer

/addCustomer

<action path="/addCustomers"

<set-property property="methodName"
value="addCustomersUIModel.Create"/>
</action>

12-11

Copyright 2004, Oracle. All rights reserved.

Adding Methods to Data Actions


To create a new Customer row, add the create operation of the CustomersView data control
to the /addCustomers data page. Other methods that are used frequently in Web applications
include setting the current row for a delete or edit action, deleting a row, and finding a row based
on an ADF business component row ID. The next slide displays each type of data control
operation and how it is created in a typical Web application.

Oracle JDeveloper 10g: Build Applications with ADF 12-11

Adding Methods to Data Pages

Drag and drop methods from the


Data Control Palette to add
methods to a data page:
Create

setCurrentRowWithKey

Delete

12-12

Copyright 2004, Oracle. All rights reserved.

Adding Methods to Data Pages


As shown in the slide, the setCurrentRowWithKey method is added to the
/editCustomers data page to enable the data page to display only the currently selected
row. This method is also used to set the currency of the row before deleting the row.
A row is selected in the /browseCustomers data page by using a Select Row link, which
passes the current rows key to a linked page or action. Additionally, the create and delete
methods are used as indicated, for creating new rows and deleting a selected row.

Oracle JDeveloper 10g: Build Applications with ADF 12-12

Navigating in Data Pages

HTML Form tag submits to itself, by default.


Change the action to the page that receives the
form data.
Use the Property Inspector to change the value of
action.
Select the data page or
action that receives the
form data.

12-13

Copyright 2004, Oracle. All rights reserved.

Navigating in Data Pages


When you draw a link between pages, you define where the page goes next. However, when you
create an input form by dragging a view object, the form is coded by default to submit to the
same page on which it resides. Thus, this must be changed to enable application flow. Change
the value of the action attribute in the Property Inspector to specify the receiving data page or
data action.

Oracle JDeveloper 10g: Build Applications with ADF 12-13

Data Action Life Cycle


1. Initialize context
Get HTTP request

Get binding info

2. Build event list

8. Invoke custom methods

3. Check for model bindings

9. Refresh binding controls

4. Check if updates allowed

10. Dispatch to forward

5. Process updates
6. Validate updates
7. Handle model and UI events

12-14

Copyright 2004, Oracle. All rights reserved.

Data Action Life Cycle


1. Initialize context. The first step handleLifecycle() performs is to initialize the
context. In a Model 1 application, the context is an instance of
oracle.adf.controller.lifecycle.LifecycleContext. In a Struts
application, the context is an instance of
oracle.adf.controller.struts.actions.DataActionContext, a
subclass of LifecycleContext. In either case, handleLifecycle() calls the lifecycle context initialize method. This sets the value of the associated request, binding
container, and life cycle in the context.
2. Build event list. Next, handleLifecycle() builds the list of events to be performed
by retrieving them from the request object with the life-cycle method
buildEventList().

Oracle JDeveloper 10g: Build Applications with ADF 12-14

Data Action Life Cycle (continued)


3. Prepare model data bindings if they exist. At this point, handleLifecycle() checks
for model data bindings by calling getAttribute("bindings") on the binding
container retrieved in step 1. If model data bindings exist, this phase of the life cycle
prepares the data model to receive possible updates from the request. This phase also
validates the state token. For information about the state token, see Working with
Validation in ADF Clients. Note that a life cycle may not have associated model bindings.
Instead, the life cycle can call events that operate only in the user interface. You may want
to call custom page navigation events that do not use data bindings. For example, you may
want to create an event associated with a Help button that takes the user to an HTML page
for the Web application. If there are no associated model bindings,
handleLifecycle() skips to step 7.
4. Check to see whether model updates are allowed. Some events should not be allowed to
update the model. If the event is performing a rollback on data changes, for example, you
do not allow model updates. The handleLifecycle()method calls
shouldAllowModelUpdate() on the life cycle to see whether model updates are
allowed. If the user is allowed to update model data from the user interface,
handleLifecycle() goes to the next step. If model updates are not allowed,
handleLifecycle() skips to step 7.
5. Process model updates. At this point, handleLifecycle() collects the new data
values from the request and updates the model with them.
6. Validate model updates. At this point, handleLifecycle() validates updates to the
model by calling validateInputValues() on the binding container associated with
the current life cycle.
7. Handle model and UI events. Next, handleLifecycle() calls
processComponentEvents() on the life cycle. This method handles both named
events, which you create and name yourself, and events tied to the data bindings that you
drop on a page (action bindings). For more information about creating your own named
events, see Working with Named Events in Oracle ADF.
8. Invoke custom methods (Struts only). In a Struts application only, you can drag methods
to an action, data action, or data page without having to subclass the parent class.
handleLifecycle()calls invokeCustomMethod() on the life cycle to execute
these custom methods at this point. For more information, see Executing Business Service
Methods with a Data Action.
9. Refresh binding controls. This step notifies the binding container associated with the
current life cycle that all model updates for the action or page are complete. At this point,
handleLifecycle() calls refreshControl() on the binding container.
10. Dispatch to Forward. At this point, handleLifecycle() calls the
findForward() method on the life cycle. For Struts applications, findForward()
looks for the value of the <forward> element in the struts-config.xml file, which it
passes to the execute method of the action class or subclass. For Model 1 applications, this
method looks for the forward path in the context and dispatches directly to the new page.

Oracle JDeveloper 10g: Build Applications with ADF 12-15

Customizing Data Actions

Data action methods may be customized to provide


functionality for:
A data action having two possible forwards:
protected ActionForward findForward() {
Object s = request.getParameter("Update");
if (s != null) {
return getActionMapping().findForward("success");
} else
return getActionMapping().findForward("browse"); }

Any custom functionality:


Protected void invokeCustomMethod(DataActionContext ac) {

12-16

Copyright 2004, Oracle. All rights reserved.

Customizing Data Actions


In addition to the methods from the Data Control Palette, there are methods in the data action
class which may be overridden. To create custom data actions, utilize the findForward() or
invokeCustomMethod() methods. findForward() is useful for creating functionality,
which checks which page the user navigated from and, thus, which page to send to the client
next. Any other custom functionality can be created in invokeCustomMethod(). Both
methods are available by double-clicking the data action in the Page Flow Diagram to subclass
the data action, as shown below.

Oracle JDeveloper 10g: Build Applications with ADF 12-16

Data Action Events

Built-in operations are listed in the UIModel.xml file:

Defined by:
Dragging operation from the Data Control Palette
Explicit creation in the Structure pane

Invoked by:
Button with the name event_<operation>,
for example, event_Commit.
Hyperlink with a parameter event=< operation>,
for example, event=Commit.

12-17

Copyright 2004, Oracle. All rights reserved.

Data Action Events


Built-in operations are the operations such as next, last, insert, and so on, which are available for
an iterator and which can be dragged to a page as a button.
When you drag an operation to a page, a name is generated for the button, which is prefixed with
the string event_, followed by the name of the operation itself.
Events can also be passed as hyperlinks by using the URL parameter event=, again followed
by the name of the event.
This means that you can add hyperlinks on a JSP that trigger events. You can also add buttons to
a page by dragging operations from the Data Control Palette.

Oracle JDeveloper 10g: Build Applications with ADF 12-17

Data Action Events

Using built-in events, you can define your own


operations:
Defined by:

Invoked by:

12-18

Coding an on<CustEvent>() method in the data


action
Button with the name event_<CustEvent>,
for example, event_Help.
Button with the name event and value
<CustEvent>,
for example, name=event value=Help.
Hyperlink with a parameter event=< operation>,
for example, event=Commit.
Copyright 2004, Oracle. All rights reserved.

Data Action Events (continued)


To utilize custom events, create an on<CustEvent>() method in the data action. Then,
invoke the event by using the same naming convention as the built-in operations.
This is a technique to extend the default behavior without interfering with the standard event life
cycle.

Oracle JDeveloper 10g: Build Applications with ADF 12-18

on<Event> Example: Built-in Events

Extending a named built-in event


?event=commit

public void onCommit(DataActionContext ctx)


{
HttpSession session = ctx.getHttpServletRequest().getSession();
Boolean loggedOn = (Boolean)session.getAttribute("AUTHFLAG");
if (loggedOn.booleanValue())
{
ctx.getEventActionBinding().doIt();
}
}

12-19

Copyright 2004, Oracle. All rights reserved.

on<Event> Example: Built-in Events


In this example, you can add some logic to a built-in event; for example, allowing the commit
event to take place only if the user is logged in.
Thus, the commit event is triggered through a submit button called event_commit or an
argument on the URL (as shown above). This assumes that the UIModel for this data action or
page contains the commit operation.
After the button is pressed, the data action is notified that the commit operation has taken place.
The data action then introspects the subclass of data action provided for an onCommit()
method.

Oracle JDeveloper 10g: Build Applications with ADF 12-19

on<Event> Example: Custom Events

Calling a custom operation


event=foo

public void onFoo(DataActionContext ctx)


{
// just direct the flow to the "foo" forward
ctx.setActionForward("foo");
}

12-20

Copyright 2004, Oracle. All rights reserved.

on<Event> Example: Custom Events


In addition to built-in operations that are already registered, you can also code custom events that
are again detected by introspection. In this case, the event foo simply sets the forward for the
data action or page to the target of the foo forward.
Note that if there is no operation defined for an event, the data action assumes that the event is in
fact identifying a forward. Thus, event=foo triggers the flow to follow the foo forward.

Oracle JDeveloper 10g: Build Applications with ADF 12-20

Forwards and Events in ADF Applications

Name related forward components


the same as the submit buttons to
submit first to the data page, then
to the forward target.
addCustomers.jsp:

<html:form action="/addCustomers.do">

<input name="event_Add" type="submit"


value="Submit"/>

12-21

Copyright 2004, Oracle. All rights reserved.

Forwards and Events in ADF Applications


As previously discussed, Struts looks for a forward by the same name as the specified event if
the event does not exist. In the case of a create and/or edit scenario, the form data must be
submitted to the methods associated with each data page. Thus, the form action returns control to
the addCustomers.do data page. To return control to the browse page, create a forward
named the same as the submit button name in the calling form, as shown in the slide.

Oracle JDeveloper 10g: Build Applications with ADF 12-21

Summary

In this lesson, you should have learned how to:


Create data pages mapped to business services
Create Web applications that utilize data pages
Customize data actions and data pages to
enhance the behavior of an application

12-22

Copyright 2004, Oracle. All rights reserved.

Summary
This lesson should have taught you how to utilize data pages and data actions to easily
incorporate business services into a Struts-based Web application.

Oracle JDeveloper 10g: Build Applications with ADF 12-22

Practice 12-1: Overview

This practice covers the following topics:


Creating data actions
Adding methods to data actions

12-23

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 12-23

Practice 12-1
Adding features to data pages.
Start JDeveloper, and open the practice12 workspace.
1. In this step, you add navigation operations to the categories page. The buttons allow the
user to navigate forward or backward through sets of category rows.
a. Open the categories data page.
b. In the Data Control pane, open the SalesAppModuleDataControl node, expand the
CategoriesView node, and then the Operations node.
c. Select the Previous Set item, and drag it to the Design Editor following the last
object. If prompted with an Add Form Element Confirmation dialog box, answer Yes.
d. Perform the same steps and add the Next Set operation, and drag it next to the
Previous Set button.
e. You must include the data table inside the form tag that you just added. Go to the
Source tab, find the <form> tag, and move it to just above the <table> tag.
f. Next, set the action property of the form to categories.do.
2. Modify the iterator so that the page does not display all the items at one time. This makes
the pages more user friendly. If the users do not see the category that they are looking for,
they can click one of the buttons to see the next set of records, rather than having to scroll
to see all of the categories.
a. In the Applications Navigator, click the categories.jsp node.
b. In the Structure pane, click the UIModel tab, which is the second tab at the top of the
Structure pane.
c. Click CategoriesViewIterator and set the Range Size value to 5 in the Property
Inspector. This restricts the number of categories displayed on a page to 5.
3. Add navigation operations to the products page.
a. Open the products data page.
b. Within the CategoriesView node, expand the ProductInformationView node, and
then the Operations node and add Previous Set and Next Set items as you did for the
categories page. Do not forget to move the <form> tag and set the action property to
products.do.
4. Modify the products iterator to display 5 rows just as you did for the categories iterator.
5. Clean up the unnecessary columns from both pages.
a. In the table created for the view, select the first top left cell, right-click, select Table
from the context menu, and select the delete column option.
b. This removes the current_row column from the table.

Oracle JDeveloper 10g: Build Applications with ADF 12-24

Practice 12-1 (continued)


6. Create a Master Detail Page navigation for the categories and products pages.
a. In the page flow, delete the link from categories to products that you created earlier.
b. Open the categories page in the Design Editor, and delete the link and message bean.
c. Select the Operations node for the CategoriesView in the Data Control Palette.
d. Drag the setCurrentRowWithKey categories operation as a Find Row Link to the
CategoryName column. (You can choose any column.)
e. Move the <a href tag around to include the category name.
<a ref="categories.do?event=setCurrentRowWithKey&Arg0=
<c:out value='${Row.rowKeyStr}' />">
<c:out value="${Row.CategoryName}"/></a>

f. Add a forward between categories and products, and rename it as


setCurrentRowWithKey.
g. Run the categories page, and select a category to test the detail page.
h. Use the link back to categories to select another category.
i. Close the browser.

Oracle JDeveloper 10g: Build Applications with ADF 12-25

Practice 12-1 (continued)


7. Create a data page for ShoppingCartView that you created in an earlier practice.
a. Add the following entries in the ApplicationResources file:
link.products=continue shopping
link.categories=choose another category
b. Open the Page Flow Diagram, and create a shoppingCart data page with the default
corresponding jsp.
c. Drag the ShoppingCartView data control as a read-only table to the page.
d. Select the Struts Html link tag, and drop it at the bottom of the page. Add a Struts
Bean message tag to the link tag, and set the Key value as link.products.
Specify /products.do as the action value in the Property Inspector..
e. Select the Struts Html link tag and drop it at the bottom of the page. Add a Struts
Bean message tag to the link tag and specify link.categories as the Key value.
Specify /categories.do as the action value in the Property Inspector.
8. shoppingCartView is designed to hold items that the user chooses to buy from the online
store. The user adds the items by clicking a link on the item. The item is then added to
shoppingCartView. The code to accept these items and add them to the cart is in the
shoppingCartViewImpl class. Rather than having you type all the code, the code is
already in the class. The instructions for this portion of the practice are to step you through
the code.
a. Make the view object capable of using the FindByKey method. Setting this
property to true enables you to search the view object by Key. The benefit of using
this technique is that you do not have to iterate through the rows searching for a
match. That function is already written for you.

protected void create()


{
super.create();
setManageRowsByKey(true);
}
// end of create

Oracle JDeveloper 10g: Build Applications with ADF 12-26

Practice 12-1 (continued)


b. We also need a method to add items to the cart when this method is called. The
method accepts two arguments, productId and quantity. The first step of this
method is to check to see whether this product is already in the shoppingCart.
You do that by calling findCartItem(), which uses findBykey. If it does not
find the item, it adds it as a new row. The method adds a new row by calling
createRow(), insertRow(cartItem), and then calling
fillInCartDetails(). This last method sets the rest of the attributes to the
values from the product. You will look at that method next.

Oracle JDeveloper 10g: Build Applications with ADF 12-27

Practice 12-1 (continued)


c. The fillInCartItemDetails() method instantiates a
ProductInformationView and sets its where clause to the productId of the
current cartItem. It then queries the view object to get the details of the product. It
then sets the productName and listPrice of the shoppingCartItem.

Oracle JDeveloper 10g: Build Applications with ADF 12-28

Practice 12-1 (continued)


d. The findCartItem() method simply takes a productId as an argument, and
checks to see whether it exists in the shoppingCart. If it exists, it returns the
shoppingCartItem row.

e. The cartTotal() method returns the total of all the items in the cart. To do this, it
creates a rowSetIterator of the shoppingCart and iterates through it,
summing the extendedTotal attributes as it does. At the end of the
RowSetIterator, it returns the total.

Oracle JDeveloper 10g: Build Applications with ADF 12-29

Practice 12-1 (continued)


9. After the user has selected the items and added them to the cart, you need to finalize the
order; in other words go through the checkout process. The code creates a single order for
the shoppingCart, and then creates an OrderItems row for each row in the
shoppingCart This method is in the SalesAppModuleImpl class.

Oracle JDeveloper 10g: Build Applications with ADF 12-30

Practice 12-1 (continued)


10. Now that all the code is in place to add items to the cart, calculate the total, and even
finalize the order, you need code to get it all started. This method is published in the
application module so that client applications can access it. All the other methods are used
within the context of this one method. This method is the addToCart method and is also
in the SalesAppModuleImpl class.

Oracle JDeveloper 10g: Build Applications with ADF 12-31

Practice 12-1 (continued)


11. Now that the code is in place to complete your application, you can add the elements to add
products to the shoppingCart. The result is a link on the product ID that forwards to a
DataAction. The DataAction calls the addToCart method, which adds the product to the
ShoppingCartView object.
a. Add a DataAction to the page flow, and name it /addToCart.
b. Drag the addToCart method from the SalesAppModule to the DataAction.
c. Change the name of the parameter in the addToCart DataAction to
param.prodId. (Use the Structure pane and select paramNames[0].)
d. Add a forward from the products page to the addToCart DataAction and name it
addToCart.
e. Add a forward from the addToCart DataAction back to the products page. Leave the
name as success.
12. Next, add an href to the products page that uses the forward you just defined and passes
the productId as an argument. Because this is a common activity, create a code snippet
that makes this easier.
a. Open the code snippet list on the Component Palette.
b. Right-click and select Add Component.
c. Name the component an href with an event and argument
d. Enter the following code snippet:
<a href="myPage.do?event=myEvent&myArg=<c:out
value="${Row.myValue}" />"> link words </a>
e. Click OK. You are now ready to use this snippet wherever you need.
f. From the Component Palette, select code snippets. In the Design Editor for the
products page, place your cursor just before the productId value in the read only
table. Now click the an href item in the Component Palette. This adds your code
snippet to the page.
g. Find the code in the Source Editor and change it for your specific application by
replacing myPage, myEvent, myArg, and myValue. Your code should look like:
<a href="products.do?event=addToCart&prodId=<c:out
value="${Row.ProductId}" />">
<c:out value="${Row['ProductId']}"/></a>
h. Add a forward from the products page to the shoppingCart page. Name the forward
viewCart.
13. In the Visual Editor on the products page, add an href that calls the forward to the
shoppingCart. The code should look like the following code (You can use the snippet
again.):
<a href="products.do?event=viewCart">View your Cart </a>

Oracle JDeveloper 10g: Build Applications with ADF 12-32

Practice 12-1 (continued)


14. Build and test the application starting at the categories page.
a. Select a category and notice that the products page is coordinated with that category.
b. Go back to the categories page and select another category. Observe the same
behavior.
c. Click a product to add it to the shoppingCart.
d. See that the item is added to the cart.
e. Experiment with multiple items by clicking the same item multiple times.
f. When you are done, close the browser.

Oracle JDeveloper 10g: Build Applications with ADF 12-33

Adding Validation and Error Handling

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Practice
Total

Timing
35 minutes
30 minutes
65 minutes

Objectives

After completing this lesson, you should be able to do


the following:
Validate form input
Use declarative validation
Use client-side validation
Utilize control hints to modify the view

13-2

Copyright 2004, Oracle. All rights reserved.

Objectives
Business logic and rules should be enforced in the business tier of an application. However, it is
possible and sometimes useful to validate data at the client level (thus saving the user a round
trip to the server). This provides for an effective and robust user interface. This lesson shows you
how to incorporate client-side validation into the view of a Struts-controlled application.
Additionally, enhancing the view by using control hints is also covered in this lesson.

Oracle Jdeveloper 10g: Build Applications with ADF 13-2

Overview of Validation
Form Bean validate()
method, Struts Validator

JSP

JavaScript

13-3

Struts
Form Bean

Method Validators,
Control Hints

Struts
Action

ADF
Business
Components

New Validation Methods

Copyright 2004, Oracle. All rights reserved.

Overview of Validation
Validation can be performed at many levels of an application. You have already seen how to
create validation methods in ADF Business Components by using method validators. However,
there are several ways to incorporate validation in Struts: utilizing the form bean validate()
method, or by creating custom validation classes and calling their methods from the
execute() method of a Struts action. There is also a plug-in available in Struts, which
incorporates common validation rules. Additionally, simple validation can be performed at the
client level by creating a JavaScript file, which is referenced in the JavaServer Pages (JSP).

Oracle Jdeveloper 10g: Build Applications with ADF 13-3

Need for Validation

In Web applications, the user usually does not receive


training on how to complete fields correctly. Thus, an
application must provide feedback to the user for
these types of actions:
Entering required values
Specifying values within a specified range
Comparing values
For example, Password1 must match Password2.

13-4

Copyright 2004, Oracle. All rights reserved.

Need for Validation


Client-side validation enables immediate response to a user interacting within an HTML form.
For example, the response can display an alert when a business rule is violated or correct data if
an entry does not have the desired format. Client-side validation is not meant to replace serverside enforcement of business and format rules. It should be thought of as a convenience for the
end user to avoid waiting for a server response simply to determine whether the submitted data is
correct.

Oracle Jdeveloper 10g: Build Applications with ADF 13-4

Client-Side Validation

To perform validation by using Struts, you must:


1. Create a form bean class
2. Overwrite the form bean validate() method,
passing an error to the action
3. Create the error message in
ApplicationResources.properties
4. Add the input attribute for the form to the action to
indicate where the error message should appear

13-5

Copyright 2004, Oracle. All rights reserved.

Client-Side Validation
Validation can be incorporated by using the form bean class of a Struts action. The form bean
contains a validate() method, where you can define the validation logic. The next step is to
create a message for the error in the ApplicationResources.properties file.

Oracle Jdeveloper 10g: Build Applications with ADF 13-5

Form Bean Validation Method

The form bean contains a validate() method for


validating form fields. Overwrite this method to
perform custom validation:
public ActionErrors validate(ActionMapping
mapping, HttpServletRequest request)
{
ActionErrors errors = new ActionErrors();
if ((username == null) ||
(username.trim().equals("")))
{
errors.add("username", new
ActionError("error.username.required"));
}
return errors;
}
13-6

Copyright 2004, Oracle. All rights reserved.

Form Bean Validation Method


After you have created a form bean class, overwrite the validate() method to perform
validation on form fields. In this example, if the form field username is a null value or an
empty string, the error.username.required error is passed to the action. The next step is
to create a message for this error in the ApplicationResources.properties file.

Oracle Jdeveloper 10g: Build Applications with ADF 13-6

Creating the Error Message

To display the error message, specify the


message in
ApplicationResources.properties:
error.username.required=The Username Value must be
Supplied

Define where the error message is to be displayed


by using the input attribute:
<action name="logonbean" path="/logon"
input="showLogon.jsp" type="view.LogonAction">

13-7

Copyright 2004, Oracle. All rights reserved.

Creating the Error Message


To create the error message, add it to the ApplicationResources.properties file. In
the example above, this corresponds to ActionError created in the form beans validate()
method. Note that the validate attribute of the action should be set to true, which is the
default.

Oracle Jdeveloper 10g: Build Applications with ADF 13-7

Printing Errors in the JSP

Ensure that the JSP contains an <html:errors> tag:


<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ page contentType="text/html;charset=windows-1252"%>
<html>

<body>
<html:errors />

Note that you can specify the property attribute of the


<html:errors> tag to print only the corresponding
error:
<html:text property="username"></html:text>
<html:errors property="username" />

13-8

Copyright 2004, Oracle. All rights reserved.

Printing Errors in the JSP


The <html:errors> tag must be included in the JSP to display the error. This tag is available
in the Struts HTML category of the Component Palette. There are two ways to display the error,
as shown below.
Generic <html:errors>

Specific <html:errors>
(property attribute set)

Oracle Jdeveloper 10g: Build Applications with ADF 13-8

Validating Actions

A second type of validation is to overwrite the execute


method in the action class. This type of validation is
useful when:
You have previously created classes that check
the validity of a given value
You do not want the form values to be reset after
validation
The validation logic is complex

13-9

Copyright 2004, Oracle. All rights reserved.

Validating Actions
Instead of validating form input by using the validate() method, you can also validate
values by using the execute() method of the action. This is especially useful if you already
have JavaBeans or other classes that evaluate user input.

Oracle Jdeveloper 10g: Build Applications with ADF 13-9

Creating a Validation Class

The first step in validating user input is to create a


method for validation. This can be done in a simple
class file, as shown:
package view;
public class LoginValidation
{
boolean checkUsernamePassword(String un, String pw)
{
if ( un.equals("scott") && pw.equals("tiger") )
return true;
else
return false;
}
}

13-10

Copyright 2004, Oracle. All rights reserved.

Creating a Validation Class


To validate using the action, you must first create a method for validation. This should be done
outside the action and action form bean classes, in a new file. The example above contains one
method, checkUsernamePassword(), which returns true if the username is scott and
the password is tiger. This is, of course, a simple example. The code for validating the
username and password in a more complex application can validate based on database values.

Oracle Jdeveloper 10g: Build Applications with ADF 13-10

The execute() Method

To validate user input in the action class, overwrite the


execute() method, calling your validation method:
public ActionForward execute
{
LogonActionForm logonForm = (LogonActionForm) form;
String un = logonForm.getUsername();
String pw = logonForm.getPassword();
LoginValidation loginvalidation = new
LoginValidation();
if ( loginvalidation.checkUsernamePassword(un,pw))
{
return mapping.findForward("success");
} else return mapping.findForward("failure"); }

13-11

Copyright 2004, Oracle. All rights reserved.

The execute() Method


Call the validation method that you have created in the execute() method of the action class.
To access the values of the form fields, create an instance of the form bean and utilize the
get() methods in the form bean. This example uses the findForward() method to direct
the user to the appropriate page. You can then use the Struts logic tags to determine whether the
user entered incorrect data, and display a helpful message if the user is attempting a login for the
second time.

Oracle Jdeveloper 10g: Build Applications with ADF 13-11

Validation Results

1. User enters incorrect


2. User enters no data
login (action validation).
(form bean validation).

3. User enters correct


login.

13-12

Copyright 2004, Oracle. All rights reserved.

Validation Results
The validation incorporated thus far in this lesson ensures that the user enters something in the
username and password form fields (case 2). When that validation has occurred, the action
validates the entered username to ensure that it is a valid login (Scott, Tiger). If not, the
failure forwards to the original login form (case 1). Finally, if the user enters the correct login,
the user is forwarded to the success page (case 3).

Oracle Jdeveloper 10g: Build Applications with ADF 13-12

Struts Validator

Declaratively validate form fields by using the Struts


Validator. The validator plug-in:
Is XML based
validator-rules.xml (Validation rules)
validations.xml (Usages)

13-13

Defines rules for each field in a form bean


Can provide client validation using JavaScript
Is extensible

Copyright 2004, Oracle. All rights reserved.

Struts Validator
Validator is driven by two XML files, validator-rules.xml and validations.xml.
validator-rules.xml describes all the validation rules that can be used, such as
required, maxLength, integer, and so on.
Each rule is defined in validations.xml, which applies rules to the various fields in a form
bean. If validation fails, the user is redirected to the input page with the relevant error messages
from the validator. Note that validator-rules.xml is extensible. You can add custom
validation rules by utilizing the appropriate classes to implement them.
Besides for server-side validation, validator-rules.xml can also have a JavaScript
component for client-side validation.

Oracle Jdeveloper 10g: Build Applications with ADF 13-13

Setting Up the Struts Validator

1. Specify the validator class in the <plug-in> tag of


struts-config.xml.
2. Add validation-rules.xml to your project.
3. Modify the form bean class to subclass
ValidatorForm or DynaValidatorForm.
4. Create a usage file to specify form field rules.
5. Add error messages to
ApplicationResources.properties.

13-14

Copyright 2004, Oracle. All rights reserved.

Setting Up the Struts Validator


Perform the steps above to set up your application workspace to utilize the Struts Validator. The
next few slides explain these steps in detail.

Oracle Jdeveloper 10g: Build Applications with ADF 13-14

Utilizing the Struts Validator

Add ValidatorPlugIn to the <plug-in> tag and


specify the path for validator-rules.xml and
validation.xml:

13-15

Copyright 2004, Oracle. All rights reserved.

Utilizing the Struts Validator


The necessary files for utilizing the Struts Validator are contained in
org.apache.struts.validator.ValidatorPlugIn. To add the file, select the
PlugIns category of the Struts Configuration Editor and specify the full path of
ValidatorPlugIn. Additionally, an example validator-rules.xml file is located in
the jakarta-struts\lib directory. Copy this file in the WEB-INF directory of your
project and add the file to the project. Specify this file, as well as validation.xml, which
you will create later, using the property attribute of the plug-in tag. The property value must be
pathnames and the XML files specified can be comma separated. The entry should look
like this:
<plug-in
className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEBINF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

Oracle Jdeveloper 10g: Build Applications with ADF 13-15

Utilizing the Struts Validator

Specify the form bean to use the Struts Validator


by subclassing ValidatorForm or
DynaValidatorForm:
import org.apache.struts.validator.ValidatorForm;
public class LogonActionForm extends ValidatorForm {

Create validation.xml to validate form fields,


and ensure that each form field to be validated
contains an entry in
ApplicationResources.properties:
Logon.username=username
Logon.password=password

13-16

Copyright 2004, Oracle. All rights reserved.

Utilizing the Struts Validator (continued)


Setting up the validator plug-in is quite simple. All the libraries required are already configured
for a Struts project in JDeveloper 10g. The major task is to make sure that any form beans that
need validator support are based on the correct superclass (either ValidatorForm or
DynaValidatorForm, depending on the type of form bean). The next step is to create a usage file,
named validation.xml to specify which form fields to validate and how they should be
validated. The next slide provides an example. If not already specified, each form field must
have a reference in the ApplicationResources.properties file.

Oracle Jdeveloper 10g: Build Applications with ADF 13-16

validation.xml: Example

<!DOCTYPE form-validation PUBLIC


"-//Apache Software Foundation//DTD Commons
Validator Rules Configuration 1.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_0.dtd
">
<form-validation>
<formset>
<form name="logonbean">
<field property="password" depends="required" >
<arg0 key="logon.password" />
</field>
</form>
</formset>
</form-valiidation>

13-17

Copyright 2004, Oracle. All rights reserved.

validation.xml: Example
In this example, the form bean named logonbean is validated by using the built-in validation
rule required. At run time, the validator checks for a value in the password field, and if it is
null or an empty string, the key logon.password is referenced in the
ApplicationResources.properties file and this value is passed as an argument to the
errors.required entry. Some of the additional built-in validation rules and their
corresponding error message keys are described in the table below:
Built-in Validation Rules
("depends" attribute)

Error Message Key in Properties File

range

errors.range={0} is not in the range {1} through {2}.

byte/short/integer/long/
float/double

errors.byte={0} must be a byte.

date

errors.date={0} is not a date.

creditCard

errors.creditcard={0} is an invalid credit card number.

email

errors.email={0} is an invalid e-mail address.

Oracle Jdeveloper 10g: Build Applications with ADF 13-17

Struts Validator Output

Validator messages can be displayed on the page or in


a JavaScript window:

13-18

Copyright 2004, Oracle. All rights reserved.

Struts Validator Output


The error messages generated by the Struts Validator are displayed within the JSP by default.
Alternatively, the error messages can be displayed in a JavaScript window. The code for the
JavaScript validation is already created for you in validator-rules.xml. Thus, to display
error messages using JavaScript, only the JSP must be modified. The name of the form is passed
to the JavaScript method within the <head> tags, and the form attribute onsubmit is specified
as follows:
<html>
<head>
<html:javascript formName="logonbean"/>
</head>
<body>
<html:errors />
<html:form action="/logon.do" onsubmit="return
validateLogonbean(this)">
Username: <html:text property="username"></html:text>

Oracle Jdeveloper 10g: Build Applications with ADF 13-18

Exception Handling

Exception handling is implemented by:


1. Creating a class for exception handling, which
subclasses
org.apache.struts.action.ExceptionHandler

2. Overriding the execute() method to process the


exception
3. Returning an ActionForward object
4. Configuring the exception handler in the strutsconfig.xml file
5. Creating an exception message in
ApplicationResources.properties

13-19

Copyright 2004, Oracle. All rights reserved.

Exception Handling
Exception handling is implemented in the case that an actions execute() method throws an
exception by creating a class for the exception, which subclasses ExceptionHandler.
Override the execute() method to process the exception, and return an ActionForward
object. Next, configure the exception handler in the struts-config.xml file. This can be
done globally:
<global-exceptions> <exception
key="exception.message.global" type="java.io.IOException"
handler="view.MyExceptionHandler"> </global-exceptions>
Or for a specific action:
<action>
<exception type="java.io.IOException"
key="exception.message.action"
handler="view.MyExceptionHandler" />
</action>
The last step is to map the key attributes to an appropriate error message in
ApplicationResources.properties.

Oracle Jdeveloper 10g: Build Applications with ADF 13-19

JavaScript

JavaScript is supported
in JDeveloper as a
simple way to
incorporate validation.

13-20

Copyright 2004, Oracle. All rights reserved.

JavaScript
A simple way to incorporate additional validation in a Web application is to use JavaScript.
Code insight and highlighting are supported in JDeveloper for JavaScript (.js) files. JavaScript
validation is best used for simple validations such as verifying that a user enters a number in a
number field. However, careful consideration must be given to the extensive use of JavaScript,
as clients can turn off JavaScript in their browser. In this case, validation should be duplicated by
using form bean validation or the Struts Validator so that the user cannot enter invalid or
incorrect data.

Oracle Jdeveloper 10g: Build Applications with ADF 13-20

Enhancing the View

Use control hints


to modify the way
an attribute is
displayed in a
client.

13-21

Copyright 2004, Oracle. All rights reserved.

Enhancing the View


Use the Control Hints page to associate a control hint with a view or entity attribute. The page is
accessed in JDeveloper by selecting the ADF Entity Object or View Object attribute that you
want to modify. Click the Control Hints tab and specify a more user-friendly label such as
Credit, instead of the default CreditLimit. Optionally, specify the format of the attribute. To
display a calendar picker in the client, select Date in the Control Type list. Additionally,
specifying the Tooltip Text makes the text available through the HTML ALT attribute. At run
time, the client application displays the attribute by using the control hints that you specify:

Note that if a control hint is defined for an entity attribute, all view objects of that entity will
inherit the control hint. However, a view object attribute can override any entity attribute control
hints.

Oracle Jdeveloper 10g: Build Applications with ADF 13-21

Summary

In this lesson, you should have learned how to:


Validate form input using:
The validate() method
The action class
The Struts Validator

13-22

Develop JavaScript validation


Customize the view by using control hints

Copyright 2004, Oracle. All rights reserved.

Summary
This lesson should have taught you how to incorporate validation in the controller and view tiers
of an application. Additionally, you should have learned how to customize the view through the
use of ADF Business Component attribute control hints. These types of development objectives
aid the user in successfully navigating through a Web application.

Oracle Jdeveloper 10g: Build Applications with ADF 13-22

Practice 13-1: Overview

This practice covers the following topics:


Validating form fields by using the validate()
method
Creating validation methods
Calling validation methods from actions
Utilizing the Struts Validator
Handling exceptions

13-23

Copyright 2004, Oracle. All rights reserved.

Oracle Jdeveloper 10g: Build Applications with ADF 13-23

Practice 13-1
In this practice, you enhance the views and create a new view.
Start JDeveloper, and open the practice13 workspace.
1. Enhance the view objects to make the the UI more user-friendly.
Hint: To edit the view objects, double-click the view object in the System Navigator.
Expand the attribute list, and select the attribute you need to change. Click the
Control Hints tab and make the necessary changes.
a. Edit the CreditLimit attribute in CustomersView. On the Control Hints tabbed page,
set the format type to currency and format to $0000.00.
b. Edit the UnitPrice and DiscountUnitPrice attributes in OrderItemsView. Set the
format type to currency and format to $0000.00.
c. Edit the OrderDate attribute in OrdersView. Set the format type to Simple Date and
format to yyyy-mm-dd.
d. Edit the ListPrice attribute in ProductInformationView. Set the format type to
currency and format to $0000.00.
e. Edit the ListPrice and ExtendedTotal attributes in ShoppingCartView. Set the
format type to currency and the format to $0000.00.
2. Add a validator for input fields by adding the validator plug-in to the Strutsconfig.xml file.
a. Open the Page Flow Diagram.
b. In the Structure pane, right-click the the top-level Struts Config node and choose New
> Plug In from the context menu. This will create a new plug-in node in the structure.
c. Select the new plug-in node and switch to the Property Inspector.
d. Set the className property for the plug-in to
org.apache.struts.validator.ValidatorPlugIn.
e. Now with the plug-in node still selected in the Structure pane bring up the context
menu and choose New > Set Property. This will create a child node under the plugin labeled as <set-property>.
f. Select the new <set-property> entry and switch to the Property Inspector.
g. Set the property property for this <set-property> entry in the inspector to path
names.
h. Set the value property to the following (this can be changed to suit your application):
/WEB-INF/validator/validator-rules.xml,/WEBINF/validator/validations.xml.

i. The /WEB-INF/validator directory already has a copy of the Validator rules


file. The file has been copied for you from the basic version supplied with
JDeveloper. The file is delivered in %JDEV_HOME%/jakartastruts/lib/validator-rules.xml.

Oracle Jdeveloper 10g: Build Applications with ADF 13-24

Practice 13-1 (continued)


j. Copy the predefined Validator error messages in your resources file. These messages
appear at the beginning of the validator-rules.xml file:
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1}
characters

3. Modify the authenticateUser Data Action to use the logon Form Bean you created in an
earlier practice.
a. Select the authenticateUser Data Action on the Struts diagram.
b. Change the input property to /logon.do.
c. Change the name property to logon.
4. Set up form beans to use the correct superclass.
a. Open the Page Flow Diagram.
b. In the Structure pane, open the logon Form Bean.
c. In the Properties pane, change the type to
org.apache.struts.validator.DynaValidatorForm.
d. Select the WEB-INF/validator node in the Applications Navigator. Note that there is
a file named validations.xml. This file holds the validation rules that you are
going to apply. Normally, you create this file by selecting the WEB-INF node, rightclicking, and selecting New from the context menu. You then select xml, new xml
file in the gallery.
e. Open the validations.xml file and examine the code. You should note that the
statements check whether the customerName field has a value and that the
customerId field is required, and whether it is an integer and has a value between
100 and 600. The xml validation code is on the following page.

Oracle Jdeveloper 10g: Build Applications with ADF 13-25

Practice 13-1 (continued)


<form-validation>
<formset>
<form name="logon">
<field
property="lastName"
depends="required">
<arg0 key="logon.lastname"/>
</field>
<field
property="customerId"
depends="required,integer,intRange">
<arg0 key="logon.customerid"/>
<arg1
name="intRange"
key="${var:min}"
resource="false"/>
<arg2
name="intRange"
key="${var:max}"
resource="false"/>
<var>
<var-name>min</var-name>
<var-value>100</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>600</var-value>
</var>
</field>
</form>
</formset>
</form-validation>

5. Modify the logon page to use the validator.


a. Run the logon page and provide some incorrect values to test Last Name and
Customer ID validation. Note how the page handles input errors.
b. Close the browser when you are done.
c. Change the form tag to the following:
<form action="authenticateUser.do" onsubmit="return
validateLogon(this);">

d. Update the JSP to use JavaScript validation by inserting the following statement right
below the <head> tag:
<html:javascript formName="logon"/>

e. Make sure that your browser is configured to accept JavaScript.


f. Run the logon page and provide some inappropriate values to test Last Name and
Customer ID validation.

Oracle Jdeveloper 10g: Build Applications with ADF 13-26

Enhancing the User Interface

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Practice
Total

Timing
45 minutes
45 minutes
90 minutes

Objectives

After completing this lesson, you should be able to do


the following:
Use the Property Inspector to modify visual
components
Use the Structure pane to modify data elements
Add navigational elements

14-2

Copyright 2004, Oracle. All rights reserved.

Objectives
After the fundamental application is complete, you can begin to enhance the user interface (UI)
with additional elements. These elements can be either visual or databound elements.
In this lesson, you learn how to add elements that enhance the UI. You also learn how to add
navigational elements.

Oracle JDeveloper 10g: Build Applications with ADF 14-2

Modifying Visual Component Properties

To change the appearance of an object in the Visual


Editor, you can use:
Formatting toolbar of the HTML/JSP Visual Editor:

14-3

Property Inspector:

Copyright 2004, Oracle. All rights reserved.

Modifying Visual Component Properties


The Visual Editor enables the user to edit the design directly as opposed to editing the source
code. To change the appearance of objects in the Visual Editor, you can use:
Formatting toolbar of the JavaServer Pages (JSP) Visual Editor
Property Inspector

Oracle JDeveloper 10g: Build Applications with ADF 14-3

Using the Toolbar to Format Objects

Style
poplist

Font
poplist

Font
size

Bold/
italic/
underline

14-4

Foreground
color

Align left/
center/right

Background
color

Numbered/
bulleted
list

Decrease/
increase
indent

Copyright 2004, Oracle. All rights reserved.

Using the Toolbar to Format Objects


A useful feature of the JSP/HTML Visual Editor is the formatting toolbar that enables you to
easily format the selected objects. When you change the appearance of an item by using the
toolbar, its appropriate code is also modified.
The primary function of the toolbar buttons is to modify or extend tags in an HTML or JSP page.
Suppose you have the code:
<P>Current Inventory</P>
If in the Visual Editor you place the cursor anywhere within the paragraph (because styles apply
to entire paragraphs) and select H1 from the Style pop-up list, JDeveloper changes the code to:
<H1>Current Inventory</H1>

Oracle JDeveloper 10g: Build Applications with ADF 14-4

Using the Property Inspector

The Property Inspector:


Displays attributes of the selected tag or tags
Displays intersection or union of attributes for
multiple selected tags
Visually distinguishes
changed attributes

14-5

Copyright 2004, Oracle. All rights reserved.

Using the Property Inspector


The Property Inspector enables you to edit attribute values of any tag in an HTML or JSP page.
The Property Inspector shows all editable attributes of a tag or tags, depending on what is
selected in the document. This synchronization occurs regardless of whether you select an object
in the Visual Editor or in the Structure pane.
The Title area in the Property Inspector shows the ID or Name for the selected tag. If no ID or
Name is specified, the Title area shows the tag type.
If you press [Ctrl] and click to select multiple tags in the Visual Editor, the Property Inspector by
default displays those attributes that both tags have in common, enabling you to modify the tags
of multiple objects at once. If you want to see all attributes of the selected tags, click Union.
The Property Inspector provides a visual indication that an attribute has been changed from its
default value by prefixing the attribute with a square green icon. Attributes with default values
have no icon prefixed with them.

Oracle JDeveloper 10g: Build Applications with ADF 14-5

Adding Images to JSPs

To add images to JSPs, drag an image file to the


Visual Editor:

14-6

Copyright 2004, Oracle. All rights reserved.

Adding Images to JSPs


The Visual Editor supports images by using the image tag from the HTML library in the
Component Palette. You can also simply drag an image file (.gif, .jpeg, and so on) to the Visual
Editor. The JSP source is updated to include the image tag. Attributes for the image are specified
by using the Property Inspector, as shown below:

Oracle JDeveloper 10g: Build Applications with ADF 14-6

Using Style Sheets

You can use the following types:


Style sheets available in JDeveloper:
Oracle
Browser Look and Feel (BLAF)
JDeveloper

14-7

Style sheets that you add to the Component


Palette

Copyright 2004, Oracle. All rights reserved.

Using Style Sheets


Cascading style sheets (CSS) are used extensively in many Web applications. You can find
information about CSS at http://www.w3.org/Style/CSS.
JDeveloper provides some built-in style sheets, including Oracle, Browser Look and Feel
(BLAF), and JDeveloper style sheets, and also enables you to create your own CSS. You can add
external style sheets to the Component Palette so that you can easily apply them to your Web
pages.

Oracle JDeveloper 10g: Build Applications with ADF 14-7

Editing Default Style Sheets

To modify an existing style sheet, open it in the Code


Editor:
Code insight is
available for CSS
files.
Saving the file
updates the CSS
for the current
application
workspace.

14-8

Copyright 2004, Oracle. All rights reserved.

Editing Default Style Sheets


You can edit one of the provided style sheets (oracle.css, jdeveloper.css, or
blaf.css) by using the Code Editor. First, add the style sheet to your JSP by dragging the
style sheet name from the CSS category of the Component Palette to the Visual Editor. The
.css file is copied into the current workspace. Navigate to the css node in the Web Content
folder of the workspace, and double-click the style sheet to open it in the Code Editor. Edit the
file as necessary, using code insight where available. Saving the file updates the style sheet for
the current application workspace only.

Oracle JDeveloper 10g: Build Applications with ADF 14-8

Creating a New Style Sheet


New Gallery

CSS File

Create Cascading Stylesheet


HTML

untitled1.css

14-9

Copyright 2004, Oracle. All rights reserved.

Creating a New Style Sheet


JDeveloper enables you to create a new style sheet.
To create a new untitled1.css file and add it to your project, select File > New > Web-Tier
> HTML > CSS File. This produces a generic file that you can supplement with your own code.
The Code Editor provides color coding and syntax highlighting of CSS elements.

Oracle JDeveloper 10g: Build Applications with ADF 14-9

Editing Style Sheets

14-10

Copyright 2004, Oracle. All rights reserved.

Editing Style Sheets


When you open a style sheet for editing, the colors and fonts in the Code Editor help you to
know whether the syntax is correct. You can set preferences for the display of colors and fonts in
the CSS Code Editor by performing the following steps:
1. Select Tools > Preferences from the JDeveloper menu; the Preferences window opens.
2. Expand the Code Editor node in the left pane of the Preferences window.
3. Select Syntax Colors in the left pane of the Preferences window.
4. Select CSS from the Language pop-up list in the right pane of the Preferences window.

Oracle JDeveloper 10g: Build Applications with ADF 14-10

Adding a Style Sheet to the


Component Palette
To add a style sheet:
1. Select CSS from the pop-up
list.
2. Right-click in the Component
Palette.
3. Select Add Component.
4. Click Browse to choose file.
5. Enter name.

14-11

Copyright 2004, Oracle. All rights reserved.

Adding a Style Sheet to the Component Palette


By default, the Oracle, BLAF, and JDeveloper style sheets are present in the CSS Component
Palette when you select CSS from the pop-up list. You can add existing style sheets to the
Component Palette by performing the following steps:
1. Select CSS from the pop-up list in the Component Palette (this option is available in the
HTML or JSP Visual Editor).
2. Right-click in the Component Palette.
3. From the context menu, select Add Component.
4. Click Browse to invoke a file chooser and select the desired .css file.
5. Enter a name for the style sheet as it is displayed in the Component Palette.
You can also add a style sheet by selecting Tools > Configure Palette from the JDeveloper menu.
Then, select CSS in the Pages window (or choose CSS from the Page Type pop-up list), and
click Add.

Oracle JDeveloper 10g: Build Applications with ADF 14-11

Applying a Style Sheet to a Page

14-12

Copyright 2004, Oracle. All rights reserved.

Applying a Style Sheet to a Page


When a style sheet is in the Component Palette, you can easily apply it to a JSP or HTML page
by selecting CSS from the drop-down list, and then clicking the desired style sheet name. The
slide shows how applying the myNewCSS style sheet to the JSP changes the appearance of the
H1 heading Inventory Item. Applying a style sheet to a JSP or HTML page adds a line of code
similar to the following:
<link href="css/myNewCSS.css" rel="stylesheet" media="screen"/>
You can apply multiple style sheets to a page, with the result that attributes defined in the last
CSS that is applied override those defined in style sheets applied earlier. Suppose that you apply
the style sheets Oracle and then myNewCSS. The Oracle style sheet changes the background to
light gray, but does not affect H1 tags. The myNewCSS style sheet changes the H1 tag, but does
not define the background color. The resulting JSP has a light gray background, and the elements
defined with the H1 tag have the changed appearance. The following lines are added to the code:
<link href="css/oracle.css" rel="stylesheet" media="screen"/>
<link href="css/myNewCSS.css" rel="stylesheet" media="screen"/>
To undo the application of a style sheet, you can delete the appropriate line of code.

Oracle JDeveloper 10g: Build Applications with ADF 14-12

Adding Buttons to a JSP

Form action buttons: Submit and Reset


Data control buttons
Model: Commit and Rollback
View: Navigation and DML

14-13

Copyright 2004, Oracle. All rights reserved.

Adding Buttons to a JSP


Buttons in a JSP provide a way for users to initiate actions. There are two types of buttons that
you typically place on a page:
Data control buttons: These include Commit and Rollback buttons for the data model and
Navigation and DML buttons for each view in the model.
Form action buttons: Submit and Reset

Oracle JDeveloper 10g: Build Applications with ADF 14-13

Adding Data Control Buttons

Data control buttons:


Are added to JSP
from Data Control
View
Palette
operations
Are related to data
on the page
When related to
view, can control
Model
operations
navigation or initiate
DML
When related to model, can commit or rollback

14-14

Copyright 2004, Oracle. All rights reserved.

Adding Data Control Buttons


You use the Data Control Palette to add buttons that control navigation or DML for the view, or
commit and rollback for the model. You can drag these buttons to a JSP either as Button or
Button with Form.
When you create buttons in this way, Expression Language automatically binds them to the data
on the page. Expression Language is discussed later in this lesson.

Oracle JDeveloper 10g: Build Applications with ADF 14-14

Adding Navigation Buttons


Data Control Palette

DepartmentsView1

Drop As:
Navigation Buttons

14-15

Copyright 2004, Oracle. All rights reserved.

Adding Navigation Buttons


There is a quick way to create navigation buttons for a view. In the Data Control Palette, select
the view with which you want to associate the buttons, then select Navigation Buttons from Drop
As list. Drag the view to the page, and make sure to drag it to the form (enclosed by red dotted
lines) where the data controls reside.
The result is that four buttons are created with the values First, Previous, Next, and Last. The
functionality for these buttons is predefined; the code is similar to the following code for the
First button:
<input type="submit"
name="<c:out value='${bindings.First.path}' />" value="First"
<c:out value="${bindings.First.enabledString}"/>/>
This code uses JSP Standard Tag Library (JSTL) and Expression Language (EL) to navigate to
the first record in the set.

Oracle JDeveloper 10g: Build Applications with ADF 14-15

Adding Form Action Buttons

Cursor

14-16

Copyright 2004, Oracle. All rights reserved.

Adding Form Action Buttons


There are two types of form action buttons: Submit and Reset. The Submit button performs the
action that is defined for its surrounding form. The Reset button clears any data that the user
entered in the form.
To add Submit and Reset buttons to a JSP or HTML page, first position the cursor in the Visual
Editor at the point where you want the button to appear. Then, click the appropriate HTML
element in the Component Palette. If the cursor is not within a form, as denoted by the red dotted
outline, then a new form is created for the button.
By default, the Submit button performs the data action that is associated with the page. You can
change this in the Property Inspector for the form, which is displayed when you click in a blank
area of the form. Look at the action property, which is a pop-up list of the data actions that have
been defined. You can change the functionality of a Submit button by changing the action
property of the form.

Oracle JDeveloper 10g: Build Applications with ADF 14-16

Supplementing Button Functionality

14-17

Use button events.


The form action plus
defined events are
performed.

Copyright 2004, Oracle. All rights reserved.

Supplementing Button Functionality


In addition to the action that is defined for the button, you can provide supplemental
functionality for a button by defining one or more of the Events properties for the button. There
are 14 such properties, but the one most commonly used for a button is onClick. Here you can
use JavaScript to perform actions such as:
Opening another window:
window.open('http://otn.oracle.com','myWindow','');
Displaying a message on the status line:
window.status('Ouch, that hurts!');
The example in the slide shows the Next button, which has an onClick event defined that opens
another browser window and displays the Oracle Technology Network (OTN) home page. This
button has dual functionality: it navigates to the next record and also opens the new browser
window.

Oracle JDeveloper 10g: Build Applications with ADF 14-17

Using Expression Language

Expression Language is:


Used in combination with JSTL tags
A way to provide dynamic content without scripts
or JSP expressions
Using a JSP expression to access an attribute:
<x:aTag att=
"<%= pageContext.getAttribute("aName") %>">

The simpler syntax of Expression Language:


<x:aTag att= "${aName}">

14-18

Copyright 2004, Oracle. All rights reserved.

Using Expression Language


In combination with JSTL tags, you can use Expression Language (EL) to add dynamic elements
to a JSP. The EL provides identifiers, accessors, and operators for retrieving and manipulating
data resident in the JSP container. This makes it possible to use data without adding scriptlets or
regular expressions.
EL expressions are enclosed within the characters ${ and }; for example
${customer.lastName}. The value of the EL expression is evaluated at run time.
An example of a JSTL action that uses an EL expression is:
<c:out value="${customer.lastName}"/>

You can concatenate multiple expressions with static text. For example:
<c:out value="Hello ${customer.firstName} ${customer.lastName}"/>

Oracle JDeveloper 10g: Build Applications with ADF 14-18

Using EL Attributes

To reference attributes:
Enclose within ${}
Nest by using dot notation or []

Optionally include scope

<c:out value=
"${sessionScope.cart.numberOfItems} ">

14-19

Copyright 2004, Oracle. All rights reserved.

Using EL Attributes
You can access attributes by name, with an optional scope. Use dot notation or brackets ([]) to
access properties of attributes, which may be nested. For nested expressions, the value that is
returned is dependent on the type of object. For example, for the expression ${exp1.exp2}, if
exp1 is:
A map, the value that is returned is exp1.get(exp2)
A list or array, exp2 is coerced to an int and the value of the indicated list or array
member is returned
A JavaBean object, exp2 is coerced to a String and the result of a getter call is returned
You can specify a scope for the attribute. If no scope is specified, an attribute identifier is first
checked against page scope, then request scope, session scope, and finally application scope. If
the attribute is found, the value of the first match is returned; if not found, null is returned.

Oracle JDeveloper 10g: Build Applications with ADF 14-19

Using EL Literals and Operators

Literals: Values not beginning with ${

<c:out value="Hello ${customer.firstName}"/>

Operators

<c:if test="${bean1.a < 3}" />

14-20

Copyright 2004, Oracle. All rights reserved.

Using EL Literals and Operators


Literals
Any value that does not begin with ${ is treated as a literal. EL includes the following types of
literals:
Boolean: true and false
Long: As in Java
Floating point: As in Java
String: With single and double quotes. Use \ as an escape character; for example,
" is escaped as \".
Null: null
Operators
EL also includes a number of operators:
Arithmetic: +, -, *, /, div, %, mod
Logical: and, &&, or, ||, not, !
Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le
Empty: The empty operator is a prefix operation used to determine whether a value is
null or empty.

Oracle JDeveloper 10g: Build Applications with ADF 14-20

Using EL Implicit Objects


When referenced by name, the appropriate object is
returned instead of the corresponding attribute.
Examples:
${pageContext} returns the pageContext
object.
${pageContext.request.contextPath} returns
the context path (obtained from
HttpServletRequest).
${sessionScope.cart.numberOfItems} returns
the numberOfItems property of the sessionscoped attribute named cart.
${param["mycom.productId"]} returns the
String value of the mycom.productId parameter.
14-21

Copyright 2004, Oracle. All rights reserved.

Using EL Implicit Objects


The JSTL expression language defines a set of implicit objects:
Object
pageContext
pageScope
requestScope
sessionScope
application
Scope
param
paramValues
header
headerValue
initParam

Description
The PageContext object
A map that maps page-scoped attribute names to their values
A map that maps request-scoped attribute names to their values
A map that maps session-scoped attribute names to their values
A map that maps application-scoped attribute names to their values
A map that maps parameter names to a single String parameter value
A map that maps parameter names to a String[] of all values for that
parameter
A map that maps header names to a single String header value
A map that maps header names to a String[] of all values for that
parameter
A map that maps a parameter name to a single String parameter value

Oracle JDeveloper 10g: Build Applications with ADF 14-21

Using EL to Customize a Page

You can add conditional display logic using EL


For example, display a message and value only if the
value is not empty.

14-22

Copyright 2004, Oracle. All rights reserved.

Using EL to Customize a Page


You can add conditional logic by using EL to display items only if they have a value. For
example, in your application, you return the value of all the items in the shopping cart. Before
you start adding items, it is not appropriate to display a total message without a value. Using EL,
you can add the condition to make the user interface a little cleaner.
Add an EL if statement around the display that checks the value of the variable:
<c:if test="${not empty sessionScope.cartTotal}">
Items in cart
<c:out value="${sessionScope.cartTotal}"/>
</c:if>
The result is, if there are items in the cart, the total message is displayed, otherwise it is not.

Oracle JDeveloper 10g: Build Applications with ADF 14-22

Summary

In this lesson, you should have learned how to:


Use the Property Inspector to modify visual
components
Use the Structure pane to modify data elements
Use EL to add conditional display logic

14-23

Copyright 2004, Oracle. All rights reserved.

Summary
In this lesson, you should have learned how to enhance the user interface in the following ways:
By using the Property Inspector to modify visual components
By using the Structure pane to modify data elements
By using EL to add conditional display logic to your page

Oracle JDeveloper 10g: Build Applications with ADF 14-23

Practice 14: Overview

This practice covers the following topics:


Modifying visual elements of a JSP
Using the formatting toolbar
Using the Property Inspector

14-24

Adding navigation buttons to a JSP


Adding a button to a JSP that invokes an external
Web page
Creating a style sheet and applying it to the JSP

Copyright 2004, Oracle. All rights reserved.

Practice 14: Overview


In this practice session, you will use the formatting toolbar and the Property Inspector to modify
the way a JSP looks, and you will use the Structure pane to modify its data elements. You will
add buttons to the JSP for navigation and for opening an external Web page. You will create a
style sheet, add it to the Component Palette, and apply it to the JSP.

Oracle JDeveloper 10g: Build Applications with ADF 14-24

Practice 14-1
At this point, the pages that you have built are displayed by using a default presentation, which is
not bad, but probably is not good enough for an enterprise application. In this practice, you add a
few things that make the pages more user-friendly.
Start JDeveloper, and open the practice14 workspace.
1. Create a heading page.
a. In the Page Flow Diagram, create a JSP page and name it /heading.jsp.
b. Add Welcome to the top of the page. Use a messageBean for consistency.
c. Next, add a JSTL out tag to get sessionScope.customerName.
${sessionScope.customerName}
d. In the Component Palette, select CSS from the list and drag the JDeveloper CSS to
the page.
2. Include the heading page in all pages.
a. Select the logon page.
b. Select the JSP jsp:include tag and drag it to the top of the page.
c. Use the Browse button to find and select the heading page.
d. Repeat the operation for the categories, products, and shoppingCart pages.
3. Update the CSS to make your read-only tables more readable.
a. Select the CSS | jdeveloper.css node in the Web Content folder.
b. In the Structure pane, select the TH node.
c. In the Property Inspector, set the background-color value to #336699 or a color of
your choice.
d. Set the color to White.
e. Set the font-style key to italic, font-weight to bold and text-align to center.
4. Update the categories page to use messageBeans for the headings.
a. Open the ApplicationResources file and add the following entries. Save the
file when you are done:
category.id= Category Id
category.name= Name
category.description= Description
b. Open the categories page in the Design Editor.
c. If there is a currency column in the read-only table, select it and
remove it (right-click | table | Delete Column).
d. It there is no title message bean, add it. Set the title message bean style to Heading1
(H1). Make sure to exclude the jsp:include and error tags from the H1 style.

Oracle JDeveloper 10g: Build Applications with ADF 14-25

Practice 14-1 (continued)


e. The default construction of this page includes JSTL tags that populate the heading
row of the page at run time. The values for these default headers are hard-coded and
do not provide for internationalization of the page. Delete all these tags in the table
headers (JSTL tags).
f. Drop a Struts bean message tag in each column header and set the key value to the
corresponding key value. This provides for internationalization of the headers.
5. Update the other pages in your application to follow the same style and standard:
shoppingCart
products
6. Add a total to the ShoppingCart.
a. Insert a new blank row at the bottom of the shoppingCart table.
b. Add a jstl:out tag to the last column in the new row.
c. Use ${sessionScope.cartTotal} as the value for the out tag.
7. Build, run, and test your application.

Oracle JDeveloper 10g: Build Applications with ADF 14-26

Adding JAAS Security to the Client

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Practice
Total

Timing
45 minutes
45 minutes
90 minutes

Objectives

After completing this lesson, you should be able to do


the following:
Describe how Java Authentication and
Authorization Services (JAAS) works in a Web
application
Use JAAS to add security to an application
Add users and roles to an application deployment
descriptor
Add JAAS security to a Web application

15-2

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 15-2

JAAS Provider

The JAAS provider supports:


Storage, retrieval, and administration of:
- Realm information (users and roles)
- Policy (permissions)
Multiple repositories:
- XML based
- LDAP based
Login modules

It works with J2EE declarative security model:


Is part of the deployment model
Requires little or no programming

15-3

Copyright 2004, Oracle. All rights reserved.

JAAS Provider
The JAAS provider supports management of realm information, which contains user and role
properties. It also manages policy information, which it uses to determine who can do what in an
application. JAAS uses a repository to keep all this run-time information. The repository can be
either a Lightweight Directory Access Protocol (LDAP)based repository or an XML file. A
JAAS provider also uses login modules for obtaining user information.
JAAS works with the Java 2, Enterprise Edition (J2EE) declarative security model. This model
runs with a J2EE application container and is part of the deployment model. It can be
implemented with little or no programming.

Oracle JDeveloper 10g: Build Applications with ADF 15-3

Defining Security Needs

Determine the logical roles in an application:


Customer
Buyer
Administrator

Determine authorization constraints: Who can do


what actions.
Decide provider type:
XML- based flat file
LDAP (Oracle Internet Directory)

15-4

Map security roles to users and groups.

Copyright 2004, Oracle. All rights reserved.

Defining Security Needs


The first step in implementing security for an application is to decide what type of security is
needed. Do you want to write your own security mechanisms? Do you want to use an existing
scheme? Do you need to authenticate users only, or do you need to restrict access to some
functions by a user?
You also need to decide what provider type you are going to use.
You also need to map security roles to specific users and even groups of users.

Oracle JDeveloper 10g: Build Applications with ADF 15-4

Oracle JAAS Implementation: JAZN

OracleAS Containers for J2EE (OC4J) implement a


JAAS provider called JAZN.
The Oracle provider supports:
Integration with single sign-on (SSO)
Access control through Java 2 permissions
Secure file-based storage of user passwords

JAZNUserManager
Obfuscates passwords in flat file storage
Supports full role-based access control
Supports full support for Java 2 permissions model

15-5

Copyright 2004, Oracle. All rights reserved.

Oracle JAAS Implementation: JAZN


Software vendors provide specific implementations of a JAAS provider. The OracleAS
implementation of JAAS is named JAZN. The Oracle provider (JAZN) supports integration with
Oracle Single Sign-On, access control through standard Java 2 permissions (policies), and secure
file-based storage of user passwords.
JAZNUserManager provides password protection through obfuscated passwords in the jazndata.xml file. It also supports full role-based access control.

Oracle JDeveloper 10g: Build Applications with ADF 15-5

Client Authentication

Authentication:
Determines who clients are
Can they prove it?

JAAS integrates any number of authentication


schemes, for example:
SSO: Uses OracleAS Single Sign-On
SSL: Uses secure sockets layer (SSL) for client
certificate-based authentication
Basic authentication: Prompts for username and
password
Write your own login module.

15-6

Copyright 2004, Oracle. All rights reserved.

Client Authentication
Authentication is the part of JAAS that ensures that the given users (principals) are who they say
they are. This is the first part of the security model. After users are identified and it is verified
that they are who they say they are, they are considered authenticated. The next step is to check
what they are authorized to do.
JAAS integrates with well-known and used authentication schemes.
SSO: An Oracle feature that integrates with an application deployed to OracleAS. The
authentication and authorization is specified and controlled by deployment descriptor files
on the server.
SSL: This authentication scheme is based on using certificates that are passed from a
browser and validated by the application.
Basic: The user is prompted for a username and password. The values are validated by a
login module.
Write your own login module: You can write your own login module to authenticate
against any data source or authentication mechanism. These modules can include any type
of authentication, including biometrics, smartcards, and others.

Oracle JDeveloper 10g: Build Applications with ADF 15-6

Client Authorization

15-7

Client authorization is specified in J2EE


deployment descriptors.
Every client obtains a security principal.
A client can invoke a URL or a method only if the
clients role has the associated rights.
The J2EE container enforces security policies and
provides tools for managing security.
Struts includes roles at the node level.

Copyright 2004, Oracle. All rights reserved.

Client Authorization
The security roles that are defined by the application assembler provide the deployer with a
logical and simplified security view of the Web application. The deployer is responsible for
mapping the logical security roles to principals or to groups of principals that are defined in the
target operational environment.
At run time, a client is allowed to access a URL or invoke a business method only if the principal
making the request is authenticated and authorized (by being associated with an appropriate
security role) to access the requested resource. The container provider enforces the security
policies at run time and provides the tools for managing security during deployment and at run
time.
The security view defines the various types of users of the application and their rights to invoke a
URL request or methods in the enterprise bean interfaces.
Note: The security roles define the logical security view of an application. They should not be
confused with the user groups, users, principals, and other concepts that exist in the target
enterprises operational environment.
The security roles and information are configured and mapped in configuration files and
deployment descriptors.

Oracle JDeveloper 10g: Build Applications with ADF 15-7

Basic Authentication Scenario


Oracle Containers
for J2EE
WebApp
HTTP client

Servlet 1 Servlet 2

OracleAS

JAAS

OracleAS
JAZN Provider

JAZNUserManager
JAAS
HTTP Server

15-8

OracleAS
JAAS Policy

Copyright 2004, Oracle. All rights reserved.

Basic Authentication Scenario


The basic scenario for authenticating and authorizing a user in a J2EE Web application includes
a number of J2EE components that work together to service the application requests and provide
security. The typical scenario is:
HTTP client tries to access the Web application.
The JAAS provider retrieves the user credentials.
The JAAS provider authenticates the user based on the JAZN provider.
The JAAS provider authorizes the user based on define permissions and roles.
The servlets code runs under the AccessControlContext of the user.
SecurityManager returns safely and the client HTTP request proceeds.
For more detailed information about J2EE security, see http://java.sun.com/j2ee. For more
information about the Oracle implementation of JAAS, see the Oracle Application Server
Containers for J2EE Security Guide.

Oracle JDeveloper 10g: Build Applications with ADF 15-8

Adding JAAS Security to an Application

JDeveloper provides a dialog box to help add


JAAS security to an application.
By using the dialog box, you do not have to
directly edit the XML files.
Security settings are maintained in the web.xml
file.
Access the settings:
Right-click web.xml in the Applications Navigator.
Select properties from the context menu.

15-9

Copyright 2004, Oracle. All rights reserved.

Adding JAAS Security to an Application


JDeveloper provides a wizard to help add security settings to the deployment descriptors without
having to edit the XML files directly. The wizard enables you to add or change any of the
properties within the web.xml file. To access the wizard, right-click the web.xml node in the
Applications Navigator, and select properties.
The web.xml file contains the security authorization scheme.

Oracle JDeveloper 10g: Build Applications with ADF 15-9

Adding Authorization Information to Struts

15-10

The Struts configuration includes an authorization


scheme.
The scheme specifies authorization at the node
level.
Specify the authorized role
in the Property Inspector.

Copyright 2004, Oracle. All rights reserved.

Adding Authorization Information to Struts


Struts provides the ability to use an authorization scheme at the node level. This means that you
can restrict access to pages and actions in a Struts application. You set the restriction by adding a
role to the node. For example, you select the categories node on the Page Flow Diagram. Then,
in the Property Inspector, enter a list of comma delimited values that the Web application will
use to restrict access. The roles are the groups that you specified in the jazn-data.xml file.

Oracle JDeveloper 10g: Build Applications with ADF 15-10

web.xml Properties

To implement JAAS security, modify:


Security roles: Add the security role that you want
to use.
Add a Web resource:
Specify any unique name.
Add a URL pattern to validate.
On the Authorizations tabbed page, select the user
role.

15-11

Copyright 2004, Oracle. All rights reserved.

web.xml Properties
The web.xml file holds information used by the J2EE container to provide security services.
One of the properties is the security roles that are authorized to use the application. The users (or
principals) that belong to these roles are defined in the jazn.xml file that you looked at in an
earlier lesson.
Next, specify a Web resource name to which security properties will be applied. This Web
resource must have a unique name, which should include a URL pattern that will be validated
and the user role that will be allowed to use the resource.
Note that URL patterns are used for the original request, and not on internal subsequent calls
such as <jsp:include> and <jsp:forward>. It is assumed that your application will not
forward a user request to any unauthorized page.

Oracle JDeveloper 10g: Build Applications with ADF 15-11

web.xml Results

<web-app>

<security-constraint>
<web-resource-collection>
<web-resource-name>TestApplication</web-resource-name>
<url-pattern>/</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>users</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>users</role-name>
</security-role>
</web-app>

15-12

Copyright 2004, Oracle. All rights reserved.

web.xml Results
In this portion of the web.xml file, you can see that the authorization entries are added. These
entries are used by the J2EE container to enforce your security constraints.

Oracle JDeveloper 10g: Build Applications with ADF 15-12

Adding Users and Roles

15-13

JDeveloper provides a wizard interface to the


jazn-data.xml file.

Select Tools > Embedded OC4J Server Preferences.

Copyright 2004, Oracle. All rights reserved.

Adding Users and Roles


JDeveloper provides a graphical user interface (GUI) wizard to help manage the jazndata.xml file. To open the wizard, select Tools > Embedded OC4J Preferences. This wizard
provides easy access to all the OC4J settings.

Oracle JDeveloper 10g: Build Applications with ADF 15-13

Adding Users

15-14

Copyright 2004, Oracle. All rights reserved.

Adding Users
From this dialog box, you can add, remove, and edit users within a realm. To add a user, click
the Add button and complete the Name and Credentials fields. This will be the username and
password for this user. The next step is to assign this user to a role or roles.

Oracle JDeveloper 10g: Build Applications with ADF 15-14

Managing Roles

15-15

Copyright 2004, Oracle. All rights reserved.

Managing Roles
Access to application resources is controlled through roles. Each user participates in one or more
roles. In this dialog box, you can define roles and add or remove users from roles.

Oracle JDeveloper 10g: Build Applications with ADF 15-15

Selecting a Specific jazn-data.xml File

JDeveloper allows you to specify which JAZN file


to use at runtime in the application configuration.
To change files:

15-16

Right-click the application module


Select configurations
Edit the jbo.security.config property
Enter the path to your jazn-data.xml file

It gives you testing and deployment flexibility.


To use LDAP, change the jazn.xml file.

Copyright 2004, Oracle. All rights reserved.

Selecting a Specific jazn-data.xml File


You can specify which jazn-data.xml file you want to use at run time. JDeveloper lets you
set the jbo.security.config property in the application module to select a specific file. This gives
you the flexibility to test with one set of application credentials and deploy with another.
In addition to using the jazn-data.xml file for user authentication, you can use Oracle
LDAP (Oracle Internet Directory) service for authentication. To use LDAP, change the
jazn.xml file to point to LDAP instead of jazn-data.xml. Configuring LDAP is beyond
the scope of this lesson. Please see the documentation for further information.
To use LDAP, comment the JAZN line and uncomment the LDAP line in the jazn.xml file.
<jazn provider="XML" location="./jazn-data.xml" persistence="VM_EXIT" />
<!-- <jazn provider="LDAP" location="ldap://myoid.us.oracle.com:389" />

Oracle JDeveloper 10g: Build Applications with ADF 15-16

Running the Application

15-17

Test the application.


The browser prompts
for username and
password.
The application is
opened if the user is
authenticated and
authorized.
If either fails, the
application is not
authorized to run.

Copyright 2004, Oracle. All rights reserved.

Running the Application


You can now test the application by using the security model. Right-click the strutsconfig.xml file in the Applications Navigator and select the page that you want to run. When
the browser runs, it prompts for a username and password. If you enter a valid username and
password, the application runs; if not, the browser displays an unauthorized message.

Oracle JDeveloper 10g: Build Applications with ADF 15-17

Summary

In this lesson, you should have learned how to:


Use JAAS to add security to an application
Add users and roles to an application deployment
descriptor
Add JAAS security to a Web application
Describe how JAAS works in a Web application.

15-18

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 15-18

Practice 15-1
In this practice, you will change the logon routine to use JAZN security authorization.
In earlier practices, you used a method in the SalesAppModuleImpl class to find customer
information based on a logon page. The method accepted a username and password, performed a
lookup in the Customers table, and returned a concatenated username. You then used that name
to display in the heading for each of the pages in your application. Now you will use another
method that gets the user ID from JAZN.
Start JDeveloper, and open the practice15 workspace.
1. First, you will configure the application to use JAZN security for authentication.
a. Right-click the web.xml file and select properties to edit the deployment descriptor.
b. Select the Login Configuration node and then select HTTP Basic Authentication for
the authentication type.
c. Add a new security role by selecting the Security Roles node. Click the Add button
and enter users as a new role.
d. Next add a security constraint by clicking the Security Constraint node and clicking
the New button at the bottom of the navigator.
e. Add a new Web resource and name it SalesApp.
f. Add a URL pattern and set the value to /.
g. Next, click the Authorization tab, and click users to authenticate that group to your
application.
h. Test the application. You can right-click on any page on the pageflow diagram and
select run. Because the entire application is protected, anywhere you choose to start
will require a JAZN logon. The valid user IDs are user with the password of 456,
SCOTT with a password of TIGER, and anonymous with any character as a
password. Try to use an invalid ID or password.
2. Now that you have JAZN working to authenticate users, add an action that will use the
JAZN authenticated user ID to look up customer information and store it in
sessionScope.customerName.
You will add a new path to the categories page, which will use this DataAction. In reality,
you may replace the current authenticateUser DataAction with this new one, but you
should be able to compare the two techniques.
a. Add a DataAction to the Page Flow Diagram, and name it authenticateUserJAZN.
You can do this on the diagram or change path in the Property Inspector
b. Expand the SalesAppModule node in the Data Control Palette, and drag the
findCustomerJAZN method to the new DataAction.
c. Select the authenticateUserJAZN node in the Structure pane and change the
resultLocation value to {sessionScope.customerName}. This will put the
results of the findCustomerJAZN method into the session variable customerName.
d. Add a page link from the Welcome.jsp page to the new DataAction.
e. Add a forward from the DataAction to the categories page.

Oracle JDeveloper 10g: Build Applications with ADF 15-19

Practice 15-1 (continued)


3. Add users to the JAZN definition, and test the application.
a. Add two new JAZN users. From the JDeveloper menu, select Run | Terminate |
Embedded OC4J Server, if the option is available. Next, select Tools | Embedded
OC4J Server Preferences. Under the Global node, expand the Authentication (JAZN)
node. Expand Realms | jazn.com and click the Users node. Add two users: user 101
with a password of 101, and user 102 with a password of 102. Select the Roles node
and click users in the Roles pane. Click the Member Users tab and move users 101
and 102 to the selected pane. Click OK.
b. Right-click the welcome.jsp page and select Run from the context menu. When
prompted, enter a user ID and password. The valid user IDs are 101 and 102. The
passwords are the same as the user IDs.
c. Click the authenticateUserJAZN link. This is the new link that you just added.
d. Notice that you are directed to the categories page and that the username is displayed
at the top of the page.
e. Experiment with other user IDs, including invalid IDs.
f. Close the application when you have done testing.

Oracle JDeveloper 10g: Build Applications with ADF 15-20

Building ADF UIX View Components

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Practice
Total

Timing
45 minutes
30 minutes
75 minutes

Objectives

After completing this lesson, you should be able to do


the following:
Describe the characteristics of ADF UIX
Define the structure of a UIX XML page
Build a UIX XML page
Add components to a UIX XML page
Create data-centric pages with data components
Run and test a UIX XML page

16-2

Copyright 2004, Oracle. All rights reserved.

Objectives
This lesson introduces ADF UIX. The lesson shows you how to build a UIX XML page and add
data components. The lesson explores the structure of a UIX XML page. The design-time
environment, including the Visual Editor, Data Component Palette, and Property Palette, is
examined.

Oracle JDeveloper 10g: Build Applications with ADF 16-2

Why ADF UIX Technologies?

Design-time benefits

Run-time benefits

16-3

WYSIWYG/Declarative development environment


Open, flexible framework
Customization
Streamlined design workflow
Standards
Platform independence
Internationalization and accessibility support
High interactivity

Copyright 2004, Oracle. All rights reserved.

Why ADF UIX?


Companies creating e-business applications face tremendous challenges adapting to rapid
development cycles and robust infrastructure requirements that Internet application development
demands.
The ability to design and implement high-quality, professional Web applications faster than
before gives companies a competitive advantage in a market that is constantly facing changing
requirements.
Based on the latest standards of Java 2, Enterprise Edition (J2EE) and Extensible Markup
Language (XML), ADF UIX is designed to give both user interface designers and application
developers an extensible framework for building scalable Web applications with a consistent
look and feel. Using ADF UIX, you can develop any kind of page-based application for desktop
and mobile devices.
ADF UIX Technologies (or UIX) is an open framework for building J2EE-compliant Web
applications. It includes Java class libraries, APIs, parsers, and other software for creating Web
applications with page-based navigation, such as an online shopping application.
You can use ADF UIX to develop the entire application or different aspects of an application
based on the Model-View-Controller (MVC) Model 2 design pattern.

Oracle JDeveloper 10g: Build Applications with ADF 16-3

What are ADF UIX Technologies?

ADF UIX Technologies are a framework based on the


MVC model.
UI Components

Servlet

View

Controller

Model
Any data source

16-4

Copyright 2004, Oracle. All rights reserved.

What Is ADF UIX?


ADF UIX is both a framework and a rich library of user interface components for developing
interactive Web applications with a consistent look and feel.
The ADF UIX framework is based on the Model 2 implementation of the MVC design pattern,
where the business logic of an application is separated from the presentation layer, and a servlet
manages client communication and business logic execution. This framework simplifies adding
and modifying client types, views, and workflow in application development.
ADF UIX enables you to develop the View and Controller layers of an application. The View
layer represents the visual aspects of the application, where data is presented to the user and the
user can provide input to the application. The Controller part provides the interactions with the
clientit maps incoming client requests to operations on the application model, and selects and
formats the next client view to display.

Oracle JDeveloper 10g: Build Applications with ADF 16-4

How Do ADF UIX Technologies Work?

1. ADF UIX components are assembled.


2. They are rendered into Markup pages.
3. They are delivered to a variety of clients.

UIX Page

16-5

Markup

Copyright 2004, Oracle. All rights reserved.

Employing ADF UIX Technologies


ADF UIX pages constitute the core visual aspects of an application. You use UIX XML
Components to create ADF UIX pages.
A UIX XML page lets you specify the page layout, data sources, and events for a user interface.
An application usually consists of multiple units of user interfaces or UIX XML pages. For
example, one page may represent the order details in an online shopping application and another
page may represent the shipping form.
Each UIX XML page is the logical representation of a user interface in an application. The same
logical page can be presented as an output page for many client devices; for example, an HTML
page for a Web browser.
Dynamic data content in a UIX XML page is achieved through data binding with any source.
ADF UIX has built-in data binding support for ADF Business Components and JavaBeans. ADF
UIX and ADF Business Components are only covered in this lesson. You many find more
information about UIX XML and JavaBeans in JDevelopers help documentation.

Oracle JDeveloper 10g: Build Applications with ADF 16-5

UIX XML Page Layout

1.
2.
3.
4.
5.

16-6

Page Header
Tabs and Navigation
Global Buttons
Data Component Area
Page Footer

Copyright 2004, Oracle. All rights reserved.

Defining the UIX XML Page Layout


Page Header (Corporate and Product Branding)
You can specify the Corporate and Products Branding images and associated link for the new
UIX XML pages.
Tabs and Navigation
The information about the tab bars and related navigation links for the new UIX XML pages is
located here. Enter the text that will appear on each tab and the destination URL that will execute
when the user clicks the tab.
Global Buttons
Information about the global buttons and related links for the new UIX XML pages is specified
here. Global buttons are available from every page in an application and appear at top right of
the page.
Data Component Area
In this location, all the data components are displayed. The source of the data may be ADF
Business Components or JavaBeans.
Page Footer (Copyright Information)
Specify information about the copyright message, privacy message, and privacy statement that
will appear in the footer of the new UIX XML pages.

Oracle JDeveloper 10g: Build Applications with ADF 16-6

Interface Nodes

Each page is divided into a hierarchical set of nodes,


each node corresponding to a specific section of the
page.

16-7

Copyright 2004, Oracle. All rights reserved.

UIX XML Interface Nodes


A UIX XML page consists of a hierarchical tree of user interface nodes. Each user interface node
can have none, one, or more child nodes; this means a node can be a parent and a child node at
the same time.
User interface nodes define both the visible and nonvisible user interface components on a page.
Examples of visible user interface components include text and images, and standard HTML
controls such as buttons and check boxes. Nonvisible user interface components do not map to
visible objects, but they organize and manage the layout, appearance, and behavior of other
components. For example, the StackLayout component does not define a visible object, but it
causes the child components to lay out vertically in a page.
Thus, a logical tree-like structure of parent and child nodes form the basis for the construction of
a visual, physical hierarchy of user interface components on a page for a browser or a mobile
device. The page construction occurs dynamically through client-specific renderers of the UIX
XML Components.

Oracle JDeveloper 10g: Build Applications with ADF 16-7

How Is It coded?
UIX XML is a dialect of the XML language for creating ADF
UIX pages declaratively.

16-8

Copyright 2004, Oracle. All rights reserved.

Coding a UIX XML Page


UIX XML is a dialect of the XML language for creating UIX pages declaratively. Using UIX
XML elements, you can specify user interfaces and link them to data sources and events.
Like XML documents, you write your UIX XML documents or pages in a text format. UIX
XML pages must be well formed and valid, complying with schemas that describe rules for UIX
XML elements semantics and XML syntax.

Oracle JDeveloper 10g: Build Applications with ADF 16-8

Support for Internationalization

UIX supports client-specific renderers, which:


Are portable to different locales, fonts platforms,
and browsers
Process text separately from images (local
imaging)
Use run-time cascading style sheets with
environment style information

16-9

Copyright 2004, Oracle. All rights reserved.

Using Internationalization and UIX XML


ADF UIX includes image generation and style sheet management technologies, which together
with the client-specific output renderers of ADF UIX components make UIX XML user
interfaces portable across different locales, fonts, platforms, and browsers.
The ADF UIX image generation technology enables you to incorporate localized images in your
applications with minimal effort. ADF UIX processes text separately from images, so your
translators need to provide resource files for the translated text only. At run time, UIX XML
dynamically combines the translated text with the images to create localized images.
The ADF UIX style management technology enables you to define and customize style sheets
for different end-user environments easily. ADF UIX uses a single XML style sheet document to
contain styles for all end-user environments, including locales, browsers, and platforms. At run
time, ADF UIX generates a cascading style sheet (CSS) by using the environment-specific style
information in the style sheet document, as determined by the locale and platform information in
the HTTP request.

Oracle JDeveloper 10g: Build Applications with ADF 16-9

User Interface Components

UIX XML pages are composed


of interface components, which
can be classified into three
types:
Simple
Layout
Composite

16-10

Copyright 2004, Oracle. All rights reserved.

Using ADF UIX Components


The ADF UIX components that you use to create your user interfaces can be broadly divided into
three groups:
Simple components define visible objects such as text and images, and objects that map to
standard HTML controls on a page. Examples include Button, Image, and Text
components.
Layout components do not map to visible objects but define the appearance, behavior, and
position of other visible objects. Examples include TableLayout, PageLayout, and
StackLayout components.
Composite components define more complex visible objects that have greater interactive
usage. Examples include Shuttle, HideShow, and Tree components.

Oracle JDeveloper 10g: Build Applications with ADF 16-10

Modular Declarative Design

16-11

Copyright 2004, Oracle. All rights reserved.

Declarative Development with ADF UIX


ADF UIX, a dialect of XML, enables you to create UIX XML pages and manage application
flow by using the familiar syntax of XML. With this technology, you define user interfaces, data
sources, and events in UIX XML pages.
Client-side validation and errors during data binding and event handling are also managed in
UIX XML pages. In short, UI designers and developers, and Controller developers can use UIX
XML.
Model developers can use any back-end technology that best meets the needs of the application,
because ADF UIX can glue any model code in UIX XML pages through data binding.
For more information about UIX XML, see the JDevelopers ADF UIX Developers Guide.

Oracle JDeveloper 10g: Build Applications with ADF 16-11

Creating a UIX XML Page

16-12

Copyright 2004, Oracle. All rights reserved.

Using the Wizard


The wizard is used to create new UIX XML pages or UIX XML templates (UIT). You can
choose the following from these wizards:
UIX XML Page Based on Existing UIX XML Template (UIT): Launches the UIX XML
page based on the UIT Wizard that creates a new UIX XML file based on a template (UIT)
definition file. Use this wizard to create application pages based on a template that you
previously created and saved.
UIX XML Page with Header, Footer, and Navigation: Launches the UIX XML Page
Wizard that creates a new UIX XML file that includes header, footer, tab bar, global
button, and page header sections, which can be modified as needed. Use this wizard if you
do not want to create pages based on a template.
UIX XML Template (UIT) with Header, Footer, and Navigation: Launches the UIX
XML Template (UIT) Wizard that creates a new UIX XML template (UIT) definition file
that includes header, footer, tab bar, global button, and page header sections, which can be
modified as needed. After you create a template with this wizard, you can base all the
pages in your application on it.

Oracle JDeveloper 10g: Build Applications with ADF 16-12

Company and Product Branding

16-13

Copyright 2004, Oracle. All rights reserved.

Branding a Page
Company Branding
Use a wizard page to specify the Corporate Branding image and associated link for the new UIX
XML pages. Click Select Image to select the image that you want to use in the Corporate
Branding section in the top left area of the page. Enter the destination URL that will execute
when the user clicks the Corporate Branding image specified above.
Product Branding
This dialog box is similar to Corporate Branding. Use it to specify the Product Branding image
and associated link for the new UIX XML pages. Click Select Image to select the image that you
want to use in the Product Branding section in the top left area of the page. Enter the destination
URL that will execute when the user clicks the Product Branding image specified above.

Oracle JDeveloper 10g: Build Applications with ADF 16-13

Page Tabs

16-14

Copyright 2004, Oracle. All rights reserved.

Incorporating Tabs on a Page


You may specify information about the tab bars and related links for the new UIX XML pages.
Tab Text: You can enter the text that will appear on each tab.
Tab Destination: Enter the destination URL that will execute when the user clicks the tab.
Click Add Tab to add a new line where you can enter the Tab Text and Tab Destination.
Click Remove Tab to remove the selected tab from the list box above so that it is not added
to your page.
Specify the selected tab index (starting from 0). (Displays only in the UIX XML Wizard.)
Specify which tab will be in front when the page displays by entering the associated tab
number. Entering 0 causes the first tab in the sequence to be in front.

Oracle JDeveloper 10g: Build Applications with ADF 16-14

Global Buttons

16-15

Copyright 2004, Oracle. All rights reserved.

Adding Global Buttons


Use this page in the wizard to specify information about the global buttons and related links for
the new UIX XML pages. Global buttons are available from every page in an application and
appear at top right of the page.
Text: Enter the text that will appear on each global button on the page.
Destination URL: Enter the destination URL that will execute when the user clicks the
global button.
Image Location: Specify the image that you want to appear on the global button. Click
Add Button to add a new line where you can enter the Text, Destination URL, and Image
Location. Click Remove Button to remove the selected global button from the list box
above so that it is not added to your page.

Oracle JDeveloper 10g: Build Applications with ADF 16-15

Page Footers

16-16

Copyright 2004, Oracle. All rights reserved.

UIX XML Page Footers


Use this dialog box to specify information about the copyright message, privacy message, and
privacy statement that will appear in the footer of the new UIX XML pages.
Copyright message: Incorporate the text that will appear as the copyright message.
Privacy message: Enter the text that will appear as the privacy message.
Relative link to privacy statement: Use the relative path to the file that will display the
complete privacy statement.

Oracle JDeveloper 10g: Build Applications with ADF 16-16

Designing with the Visual Editor

16-17

Copyright 2004, Oracle. All rights reserved.

Using the Visual Editor


A design-time tool for creating and editing UIX XML pages visually is available in Oracle
JDeveloper 10g.
The Visual Editor enables you to select, move, copy and paste, and delete UIX XML elements.
You can also drag UIX XML elements from the Component Palette to the Visual Editor.
Changes made in the Visual Editor are automatically synchronized and refreshed in the XML
Editor and Structure window.

Oracle JDeveloper 10g: Build Applications with ADF 16-17

Coding with the XML Editor

16-18

Copyright 2004, Oracle. All rights reserved.

Coding with the XML Editor


The schema-based XML Editor in Oracle JDeveloper 10g includes a specialized schema for
editing UIX XML pages.
You can invoke code insight and tip insight while editing UIX XML filescode insight opens a
list with valid UIX XML elements or attributes; tip insight displays the type of value required for
an attribute.
Proper indentation of the elements and validation against the schemas referenced in the UIX
XML page are just a mouse click away at any time during editing.
You can also select ADF UIX elements from the Component Palette for your pages. The ADF
XML elements are included on several Component Palette pages, such as ADF XML Simple
Components, ADF XML Page Layout, and ADF XML Table. Context-sensitive help for each
ADF XML element is available from the Component Palette.

Oracle JDeveloper 10g: Build Applications with ADF 16-18

UIX XML Page at Run Time

16-19

Copyright 2004, Oracle. All rights reserved.

Run-Time Deployment
UIX XML applications created in Oracle JDeveloper 10g can be deployed directly from the
integrated development environment (IDE).
By default, JDeveloper runs applications in the embedded OracleAS 10g Containers for J2EE
(OC4J) server to enable testing and debugging before deploying to a target application server.
The supported application server connection types are:
Standalone OC4J
OracleAS 10g via local Distributed Configuration Management (DCM)
OracleAS 10g via remote DCM
Deploying UIX XML applications to OracleAS 10g is completely automated in JDeveloper. For
example, when you create an ADF Business Component UIX XML application, JDeveloper
automatically generates a Web Application Archive (WAR) file that contains both the ADF
Business Components and the UIX XML application files. A deployment descriptor file and a
WAR deployment profile are also created.

Oracle JDeveloper 10g: Build Applications with ADF 16-19

Adding Data to the Page


ADF Business Components are a type of data
components that can be added to a UIX XML page.

16-20

Copyright 2004, Oracle. All rights reserved.

ADF Business Components and UIX XML


With JDeveloper, you can easily develop UIX XML pages to query, browse, and edit records for
any view objects defined in Business Components projects. You must already have an ADF
Business Components project in the same workspace as the UIX XML project in which you are
inserting the databound pages.
You can make your UIX XML pages dynamic by using the UIX languages data binding
elements. The UIX XML Business Components Application Wizard enables you to create an
ADF Business Component bound UIX XML application, generating pages for viewing, creating,
and updating each ADF Business Component View selected.
What Are ADF Business Components?
Business services provide a level of abstraction from the underlying datasource. Business
services govern the interaction between the rest of the application and the datasource, providing
validation, specific services, and other business logic. ADF Business Components technology
provides a framework-based method for developing J2EE business services. ADF Business
Components govern interaction between the rest of the application and the data stored in the data
source, providing validation, specific services, and other business logic.

Oracle JDeveloper 10g: Build Applications with ADF 16-20

Design Time Data Components

16-21

Use the Data Control


Palette to include the
data components on the
page.
Modify the prompts or
other attributes with the
Property Inspector.

Copyright 2004, Oracle. All rights reserved.

Data Binding Support in UIX XML


There are four key data binding concepts employed in Oracle ADF. During design, when adding
data components to a UIX XML page, JDeveloper adds all the appropriate code to support these
concepts in your application. The concepts work together to bring data from the business service
objects to be displayed in the view objects.
Data Controls: A data control abstracts the implementation of a business service, allowing
the binding layer to access the data from all services in a consistent way.
Iterator and Control Bindings: A binding container is a named group of related iterator
and control bindings that you use together for a particular page of your application. A
binding container is also referred to as a UI Model, because it provides the appropriate
subset of model data for a specific UI.
Binding Containers: The binding context provides the data environment for your
application. It contains all of the data controls and binding containers that your application
can access.
Binding Context: Bindings are lightweight objects that decouple back-end data and frontend UI display.

Oracle JDeveloper 10g: Build Applications with ADF 16-21

Data Binding in the Visual Editor

16-22

Copyright 2004, Oracle. All rights reserved.

Working in the Visual Editor


The Visual Editor allows for drag and drop inclusion of data controls on a UIX XML page. Each
data component items can be individually selected and modified.
For the Table and Master Detail layout types, the number of records displayed is determined by
the value of the Range Size property for the group. Setting this property determines the number
of rows displayed and the number of rows incremented by the Previous and Next buttons.
Modifying the Number of Rows Displayed
To modify the number of rows of data to be displayed for a data component, perform the steps
below.
1. Open the UIX XML page that contains the table.
2. In the Structure window, select the UI Model tab. This lists all data controls available on
your page.
3. Select the interator that you like to change: CustomerView1Iterator.
4. In the Property Inspector, change the Range Size property to the desired number of rows.

Oracle JDeveloper 10g: Build Applications with ADF 16-22

Run-Time UIX XML Page with Data Binding

16-23

Copyright 2004, Oracle. All rights reserved.

Data Binding at Run Time


During run time, the following features enable the databinding components to work within the
UIX XML page.
Repopulation of valid and invalid form values on a page when any validation failure occurs
and the page is redisplayed with errors automatic mode for region of form elements and
tables
UIX XML form element metadata is bound to ADF BC metadata, such as readOnly
bound to inverse of isUpdateable, required bound to mandatory.
Integration with UIX XML client-side validation mechanisms, such as mandatory form
elements getting a pop-up error window when not filled in; ADF BC server-side validation
errors presented in-line with the form element causing the problem

Oracle JDeveloper 10g: Build Applications with ADF 16-23

Summary

In this lesson, you should have learned how to:


Define and discriminate the ADF UIX XML
components
Construct a UIX XML page by using the wizards
Include data items on a page from the model
Run and test a UIX XML page

16-24

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 16-24

Practice 16: Overview

This practice covers:


Creating a UIX XML page
Adding ADF Business Components
Running the page using OC4J

16-25

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 16-25

Practice 16-1: Building a UIX XML Page


The goal of this practice is to build a UIX XML page, including ADF Business Components, and
then run the page by using JDevelopers OC4J server. The company would like to see what ADF
UIX technologies could do for their online ordering system. To enable them to make a better
decision, they have asked you to build a mock-up of the customers screen by using UIX XML.
They would like to brand the pages and allow users to navigate and find out about products.
Your job is to create the page.
Start JDeveloper, and open the practice16 workspace.
Construct the UIX XML Page
1. In the JDeveloper menu, select the Open menu option and navigate to the practice16
workspace.
2. In the navigator, expand the practice16 node and select the ViewController node. Rightclick and select the New option.
3. In the New window, highlight the ADF UIX node, and in the right pane, select the UIX
XML Page with Header, Footer, and Navigation option. Click OK to invoke the UIX XML
Page Wizard, which enables you to build the page.
4. Populate the wizard properties with the following values.
Step 1: File Name = Customer.uix
Step 2: Page Title = ADF Course Customer Page
Step 3: Corporate Branding = ..\public_html\images\exlibris.gif
Step 4: Product Branding = ..\public_html\images\product.gif
Step 5: Tab Bar = (Specify the selected tab index = 0) and add the following tabs.

Tab Text

Tab Destination

Customers

Products

Details

Step 6: Page Header Text = ADF Course Practice

Oracle JDeveloper 10g: Build Applications with ADF 16-26

Practice 16-1: Building a UIX XML Page (continued)


Step 7: Global Buttons
Text

Destination URL

Image Location

Cart

..\public_html\images\cart.gif

Help

..\public_html\images\help.gif

Logon

..\public_html\images\login.gif

Step 8: Specify your own copyright information.


Press Finish and the Visual Editor will display your page.
5. Right-click on the page in the Visual Editor, and select Run Customer.uix to see the
page run in a browser.

Oracle JDeveloper 10g: Build Applications with ADF 16-27

Practice 16-2: Adding Data Components to a UIX XML Page


The goal of this practice is to include existing ADF Business Components on the Customer page.
The page uses a distinct data component and service named SalesAppModule and the
CustomersView1 view.
Add Data Components to the Customer Page
1. Open the Customer.uix page in the Visual Editor. In the Data Control Palette, expand
the SalesAppModule node exposing the CustomersView1 and Operations nodes.
2. Select the CustomersView1 node and ensure that the Drag and Drop As: pull-down is
set to Read-Only Table.
3. Drag the CustomersView1 from the Data Control Palette to the center of the
Customer.uix page in the Visual Editor.
4. The columns from left to right should include: Select, CustomerId, CustFirstName,
CustLastName, NLS Language, CreditLimit, CustEmail, and Status. You may double-click
each label and change the text property to something that you deem appropriate.
5. Right-click anywhere on the Visual Editor and run the Customer.uix page. Your page
should look similar to the following example.

Oracle JDeveloper 10g: Build Applications with ADF 16-28

Deploying an ADF Application

Copyright 2004, Oracle. All rights reserved.

Schedule:

Topic
Lecture
Lab
Total

Timing
45 minutes
30 minutes
75 minutes

Objectives

After completing this lesson, you should be able to do


the following:
Create a remote OracleAS Containers for J2EE
(OC4J) Connection in JDeveloper
Configure OC4J for application deployment
Use the JDeveloper Deployment Wizard to deploy
to OC4J
Run a JSP application in OC4J

17-2

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 17-2

Overview

Servlet/JSP/HTML

Packaging

Deployment

Libraries, Packages
17-3

Copyright 2004, Oracle. All rights reserved.

Overview
The final destination for your servlet or JavaServer Pages (JSP) is a Web server. You may have a
large number of classes and libraries in your application. In this lesson, you learn how to package
these various entities and deploy them to OC4J. Up to this point, servlets and JSP pages have
been tested by running them in the embedded OC4J server installed with Oracle JDeveloper 10g.
This lesson discusses deployment to a remote OC4J server in a production environment.

Oracle JDeveloper 10g: Build Applications with ADF 17-3

Overall Considerations for Deployment

Packaging and distributing involves:


Class files
Libraries
HTML files

17-4

How you set up the deployment environment


depends on the server.

Copyright 2004, Oracle. All rights reserved.

Overall Considerations for Deployment


All the class files, libraries (including custom tag libraries), and HTML files in your application
can be packaged together for deployment to a Web server. The way these files are packaged and
copied to the Web server is dependent on the server itself.

Oracle JDeveloper 10g: Build Applications with ADF 17-4

J2EE Archive Format

17-5

Archive Type

Module Type

Software Content

Java Archive (JAR)

J2EE client module

Java Application
components

EJB JAR

J2EE EJB module

Enterprise
JavaBeans (EJB)
components

Web Archive (WAR)

J2EE Web module

Servlets and
JavaServer Pages
(JSP) components

Enterprise Archive
(EAR)

Not applicable

J2EE application

Copyright 2004, Oracle. All rights reserved.

Archive Formats
JAR, EJB JAR, and WAR files each contain a module consisting of one or more components.
An Enterprise Archive (EAR) file contains an application consisting of one or more packaged
modules. According to the J2EE specification, every application must be assembled and
packaged as an EAR file before deployment to a J2EE server.
When you create a Web (servlet or JSP) or EJB application and deploy it via an application
server connection, JDeveloper packages it as a WAR or EJB JAR wrapped in an EAR file.
If your application consists of components of different types, the components are packaged into
multiple modules, and you must create an EAR deployment profile to assemble them as an EAR
file.

Oracle JDeveloper 10g: Build Applications with ADF 17-5

Deploying to a Web Server

17-6

Copy the files with the extensions .jsp, .html,


.gif, to the document root directory of the Web
server.
Archive class files in an archive (.JAR, .WAR) file.
Set the class path of the Web server to point to the
archive files.

Copyright 2004, Oracle. All rights reserved.

Deploying to a Web Server


These steps discuss general deployment steps for a generic Web server. Deployment to OC4J is
easy and is discussed in the remainder of this lesson.

Oracle JDeveloper 10g: Build Applications with ADF 17-6

Deploying to OC4J

OC4J is a J2EE-compliant Web server, included with


OracleAS 10g. To deploy to OC4J, perform the
following:
1. Install OC4J.
2. Start the remote OC4J server by issuing the
following from a command prompt:
<oc4j directory> java jar oc4j.jar
3. Create an OC4J Connection in JDeveloper.
4. Deploy the project by right-clicking
webapp1.deploy and selecting Deploy.

17-7

Copyright 2004, Oracle. All rights reserved.

Deployment to OC4J
To deploy to OC4J from JDeveloper, install OracleAS 10g version 10.
Start OC4J by issuing java jar oc4j.jar from the <iASHome>/j2ee/home
directory, where iAS installs OC4J. JDeveloper automatically creates an archived WAR file for
use in deployment to OC4J. The name of this file defaults to <webapp1.deploy> and
contains your project class files, libraries, and database connection information. Your project is
easily deployed from JDeveloper to OC4J by creating a connection to the remote OC4J server,
and right-clicking the .deploy file and selecting Deploy.

Oracle JDeveloper 10g: Build Applications with ADF 17-7

Install OC4J

1. Open a command window.


2. Navigate to <ias_Home>/j2ee/home.
3. Run the following command:
% java -jar oc4j.jar -install

This command unpacks and installs OC4J.


4. Enter a password for the OC4J administrator
account.

17-8

Copyright 2004, Oracle. All rights reserved.

Install OC4J
Install OC4J from a command window that is open and in the <ias_home>/j2ee/home
directory. <ias_home> is usually JDeveloper/j2ee. The java jar oc4j.jar
install command unpacks and installs OC4J. You are required to enter a password for the
OC4J administrator, which you need when deploying from JDeveloper.

Oracle JDeveloper 10g: Build Applications with ADF 17-8

Start the OC4J Server

To start the OC4J server, use the following from the


OC4J home directory, usually
<iAS_Home>/j2ee/home
% java -jar oc4j.jar

The server can be stopped by using the following


command:
% java -jar admin.jar ormi://localhost/
<admin> <password> -shutdown

17-9

Copyright 2004, Oracle. All rights reserved.

Start the OC4J Server


The OC4J server is started by using the Java command to run a jar file. Options can be found in
the OC4J documentation. When successful, the console displays Oracle9iAS Containers for
J2EE Initialized. The admin.jar file is used for restarting and stopping the OC4J server. The
password supplied to admin.jar is specified when installing OC4J. This password is stored in
the principals.xml file. Note that the default install of OC4J starts the server on port 8888.

Oracle JDeveloper 10g: Build Applications with ADF 17-9

Creating an OC4J Connection

17-10

Copyright 2004, Oracle. All rights reserved.

Creating an OC4J Connection


After the OC4J server is installed and started, create a new connection in JDeveloper. Name the
connection and select Standalone OC4J as the connection type.

Oracle JDeveloper 10g: Build Applications with ADF 17-10

Creating an OC4J Connection

17-11

Copyright 2004, Oracle. All rights reserved.

Creating an OC4J Connection (continued)


Supply the username and password for the OC4J server. This user is created when OC4J is
installed, and is stored in the principles.xml file of the config directory. Note that this
file can be encrypted, so you may need to ask your server administrator for the username.

Oracle JDeveloper 10g: Build Applications with ADF 17-11

Creating a Deployment Profile

Creating a deployment profile enables you to specify


how the J2EE application is deployed:

17-12

Copyright 2004, Oracle. All rights reserved.

Creating a Deployment Profile


In the Applications Navigator, click the ViewController project and then select File > New >
Deployment Profile > WAR File J2EE Web Module to create a new deployment profile for a
Servlet/JSP application. Note that JDeveloper automatically creates this file for a J2EE
application. You can specify files for inclusion and other settings, such as the context root for the
application in this file.

Oracle JDeveloper 10g: Build Applications with ADF 17-12

Deploying to OC4J

17-13

Copyright 2004, Oracle. All rights reserved.

Deploying to OC4J
When the connection is created, deploying to OC4J is simple. Right-click the deployment
profile, and select Deploy to > <yourappserverconnection>. Additionally, connections to other
J2EE servers can be created, and applications are deployed to those servers in the same way.
Instructor Note
At this point, you may want to deploy an application, such as lesson17.jpr. Create an OC4J
connection, then right-click the .deploy file to deploy. This course does not include
Oracle9iAS; therefore, students should use a remote OC4J connection by manually starting the
OC4J server included with JDeveloper. Your ability to demonstrate deployment to a truly remote
iAS install will depend on what you have installed on your laptop, but the procedure is the same
for both instances.

Oracle JDeveloper 10g: Build Applications with ADF 17-13

Running Applications

To run the deployed application, call the following


URL:
http://hostname:8888/<workspacename><projectname>-context-root/main.jsp

The context root can be customized in the deployment


profile.

17-14

Copyright 2004, Oracle. All rights reserved.

Running Applications in OC4J


The deployed application is called by accessing the OC4J server at port 8888, and then supplying
the context root directory of the application and the name of the servlet, JSP, or HTML file. Note
that default name for the context root directory is <workspacename>-<projectname>-contextroot.
You can also determine the context root from the message window shown in this slide. Each time
you deploy an application, the context root is displayed in the message window. It is an easy
place to copy the URL and paste it in a browser for testing.

Oracle JDeveloper 10g: Build Applications with ADF 17-14

Customizing Deployment

To change the names of directories used in


deployment, double-click the .deploy file.

17-15

Copyright 2004, Oracle. All rights reserved.

Customizing Deployment
As we have seen, deployment profile uses the project name to identify the application.
Optionally, change the name, context root, and war file names in the Profile Settings dialog box.

Oracle JDeveloper 10g: Build Applications with ADF 17-15

Summary

In this lesson, you should have learned how to:


Package the applications that you develop for
deployment in a Web server
Create an OC4J connection in JDeveloper
Deploy your application to the Oracle9i
Application Server

17-16

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 17-16

Practice 17-1: Overview

This practice covers the deployment of an ADF BCbased JSP application.

17-17

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g: Build Applications with ADF 17-17

Practice 17-1
The purpose of this practice is to deploy a Struts application to OC4J. You will be manually
deploying the application created in practice 14 to a local OC4J server. The OC4J server will
actually be that which is installed with Oracle9i JDeveloper, but the deployment steps are the
same for a production deployment.
1. The ADF framework requires version 1.4 of the Java run time. To make sure that this is the
default version on your machine, run java version from a command prompt. If the
version is not 1.4, change your path statement to ensure that the correct version is used. The
1.4 Java run time is delivered with JDeveloper and is the directory
<Jdev_Home>/jdk/bin.
2. First, install the OC4J server.
a. Open a command prompt and navigate to the <JDEV_Home>/j2ee/home
directory. This is where the OC4J server is installed.
b. Type java -jar oc4j.jar install at the prompt to start the install of the
OC4J server.
c. Specify a password that you want to use (that is, admin).
d. Confirm you password.
3. Next, start the OC4J server.
a. Open a command prompt and navigate to the <JDEV_Home>\j2ee\home
directory. This is where the OC4J server is installed.
b. Type java -jar oc4j.jar at the prompt to start the OC4J server.
c. The server will automatically deploy any .war files that were included in the
deployment directories at install, and when finished will display Oracle
Application Server Containers for J2EE 10g (9.0.4.0.0)
initialized Oracle9iAS (9.0.2.0.0) Containers for J2EE
initialized.
4. Next, create a connection to the OC4J server.
a. Click the Connections tab on the navigator pane. Right-click Application Server and
select New Application Server Connection from the context menu.
b. Name the new connection OC4J, select the StandaloneOC4J type, and click Next.
c. Supply the username and password for the OC4J Connectionthe admin password
is the one that you have specified at install. Select the Deploy Password check box,
and then click Next to continue.
d. Accept the default ormi mappings for the server, and click Next.
e. Test the connection to ensure that the server is running and the username and
password are valid.
5. Set the Welcome.jsp as the default run target for the application.
a. Open the Page Flow Diagram for the application.
b. Right-click welcome.jsp on the diagram.
c. Choose Set as Default Run Target from the context menu.
6. Now create a deployment profile for the application.
a. Right-click the ViewController node, and select New from the context menu.
b. Create a New deployment profile using war file.
c. Specify shoppingApp as the deployment profile name.
d. Click OK to close the Deployment Profile Wizard.

Oracle JDeveloper 10g: Build Applications with ADF 17-18

Practice 17-1 (continued)


7. Finally, deploy the application to the remote OC4J server.
a. Right-click shoppingCart.deploy, and select Deploy to > <Your OC4J
Connection Name>. JDeveloper deploys the application. The status of the
deployment can be seen in the command window started in step 1.
b. Open a browser and navigate to http://localhost:8888. This should display
Oracle9iAS Containers for J2EE 9.0.2.0.0 Up and running. This is the home page
of OC4J.
c. Append the context root for this application to the URL and the beginning JSP for this
application, that is, welcome.jsp. (The context root appears in the deployment log
window of JDeveloper.)
d. Test the application by navigating through it. It should be the same as when you ran it
locally.
e. Close the application when you are done.

Oracle JDeveloper 10g: Build Applications with ADF 17-19

Course Schema

Copyright 2004, Oracle. All rights reserved.

Course Schema

Oracle JDeveloper 10g: Build Applications with ADF A-2

Database Scripts
These SQL scripts are used to modify the default OE schema to meet course requirements.
Add status and discount columns
alter table order_items add (
discount_unit_price number(8,2));
update order_items set discount_unit_price =
(select list_price from product_information where
product_information.product_id = order_items.product_id);
alter table customers add (
status varchar2(10));
update
update
where
update
where

customers set status = 'Silver';


customers set status = 'Gold'
mod(customer_id, 4) = 0;
customers set status = 'Platinum'
mod(customer_id, 5) = 0;

Add Categories table (copy from categories_tab)


create table categories as select * from categories_tab;
alter table categories
add constraint categories_pk1 primary key (category_id);
drop table categories_tab;

Add a foreign key constraint to the categories table from product_information


add constraint product_info_category_fk foreign key (category_id)
references categories (category_id);

Oracle JDeveloper 10g: Build Applications with ADF A-3

Practice Solutions

Copyright 2004, Oracle. All rights reserved.

Practice 2-1
1. Start JDeveloper 10g, and open the practice02sol workspace.
a. Select File > Open.
b. Select the practice02Sol.jws workspace and click Open. The workspace is in the
<JDeveloper>/jdev/mywork/practice02Sol directory.
2. Create a new JDBC connection.
a. Expand the Connections node in the JDeveloper Connections Navigator pane.
Hint: Click the Connections tab at the bottom of the System Navigator pane.
b. Right-click Database and select New Database Connection from the shortcut menu,
which launches the Database Connection Wizard. Then, click Next.
c. Enter OE in the Connection Name field, and select JDBC as the connection type. You
can choose any name that you want, but the practices and examples all use OE as the
connection name. Then, click Next.
d. Enter the username and password that was given to you by your instructor for your
database, and select Deploy Password. Leave the Role field blank. Then, click Next.
e. Select the thin JDBC driver.
f. Enter the host ID, SID, and port number that was given to you by your instructor. Then,
click Next.
g. Click the Test Connection button to test the connection.
h. Click Finish to save the connection.
3. Start the Application.
a. Click the Applications tab and expand the practice02Sol node.
Hint: The Applications tab is at the bottom of of the System Navigator pane.
b. Expand the ViewController node
c. Expand the Web Content node, right-click the welcome.jsp node, and select the run
option from the context menu.
4. Explore the functionalities of the Application.
a. In the new Browser window, use the links to navigate through the application screens.
b. You can log on by using one of the following usernames and customer IDs:
Welles
101
Pacino
102
Taylor
103
Sutherland
104
MacGraw
105
Hannah
106
c. Experiment with the process of ordering items.

Oracle JDeveloper 10g: Build Applications with ADF B-2

Practice 2-1 (continued)


5. Create a new default Application Workspace.
a. Start the Application Wizard by selecting File > New from the menu or by
selecting New from the Workspace shortcut menu (right-click the workspace
node, and select New from the context menu).
b. Select Workspaces > Application Workspace from the New Gallery.
c. In the Application Wizard, change the name of the Application to practice02.
d. Leave the default values for the Directory Name and Application Package Prefix.
e. Make sure that the Application Template is Web Application [Default].
Hint: The Application Template drop-down list is near the bottom of the wizard
window.
f. Click the Manage Template button to see which technologies are used by the Web
Application [Default] template.
g. In the navigator under the Web Application [Default] node, select View and Controller.
h. The Available Technologies shows all the possible technologies that are relevant for
your project.
i. Select the Data Model node in the navigator. This displays additional technologies that
can be added to the default ones.
j. Click Cancel and then OK to create the Application Workspace.
Hint: Click Cancel in the Templates window, and then OK in the Create Application
Workspace window.
6. Create a custom Application Workspace.
a. Start the Application Wizard by selecting File > New from the menu or by
selecting New from the Workspace shortcut menu (right-click the workspace
node).
b. Select Workspaces > Application Workspace from the New Gallery.
c. In the Application Wizard, change the name of the application to
practice02custom.
d. Leave the default values for the Directory Name and Application Package Prefix.
e. Click the Manage Template button.
f. Select the Application Templates node, and click the New button at the bottom of the
navigator.
g. In the Create Application Template dialog box, enter MyWebApps as the Template
Name, and click OK.
h. Select the new MyWebApps node in the navigator, and click the New button.
i. Enter MyTechnologies as the Project Template Name and as the Project Name, and
then click OK.
j. Select the MyTechnologies node, and in the Available Technologies list, select
HyperText Markup Language, Java, JavaServerPages, and Toplink.
Hint: You can either click the shuttle button (right arrow in the middle of the window)
or drag the selected items to the right-hand window.
k. Move the selected items in the Selected Technologies list, and then click OK.
l. Click OK to create the Application Workspace.
m. Open the Practice02custom node to see what is added.

Oracle JDeveloper 10g: Build Applications with ADF B-3

Practice 3-1
If needed, restart JDeveloper 10g, and open the practice03 workspace.
Select File > Open.
Select the practice03.jws workspace, and click Open. The workspace is in the
<JDeveloper>/jdev/mywork/practice03 directory.
1. Create Business Components.
a. Expand the practice03 node in the Applications Navigator.
b. Right-click the Model project, and select the New option.
c. Select Business Components > Business Components from Tables, and click OK.
d. Skip the Welcome screen by clicking Next.
Hint: You can click skip this next time to avoid this introduction page in the future.
e. In step 1 of Create Business Components from the Tables Wizard, specify OE as the
schema owner.
f. Select the following tables to create entities:

CATEGORIES
CUSTOMERS
INVENTORIES
ORDERS
ORDER_ITEMS
PRODUCT_INFORMATION

g. Click Next to accept these entity objects and move to the next step.
h. In step 2 of Create Business Components from the Tables Wizard, select all the tables
to create view objects and click Next.
i. In step 3 of the wizard, select the Application Module check box and specify
SalesAppModule in the name field. Then, click Next to review the business
components creation and click Finish to create the components.
2. Test the Business Components.
a. In the navigator pane, right-click your application module (SalesAppModule) and
select Test from the shortcut menu.
Hint: The application module has an icon that looks like a briefcase with a cog wheel
on it.
b. In the dialog box, verify that the middle-tier server type is set to Local and the JDBC
connection is set to OE, and then click Connect.
c. In the browser, double-click CustomersView1 and browse the customers data.
d. Click the blue up oriented icon (eject button) to see CustomersView1 in a separate
window.

Oracle JDeveloper 10g: Build Applications with ADF B-4

Practice 3-1 (continued)


Hint: The eject button has a blue icon that looks like an arrow pointed upward.
e. Double-click OrdersView2, and browse the orders. Click the blue up oriented icon
(eject button) in the View icon bar to undock each one to make them independent
windows. Notice that you can see only the orders for one customer; when you go back
to the CustomersView form and navigate to the next record, you see a different set of
orders. This is because the applications data model specifies the views in an
application as well as how they are linked to each other.
Note: Customers 101170 have orders entered. Use the query function to easily see
those customer rows.
Hint: You can use the query function of the browser by clicking the query toolbar
button. Enter 1 in the customerId field and click query. This will query all customers
with a customerId that begins with 1.
f. Close the two open windows.
g. Double-click OrdersView1, OrderItemsOrderIdFKLink1, and OrderItemsView2.
Click the blue up oriented icon (eject button) in the View icon bar to undock each one
to make them independent windows.
h. Select different rows in each of the windows and notice how they are all synchronized.
i. When you are done, close each of the windows and the Business Components Browser.
3. Create a Business Components diagram for Entity Objects.
a. Select the Model node in the Applications Navigator, and right-click and select the
New option.
b. In the New Gallery, select Business Components > Business Components diagram and
click OK.
c. Specify Entity Objects Diagram as the name, and click OK. (A white area is created in
the middle part for the diagram.)
d. Right-click in the diagram region, and select the Add to diagram option of the
context menu.
e. Expand the Business Components node, and then the Model node.
f. Select the following Entity Objects:

Categories
Customers
Inventories
OrderItems
Orders
ProductInformation

Click OK.
g. Reorganize the layout of the entity objects, and save your work. See the next page for
an example of a suggested layout.
Hint: Reorganize the layout by dragging the objects around to the diagram or by rightclicking on the diagram and selecting one of the automatic layout options.

Oracle JDeveloper 10g: Build Applications with ADF B-5

Practice 3-1 (continued)


Example of the Entity Object Layout

Oracle JDeveloper 10g: Build Applications with ADF B-6

Practice 4-1
This practice illustrates the various ways to create entity objects.
1. Start JDeveloper 10g, and create a new Application Workspace.
Hint: Start the Application Wizard by selecting File > New from the menu or by selecting
New from the Workspace shortcut menu (right-click the Workspace node).
Select Workspaces > Application Workspace from the New Gallery.
a. In the Application Wizard, change the name of the Application to practice04.
b. Leave the default values for the Directory Name and Application Package Prefix.
c. Make sure that the Application Template is Web Application [Default]. Then, click
OK.
2. Create entity objects from tables.
a. Expand the practice04 node in the Applications Navigator.
b. Right-click the model project, and select the New option.
c. Select Business Components > Business Components from Tables.
d. Make sure that the OE connection is selected in the Project initialization page.
e. In step 1 of the wizard, select the following tables:

CUSTOMERS
ORDERS
ORDER_ITEMS

f. Click Next to accept these objects and move to the next step of the wizard.
g. In step 2, select all the entities and create default view objects for them. You are
creating default views so that you can test the entity objects that you will be working
with in this practice.
h. In step 3, enter SalesAppModule for the name of the default application module.
i. Click Finish when you are done.
3. Create a Business Components diagram.
a. Right-click the model project, and select New.
b. Select Business Components Diagram.
c. Name the diagram Entity Objects.

Oracle JDeveloper 10g: Build Applications with ADF B-7

Practice 4-1 (continued)


4. Create entity objects from tables.
a. Go to the Connections Navigator pane.
Hint: The Connections Navigator is one of the tabs at the bottom of the System
Navigator pane.
b. Expand the Database node for your connection and schema name.
c. Expand the Tables node, and select the following tables:

CATEGORIES
PRODUCT_INFORMATION

d. Drag the tables to the diagram.


e. Select Create Business Components Entity Objects from the Create Tables Wizard.
Hint: There are a number of options in this wizard. You can create Java classes, entity
beans, and other object types. For this course, you are creating business component
entity objects.
(Note that the diagram includes OrdersItems. This is because it is related to one or
more of the entities that you added to the diagram.)
f. Select and delete the following objects from the diagram:

CustAddressTyp
SdoGeometry
SdoPointType

Hint: These objects are object type created by default from the table
definitions. You will not use these objects in the application that you are building, so it
is easy and clean to remove them from the entity definition.
5. Add the remaining entity objects to the diagram.
a. In the Applications pane (not the Connections pane), select the remaining entities and
drag them to the diagram:

Customers
Orders

b. Select different layout options to optimize the diagram to your liking.


6. Create entity objects from the Component Palette.
a. In the Component Palette, make sure that it is set to Business Components.
Hint: The Component Palette is to the right of the Business Components Diagram.
b. Click the Entity Object component.
c. Click the diagram to create a new entity object.
d. On the diagram, click the name of the new entity and change it to Inventories.
e. Double-click the Inventories entity object to call the Entity Object Editor.
f. In the Name node, select the INVENTORIES table as the schema object.
g. Select the Attributes node on the left side of the editor, and click the New From
Table button.

Oracle JDeveloper 10g: Build Applications with ADF B-8

Practice 4-1 (continued)


h. Select all the attributes in the list. Click OK to accept your changes on both pages of the
wizard.
i. In the navigator pane, select InventoriesProductIdFkAssoc and drag it to the diagram.
You now have a complete diagram of your entity objects with their associations.
j. Again, you can select different layout options to find one that suits your needs.
k. Save your work.
7. Specify a default value for an attribute.
a. Double-click the Customers entity.
b. Expand the attributes node in the Entity Dialog Navigator.
c. Select the NlsTerritory attribute and enter us as the default value.
8. Map an attribute to a database sequence by using an existing trigger.
a. Open the database connection.
Hint: Remember that the database connection tab is at the bottom of the System
Navigator window.
b. Expand the Schema node.
c. Expand the Trigger node, and note the existing triggers.
d. Double-click the Insert_ord_id trigger and see the corresponding code.
9. Use the database sequence orders_seq to populate the order_id attribute of the Orders
entity.
a. Edit the Orders entity.
b. Change the orderId attribute to a domain type of DBSequence.
Hint: Refer to the section Mapping an Attribute to a Database Sequence if you need
a reminder of how to do this. The ORDERS table has a database trigger that uses a
sequence to populate the ORDER_ID column.
c. Make sure to select the Refresh After Update check box.
10. Use the database trigger on the order_items table to populate the LineItemId attribute of
the OrderItems entity. Perform the same steps that you followed for the Orders entity.
11. Test your code by running the Business Components Browser and inserting rows into Orders
and OrderItems.
a. In the Business Components Browser, double-click the OrdersCustomersIdFKLink1
view.
Hint: Open the Business Components Browser, right-click the application module in
the Model node of the System Navigator, and select Test.
b. Navigate to the Orders pane, and enter a new order. To test your code, all you have to
enter is a date. Use the format yyyy-mm-dd.
c. Commit your change. Note that the new order number is refreshed after the commit.
Hint: Commit your changes by clicking the commit button in the browser main
window. The commit button is the green arrow.
d. Close the browser when you are done.

Oracle JDeveloper 10g: Build Applications with ADF B-9

Practice 4-2
To start this practice, restart JDeveloper, if neccesary, open the practice04 workspace, and
open the model project created in practice 4-1.
1. Add a validation rule to validate customers status.
a. Edit the Customers entity object to add a validation rule.
Hint: Edit the entity by double-clicking the entity in the System Navigator.
b. Your new rule is a ListValidator rule that ensures that the Status attribute has one of the
following values:

Platinum
Gold
Silver

Hint: Add a new rule by clicking the Validation node in the Entity Object Editor,
selecting the Status attribute and clicking the New button at the bottom of the window.
Make sure to select ListValidator as the rule.
c. In the Error Message field, enter Status can only be Platinum, Gold or Silver.
d. Click the OK button twice to add the validation.
e. Save your changes.
f. Select the Customers entity in the navigator pane. Note that the new rule is shown
under the Status attribute as a rule.
2. Validate e-mail attributes using a domain object.
Note that you can create the domain from the New Gallery or by using the Component
Palette when using an Entity Objects diagram.
a. Create a domain object called EmailAddressDomain. Refer to the domain slides in
this lesson if you need a reminder of how to do this. Later in the course, you will add
some code that verifies that an attribute is a valid e-mail address.
Hint: To create a domain, right-click the Model node in the workspace, and select New
Domain from the context menu. You can also select Domain from the Component
Palette of the Business Components Diagrammer and click the diagram.
b. Edit the Customers entity, and set the type of the CustEmail attribute to
EmailAddressDomain.
Hint: To edit an entity, double-click the entity in the System Navigator. Click the
Attributes node in the Entity Editor window, then select the Email attribute and change
the type to EmailAddressDomain.
c. Save your changes.
3. Run the Business Components Browser to check your new validation rules. Try to change the
status of a customer to a value that is not in the list of valid values.
Hint: To run the Business Components Browser, right-click the Application Module and
select Test from the context menu.
4. Close the browser when you are done.

Oracle JDeveloper 10g: Build Applications with ADF B-10

Practice 5-1
Open the practice05 application workspace. This application is the starting point for this
practice and includes all the steps that you should have completed so far.
1. Create a business component diagram for view objects.
a. Select the model node in the Applications Navigator, and right-click and select the New
option.
b. In the New Gallery, select Business Components > Business Components Diagram, and
click OK.
c. Name the diagram View Objects and click OK.
2. Create view objects from the navigator pane.
a. Select the entity object Categories in the navigator pane.
b. Right-click to open the context menu.
c. Select the New Default View Object option.
d. Click OK in the Create Default View Object dialog box.
3. Create view objects manually from the Component Palette.
a. Select the View Object in the Component Palette for the View Objects Diagram.
Hint: The Component Palette is usually a window just to the right of the Business
Components Diagrammer.
b. Click the diagram.
c. Change the name to InventoriesView.
Hint: Change the name of the object by clicking the name twice (not double-click), and
then entering the new name.
d. Double-click InventoriesView.
e. Select the Entity Object node.
f. Select Inventories as the available entity object and move it to the Selected window by
using the right arrow (>).
g. Select the Attributes node.
h. Select all the available attributes and move them in the Selected window.
i. Click OK to accept your changes.
4. Create view objects automatically from the Component Palette.
a. Select the view object in the Component Palette for the view objects diagram.
b. Click the diagram.
c. Change the name to ProductInformationView.
d. In the navigator pane, select the ProductInformation entity.
Hint:The navigator pane is the window on the left side of the diagrammer.
e. Drag the ProductInformation entity to the ProductInformationView box.
f. Double-click ProductInformationView to see what properties have been added to the
view object.
Hint: Note that all the attributes have been added to the view object.

Oracle JDeveloper 10g: Build Applications with ADF B-11

Practice 5-1 (continued)


5. Customize view objects.
a. Edit each view object by using the View Object Editor.
Hint: Double-click the View Object in the System Navigator to open the editor.
b. As you edit each of the following view objects, make sure to select the Java node, and
select the View Object Class and View Row Class check boxes. This will generate Java
classes that you will use in later practices.
Hint: Select the Java node to access the Java class check boxes.
c. In the list of Selected attributes, keep the following attributes for each View:

CategoriesView
CategoryId
CategoryName
CategoryDescription
CustomersView
CustomerId
CustFirstname
CustLastName
CustEmail
CreditLimit
NlsLanguage
Status
InventoriesView
ProductId
QuantityOnHand
RowId
WarehouseId
OrderItemsView
OrderId
LineItemId
ProductId
UnitPrice
Quantity
DiscountUnitPrice
OrdersView
OrderId
OrderDate
CustomerId
OrderStatus
ProductInformationView
ProductId
ProductName
ProductDescription
CategoryId
ListPrice

Oracle JDeveloper 10g: Build Applications with ADF B-12

Practice 5-1 (continued)


Later in this course, you will use a completely transient View Object to keep items for a shopping
cart application. In this step, create this view object.
6. Create a new view object named ShoppingCartView.
a. Select the Model node, and right-click and select the New View Object from the
context menu.
b. Click Next on the Welcome Page of the wizard.
c. Enter ShoppingCartView as the name, and click Next.
d. Click Next in step 2 of the wizard, because this view object is not based on an existing
entity object.
e. In step 3 of the wizard, click the New button to create the attributes for the view.
f. Enter the following information for the attributes. Make sure to click the Always
Updateable check box.
ProductId
ListPrice
Quantity
ProductName
ExtendedTotal

Number
Number
Number
String
Number

g. Click Next when you have finished entering the attributes.


h. Click Finish to end the view definition.
i. Save your work.

Oracle JDeveloper 10g: Build Applications with ADF B-13

Practice 5-2
If necessary, restart JDeveloper, open the practice05 workspace and the project model.
1. Add a calculated attribute to the OrderItemsView view object to display the total cost of
each line item. To calculate a line items total, multiply the orderItem quantity with the
discountUnitPrice. It is also useful to see the inventory items name, so you will add code to
display the item name.
a. Edit the OrderItemsView view object and add ProductInformation.Name to the view
objects attribute list. (Add ProductInformation as an entity, and then select
ProductName as an attribute).
Hint: Open the View Object Editor, and select the Entity node in the Editor window.
Select the ProductInformation entity and click the shuttle button to add it to the selected
entity list. Click the Attributes node, select ProductName, and then click the shuttle
button to add it to the attributes list.
b. Add a calculated attribute to the OrderItemsView view object, using the following
information:
The name of the attribute is LineTotal; it should be of type Number. Make sure
that the attribute is always updatable.
The attribute displays the total cost of the line item (use discountUnitPrice).
Use the attribute query expression to calculate the value of LineTotal.
The query should look like the code below:
SELECT OrderItems.ORDER_ID,
OrderItems.LINE_ITEM_ID,
OrderItems.PRODUCT_ID,
OrderItems.UNIT_PRICE,
OrderItems.QUANTITY,
OrderItems.DISCOUNT_UNIT_PRICE,
ProductInformation.PRODUCT_NAME,
ProductInformation.PRODUCT_ID AS PRODUCT_ID1,
OrderItems.QUANTITY * OrderItems.DISCOUNT_UNIT_PRICE as LineTotal
FROM ORDER_ITEMS OrderItems, PRODUCT_INFORMATION ProductInformation
WHERE OrderItems.PRODUCT_ID = ProductInformation.PRODUCT_ID

c. Test your changes by using the Business Component Browser.


2. Modify OrderItemsView to recalculate LineTotal when the line item changes.
In step 1, you added code to calculate LineTotal when each item is queried from the
database. This works fine for initially populating the field. However, when the quantity or
discountUnitPrice is changed, the LineTotal needs to be recalculated. In this step, you will
add code to calculate LineTotal whenever the getter method is called. You will also add code
to recalculate the value whenever other values change on the line item.
a. Generate a view row object for OrderItemsView
(OrderItemsViewRowImpl.java), if you have not already done so.
Hint: Double-click the OrderItemsView in the System Navigator. Select the Java node
in the editor, and click the Generate View Row Class check box.

Oracle JDeveloper 10g: Build Applications with ADF B-14

Practice 5-2 (continued)


b. Add the calculation code to the LineTotal getter method. Open
OrderItemsViewRowImpl.java and add code to the appropriate setter methods
that recalculates LineTotal. Note that adding the same code several times is not a very
good programming practice. Instead, add code to call setLineTotal(null),
which will mark the row as dirty and force the framework to perform the
recalculation.
public Number getLineTotal()
{
return new Number(getQuantity().floatValue() *
getDiscountUnitPrice().floatValue());
}
public void setDiscountUnitPrice(Number value)
{
setAttributeInternal(DISCOUNTUNITPRICE, value);
setLineTotal(null);
}
public void setQuantity(Number value)
{
setAttributeInternal(QUANTITY, value);
setLineTotal(null);
}

3. Create view links for the view objects.


a. Open the View Objects diagram if it is not already open. Make sure that all the View
Objects are in the diagram: CategoriesView, ProductInformationView,
OrderItemsView, OrdersView, CustomersView and InventoriesView.
b. Select the View Link icon from the Component Palette.
c. Create view links for each of the following views and rename them as below:
CategoriesView to ProductInformationView CategoriesProductsViewLink
ProductInformationView to InventoriesView
ProductInventoriesViewLink
ProductInformationView to OrderItemsView
ProductOrderItemsViewLink
d. Double-click each link on the diagram to validate its properties..
4. Test your application by using the Business Components Browser. Change the quantity or
price of some items to make sure that your calculation works properly.
Hint: To run the Business Components Browser, right-click the application module and
select Test from the context menu.

Oracle JDeveloper 10g: Build Applications with ADF B-15

Practice 6-1
To start this practice, if necessary, restart JDeveloper, open the practice06 workspace, and
open the model project. This project includes all the work that you should have completed to this
point in the course.
1. Enforce your validation rule to be case insensitive.
In practice 4-2, you created a ListValidator that ensures that the Status attribute of the
Customers entity has one of the following values: Platinum, Gold, and Silver. At this
point, your validation rule rejects values such as silver, which are invalid only because
the case is different. So, you need to change your validation rule so that it accepts any
combination of uppercase and lowercase letters.
Note: The resolution of this problem involves adding code to
CustomersImpl.setStatus(). Two possible solutions are:
- In the Entity Object Wizard, enter the list of valid values in uppercase (PLATINUM,
GOLD, and SILVER); in setStatus(), convert the status to uppercase.
- In the Entity Object Wizard, leave the list of valid values as Platinum, Gold, and
Silver; in setStatus(), convert the initial character of the status to uppercase
and the rest of the word to lowercase. This technique will return a value styled in initial
caps, regardless of what the user enters.
a. Click the Customers entity object. In the Structure pane, expand the Sources node,
and double-click the CustomersImpl.java node to view the code.
b. In the Structure pane, locate the setStatus():void method and click it.
c. In the Java Source code, add statements for the case-insensitive validation rule.
Hints: If you cannot remember the exact name of a method that you want to call in your
code, enter the object name followed by ., and wait for a second; JDeveloper will bring up
a list of valid methods to select from. Your code should look like the following.
public void setStatus(String value)
{
String status = value.substring(0,1).toUpperCase() +
value.substring(1).toLowerCase();
setAttributeInternal(STATUS, status);
}

d. Test your changes by using the Business Components Browser.


Hint: To run the Business Components Browser, right-click the application
module in the System Navigator, and select Test from the context menu.

Oracle JDeveloper 10g: Build Applications with ADF B-16

Practice 6-1 (continued)


2. Enforce e-mail domain validation.
You created a domain called EmailAddressDomain earlier in practice 4. To specify the
domain rules:
a. Click the domain name in the navigator pane, and double-click the corresponding
.java file in the Structure pane to open the Java code.
Hint: Select the EmailAddressDomain.java file in the Structure pane.
b. Add code to the validate() method that checks for a correctly formed e-mail
address. If the e-mail address is not correctly formed, your validate() method
should throw the following exception:
oracle.jbo.domain.DomainValidationException
("Invalid Email Address");
Hint: For help with the code, set the code snippet at the end of this practice.
c. Save your changes.
3. Test the validation rules.
a. Save your changes, rebuild your application, and then test your application by using the
Business Components Browser.
b. In the browser, open the OrdersCustomerIdFkLink form and add a new Order to a
Customer. You do not need to assign an OrderId because it will now be retrieved from
the database sequence that you defined in a previous lesson practice. The only required
field is OrderDate.
c. Commit the transaction and note that the sequence number is committed to the database
and automatically displayed on the page.
d. Now open CustomersView and change the Status attribute to an invalid value (such as
Premium) and press [Enter] or [Tab]. This will trigger the validation rule and an
Exception dialog box will appear.
e. Change status to a valid value with capitalization mistakes (such as gOLD). Note that
your code not only accepts the value, but changes it and redisplays it.
f. Change the value of an e-mail address (remove the @ character for instance) and press
[Enter] or [Tab]. Note that the exception dialog box appears with the message that you
entered in the exception.
g. Click the rollback button to undo your change, and change the Status attribute to a valid
value. This time your change is accepted.
Hint: The rollback button is on the main window on the Business Component Browser.
It is the red arrow.
h. Close the Business Component Browser.

Oracle JDeveloper 10g: Build Applications with ADF B-17

Practice 6-1 (continued)


E-mail Address Validation Code Snippet
protected void validate()
{
//
### Implement custom domain validation logic here. ###
int atpos = mData.indexOf('@');
int dotpos = mData.lastIndexOf('.');
int lastchar = mData.length() - 1;
// Check for conditions that indicate an invalid email address
if (atpos == -1 || dotpos == -1 || // there is no "@" or "."
atpos == 0 ||
// string begins with "@"
mData.lastIndexOf('@') != atpos || // string contains more than one "@"
mData.indexOf(' ') != -1 ||
// string contains a space
mData.indexOf(',') != -1 ||
// string contains a comma
dotpos < atpos ||
// there is no "." after
the
"@"
dotpos == atpos + 1 ||
// "." immediately follows "@"
dotpos == lastchar )
// string ends with "."
{ throw new oracle.jbo.domain.DomainValidationException
("Invalid email address");
}

Oracle JDeveloper 10g: Build Applications with ADF B-18

Practice 7-1
Start JDeveloper 10g, and open the practice07 workspace.
1. Create a view object from a SQL statement.
a. Create a new view object named OverstockView that selects all the products in the
Inventory for which the available sum of quantity in all warehouses is greater than 100.
The view uses the inventory and products table.
Hint: Use the expert mode to enter the query. To change the query to expert mode,
click the query node in the editor, then click the expert mode check box. You can now
enter the query shown below.
SELECT ProductInformation.PRODUCT_ID,
ProductInformation.PRODUCT_NAME,
SUM(Inventories.QUANTITY_ON_HAND) QTY
FROM PRODUCT_INFORMATION ProductInformation,
INVENTORIES Inventories
WHERE
ProductInformation.PRODUCT_ID =
Inventories.PRODUCT_ID
GROUP BY ProductInformation.PRODUCT_ID,
ProductInformation.PRODUCT_NAME
HAVING SUM(Inventories.QUANTITY_ON_HAND)>100

b. Create a default application module named SQLBasedViewModule and add the view
OverstockView to it.
Hint: To create a new application module, right-click the model project in your
workspace and select New Application Module from the context menu. On the second
page of the wizard, select OverstockView and add it to the data model.
c. Build and test your application module and view object.
2. In the business, you have customers that have qualified for special discounts. Platinum
customers get a 4% discount on all items, while Gold customers get a 3% discount on all
items. You will recalculate the discountUnitPrice when the quantity is changed.
- To calculate the discount price, you need to retrieve the listPrice of the item, multiply it
by the customers discount and store the result in the discountUnitPrice. Remember that
because this code changes data, not just presentation, the code will go on the
OrderItems entity object.
Hint: The code is listed in its entirety at the end of this practice.
a. If a customer is Platinum, apply an additional 5% discount.
b. If a customer is Gold, apply an additional 3% discount.
Hint: If you need help with the code, it is included at the end of this practice.
c. Build and test your project.

Oracle JDeveloper 10g: Build Applications with ADF B-19

Practice 7-1 (continued)


3. Modify the OverstockView so that it accepts Quantity_On_Hand as a parameter. The value
of 100 as a filtering criteria for discounting products is a rigid rule. It needs to be more
flexible so that it can match with some more realistic and flexible business needs.
a. Add a parameter to the SQL statement used by the OverstockView view.
Hint: Edit the OverstockView object, select the Query node in the editor, and change
100, in the query to :1. Click the test button to test your new query.
a. Because you have introduced a bind variable into the query, the tester will not be able
to instantiate the view object. The tester does not have a mechanism to pass a parameter
to the query.
4. Create a batch client program to test the parameter-based query.
a. Select the Model node in the navigator, and create a new Java class from the New
Gallery.
b. Name the application TestClient, and select the Generate Main Method option.
Add import statements for:
oracle.jbo.client.Configuration;
oracle.jbo.*;
c. Replace the code new TestClient(); with your code to instantiate the
SQLBasedView application module. The application name is
model.SQLBasedViewModule. The configuration name is
SQLBasedViewModuleLocal.
You can add code for this by typing bc4jclient where you want the code and
pressing [Ctrl] + [Enter]. This calls a JDeveloper code template for instantiating an
application module. All you have to do is change the details.
Hint: The code to instantiate an application module is:
String amDef = "model.SQLBasedViewModule";
String config = "SQLBasedViewModuleLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);

d. Add a print statement at the end of the main() to display a success message when you
successfully make it through the program.
public static void main(String[] args)
{
String
amDef = "model.SQLBasedViewModule";
String
config = "SQLBasedViewModuleLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
System.out.println("App Module Success");
}

e. Save your changes, and compile and test your program. At this stage, your program
does not pull any data from the database, but it should compile and run without error
and display your success message. This proves that you were able to instantiate the
application module. With that complete, you can begin to add code that will display
data from the Business Components in the SQLBasedView application module.
Oracle JDeveloper 10g: Build Applications with ADF B-20

Practice 7-1 (continued)


f. Create a string object named howMany to hold the value of the command-line
argument.
g. Add code to make sure that an argument is passed. If the program does not receive an
argument, display an appropriate error message and quit the application. If there is an
argument, set howMany to the value and display the value.
String howMany = null;
if (args.length == 0)
{
System.out.println
("You must supply a value for miminum in stock value");
System.exit(1);
}
else
{
howMany = args[0];
System.out.println
("This will show items with more than " +
howMany + " items in stock");
}

h. Add code to instantiate the OverStockView object, set its Where clause parameter
to the value of the argument from the command line, and execute the query on the view
object.
ViewObject vo = am.findViewObject("OverStockView1");
vo.setWhereClauseParam(0,howMany);
vo.executeQuery();

i.

i.

Generate the ViewRow interface for your client application. This interface provides the
typesafe methods for your client application. To generate the ViewRow interface, edit
OverstockView and select the Java node. On the Java node page, select the Generate
Java File in the View Row Class section. Select the Generate Java File, Generate
Accessors, and the Expose Accessors to the Client check boxes. This last check box
will generate the ViewRow interface.
Add a loop to display all the rows of the view object displaying the product_id,
product_name, and qty.
Hint: To use typesafe methods, which is highly recommended, you need to edit the
OverStockView object and generate a ViewRow Class. This class holds the typesafe
data access methods (such as getProductId, getProductName). After you create that
class, you can cast the Row object to a OverStockViewRowImpl object to get access to
those methods.
while (vo.hasNext())
{
OverStockViewRowImpl row = (OverStockViewRowImpl)vo.next();
System.out.println("Product Id: " + row.getProductId() );
System.out.println("Product Name: " + row.getProductName());
System.out.println("Quantity in Stock: " + row.getQty());
}

Oracle JDeveloper 10g: Build Applications with ADF B-21

Practice 7-1 (continued)


j. Modify the project properties to pass a command-line argument to your program by
editing project properties and selecting the Development > Runner node. Enter a
number in the program argument field.
k. Build, save, and test your program. (Right-click the TestClient.java file, and
select Run from the context menu.
TestClient.java
package model;
import oracle.jbo.*;
import oracle.jbo.client.Configuration;
public class TestClient
{
public TestClient()
{
}
/**
*
* @param args
*/
public static void main(String[] args)
{
String
amDef = "model.SQLBasedViewModule";
String
config = "SQLBasedViewModuleLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
String howMany = null;
if (args.length == 0)
{
System.out.println
("You must supply a value for miminum in stock value");
System.exit(1);
}
else
{
howMany = args[0];
System.out.println
("This will show items with more than " +
howMany + " items in stock");
}

Oracle JDeveloper 10g: Build Applications with ADF B-22

Practice 7-1 (continued)


TestClient.java (continued)
ViewObject vo = am.findViewObject("OverStockView");
vo.setWhereClauseParam(0,howMany);
vo.executeQuery();
while (vo.hasNext())
{
// cast the view object to a view object impl to
// use typesafe accessors
OverStockViewRowImpl row =
(OverStockViewRowImpl)vo.next();
System.out.println("Product Id: " + row.getProductId() );
System.out.println("Product Name: " + row.getProductName());
System.out.println("Quantity in Stock: " + row.getQty());
}
Configuration.releaseRootApplicationModule(am,true);
}
}

Oracle JDeveloper 10g: Build Applications with ADF B-23

Practice 7-1 (continued)


Calculate the customer discount in OrderItemsImpl.java.
public void setQuantity(Number value)
{
float statusDiscount = 0F;
float listPrice = getProductInformation().getListPrice().floatValue();
setUnitPrice(new Number (listPrice));
//

get the customer status

String customerStatus = (getOrders().getCustomers().getStatus());


statusDiscount = 0F;
if (customerStatus.equalsIgnoreCase("PLATINUM"))
{
statusDiscount = 5F;
System.out.println("Platinum");
}
else
if (customerStatus.equalsIgnoreCase("GOLD"))
{
statusDiscount = 3F;
}
// calculate discount
float discountAmount = ((listPrice * (statusDiscount)) / 100);
float discountUnitPrice = listPrice - discountAmount;
if (statusDiscount == 0F )
setDiscountUnitPrice(new Number (listPrice));
else
setDiscountUnitPrice(new Number (discountUnitPrice));
setAttributeInternal(QUANTITY, value);
}

Oracle JDeveloper 10g: Build Applications with ADF B-24

Practice 8-1
Start JDeveloper, and open the practice08 workspace.
It is important to make the business data secure and ensure that all the records comply with the
business logic.
1. Configure the ADF application to use SSO authentication.
a. Close JDeveloper.
b. Open the java.security file in the <JDevHome>\jdk\jre\lib\security folder.
c. Add the following statement at the end of the file:
login.configuration.provider=oracle.security.jazn.spi.LoginConfigFile

d. Save and close the file.


e. Restart JDeveloper, and open the practice08 application.
2. Set jbo.security.enforce for the application.
a. Locate SalesAppModule in the Applications Navigator.
b. Right-click and select the configurations option. In the Configuration Manager dialog
box, click Edit.
c. In the Oracle Business Component Configuration dialog box, click the Properties tab.
d. Locate the jbo.security.enforce property and change it from None to Auth.
e. Accept your changes and close the Configuration Editor.
3. Add authorization to entity levels.
a. Specify update permissions for the users group for the OrderItems entity.
Hint: Edit the OrderItems entity. Click the Authorization node in the editor. Select the
OrderItems entity (top-level node), and click New. Select the users group and change
the update authorization to update permissions.
b. Specify ReadOnly permissions for the Guests group for entities Orders, Categories,
ProductInformation, Inventories, and Customers.
Hint: Repeat the above steps for each of these entities.
4. Test the authorizations.
a. Right-click the SalesAppModule node in the System Navigator.
b. Select the Test option.
c. In the Business Component Configuration Name field, select the SalesAppModule
name.
d. Click the connect button.
e. In the new dialog window, specify user with a password of 456. (This is one of the
default usernames in the users group.) Test the application, and note what privileges
this user has.
f. Close the browser and launch it again. This time try with anonymous with any
character as the password. This is one of the default users in the guests group. Note the
difference in the Orders and OrderItems forms.
g. Close the browser when you are done.

Oracle JDeveloper 10g: Build Applications with ADF B-25

Practice 9-1
Start JDeveloper, and open the practice09 workspace.
1. Create a Page Flow Diagram.
a. Open the ViewController node in the Applications Navigator.
b. Double-click the struts-config.xml file located in the Web Content/WEB-INF
folder.
c. Open the Component Palette.
d. Create a diagram as the one below, which includes the following components:
Page:
/welcome
Data Page:
/categories and /products
Page Forward:
/logon

Hint: To create each of the items above, click the correct type in the Component
Palette, which is to the right of the diagram. Then, click anywhere on the diagram
surface.
e. Double-click the welcome page, and using the Design Editor, enter Welcome.
f. Reopen the Page Flow Diagram, and double-click the logon page.
Hint: You can reopen the diagram by clicking the struts-config.xml tab at the
top of the editor window.
g. Click OK on the page name proposal.
h. In the Design Editor, enter Logon.
i. Reopen the Page Flow Diagram and draw a Page Link from welcome to logon.
2. Run the welcome JSP.
a. Go back to the Page Flow Diagram.
b. Right-click on the welcome page and select the Run option from the context menu.
c. You should be able to navigate from welcome to logon and see the corresponding
message on each page.

Oracle JDeveloper 10g: Build Applications with ADF B-26

Practice 10-1
In this practice, use the various tag libraries to create JSP pages. Start JDeveloper, and open the
practice10 workspace.
1. Add a Welcome message to the Welcome page.
a. Double-click the welcome.jsp icon on the Page Flow Diagram.
b. Click the design tab at the bottom to open the Design Editor.
c. Remove the welcome text that you have put in the previous lesson.
d. Select the Struts Bean tag library from the Component Palette.
Hint: The Component Palette is to the right of the Visual Editor window.
e. Double-click the message tag.
f. In the dialog box, look for the key attribute and set its value to welcome.title.
The convention adopted for this course is <JSP_name>.<message_name>.
Note: You can see that there is a list of existing entries in the ApplicationResources
file, so it makes more sense to create the message in ApplicationResources first and
then reference the existing key in the tag. That is what you do from now on.
g. Click OK.
2. Add the message entry in the ApplicationResources file.
a. In the Applications Navigator, locate the ApplicationResources node in
ViewController > Application Sources > View.
b. Open the file and add the following text:
welcome.title=Welcome to our Online Shopping site
c. When you are done, click save or save all on the Windows menu bar.
d. Test the jsp: right-click /welcome on the Struts diagram, and select run. Note the
welcome message.
3. Create the Data Based JSPs categories.
a. Create the following entries in the ApplicationResources file and save your changes.
# Categories
categories.title=Product Categories
# Products
products.title=Product List
Hint: Open the resources file just as you have done in step 2.
b. Display the Page Flow Diagram.
c. Double-click the /categories data page.
d. Accept the page name and select the Edit this page now check box. Click OK.
e. Drag a Struts Bean message tag. Set the key value to categories.title.
f. Open the Data Control Palette.
Hint: The Data Control Palette is a tab on the Component Palette, which is to the right
of the Visual Editor.
g. Expand SalesAppModuleDataControl, and then the CategoriesView1 node.
h. Select CategoriesView1 and set the Drag and Drop As List to Read-Only Table.
i. Drag the view to the Design Editor.
j. Test the jsp: right-click /categories on the Struts diagram, and select run. Remember
that the pages that you are creating must run from within the Struts controller. They
will not run as stand-alone JSPs.

Oracle JDeveloper 10g: Build Applications with ADF B-27

Practice 10-1 (continued)


4. Create the products data-based JSP. Perform the same process that you used for the
Categories page.
a. Double-click the products data page to create the default JSP.
b. Add a Struts message bean to the page. Set the key value to products title.
c. Drag the ProductInformationView as a Read-Only Table to the products page.
Note: Select the ProductInformationView that is within the CategoriesView node.
This view is a child of CategoriesView.
d. Test the JSP.
5. Create the following entries in the ApplicationResources file.
#Logon Page
logon.title=Logon to Order
logon.subtitle=Enter your last name and customer ID below...
logon.lastname=Last Name:
logon.customerid=Customer Id:
logon.submitbutton=Logon
logon.welcome = Back to the Welcome Page

6. Create the logon JSP. Perform the same process that you used for the other pages.
a. Open logon.jsp that you created in an earlier practice, and remove the logon text.
b. Add a Struts HTML error tag and a Struts message bean. Set the message bean key to
logon.title.
c. Add a second Struts bean message, and set its key value to logon.subtitle.
d. Add an HTML table tag, and specify 3 rows 2 columns.
Hint: To add an HTML table, select HTML from the list of available component types
in the Component Palette, and then select table from the list.
e. In the top left cell, add a Struts bean message tag and set the Key value to
logon.lastname.
f. In the same column next row, add a Struts bean message tag, and set the Key value to
logon.customerid.
g. In the top right cell, drag an HTML text field tag. Double-click it. When asked, do not
add a form element. Specify lastName as name.
h. In the same column next row, drag an HTML password tag and set its property to
customerId. When asked, do not add a form element.

Oracle JDeveloper 10g: Build Applications with ADF B-28

Practice 10-1 (continued)


i. In the bottom right cell, drag a Struts HTML submit tag and decline the Add Form
element proposal. You will add the functionality to this button in a later practice. For
now, it will serve only as a placeholder.
j. Select a Struts bean message tag, and drag it to the white rectangle within the submit
tag you just added. Set its key value to logon.submitbutton.
7. Add page links.
a. Display the Page Flow Diagram.
b. Create a Page Link from logon to categories.
Hint: Select Struts Page Flow as the component group in the Component Palette. Click
the Page Link icon. Click the source page, and then the destination page.
c. Create a Page Link from categories to products.
d. Create a Page Link from products to categories.
e. Your Page Flow Diagram should look like the diagram below.
f. Select the Welcome page and run it.
g. Go through each page by using the various links.
h. Close your browser.

8. Modify the applicationResources file to make the link messages more usable.
a. Open the applicationResources file and note that when you added links to the pages,
JDeveloper added entries for those links.
b. Change the values of those links to more helpful messages.
c. Save the file and test the application again.

Oracle JDeveloper 10g: Build Applications with ADF B-29

Practice 11-1
In this practice, you create a form bean to hold logon information. That logon information will be
passed to an action that performs authentication and returns a customer name if the validation
succeeds.
Start JDeveloper, if necessary, and open the practice11 workspace.
1. Create form beans.
a. Open the Page Flow Diagram.
b. In the Structure pane, create a new form bean.
Hint: The Structure pane is usually below the System Navigator. Right-click the Form
Beans node, and select New from the context menu.
c. In the Properties pane, specify logon as the name and set the type to
org.apache.struts.action.DynaActionForm.
Hint: Use the Property Inspector to set these values. Use the Edit button (the button in
the type field) to select the type from the list.
d. In the Structure pane, select the logon bean and create a new Form Property.
Hint: Right-click the logon bean that you just created, and select new Form Property
from the context menu.
e. In the Property Inspector, set the name property to lastName and leave it as a
String.
f. Create a second Form Property for customerId (leave it as a String).
2. Create a new view object that validates the customer logon. This view object will accept two
parameters and query the customers table for a combination of both customerLastName
and customerId.
a. Create a view object. Name it AuthenticateView. Remember to create the view object
in the model project.
b. Select customers as the entity object.
c. Select customerId, custFirstName, and custLastName as the attributes.
d. Add a WHERE clause that compares the upper of custLastName with the upper of a
parameter AND compares customerId with a second parameter.
SELECT Customers.CUSTOMER_ID,
Customers.CUST_FIRST_NAME,
Customers.CUST_LAST_NAME
FROM CUSTOMERS Customers
WHERE upper(Customers.CUST_LAST_NAME)= upper(?)
and Customers.CUSTOMER_ID= ?

e. Make sure to select the Use ? Style parameters check box if you are using the above
syntax.
f. In step 6 of 6, select the Generate Java File option for the View Row Class.
g. Click Finish to validate.
h. Add the view to SalesAppModule. Remove 1 from the instance name.
Hint: To edit the application module, right-click SalesAppModule in the System
Navigator and select edit SalesAppModule, or double-click the application module.

Oracle JDeveloper 10g: Build Applications with ADF B-30

Practice 11-1 (continued)


3. Create a data action.
a. Open the Struts Page Flow Diagram.
b. Drag the Data Action icon next to the logon page.
Hint: The Data Action component is on the Component Palette under Struts Page
Flow.
c. Change the name to /authenticateUser.
4. Create a new method to validate customers logon by using the view you just created.
a. Select the SalesAppModule node in the Applications Navigator.
b. In the Structure pane, double-click the SalesAppModuleImpl.java node.
Hint: If the Java file is not there, edit SalesAppModule, click the Java node in the
editor, and click Generate Java Files for the Application Module Class.
c. In the Source Editor, create a new method that has the following characteristics:
Its signature is:
public String findCustomers(String lastName, String customerId)

(The return parameter is a string of FirstName and LastName concatenated )


Hint: If you need help with the code, it is shown at the end of this practice.
d. Import any classes necessary.
e. Compile the class and correct any errors that you may have.
5. Make the method available to client applications.
a. Double-click SalesAppModule to open the Module Properties Wizard.
b. Select the Client Interface node.
c. Move the findCustomers method from Available to Selected, and click OK.
6. Add the method to the AuthenticateUser data action.
a. Open the Page Flow Diagram.
b. From the Data Control Palette, open the SaleAppModuleDataControl node.
Hint: The Data Control Palette is a tab at the bottom on the Component Palette, which
is located to the right of the diagrammer.
c. Open the Operations node, and select the findCustomers() method.
d. Drag the method to the authenticateUser data action.
7. Set the parameter properties of the data action.
a. In the Structure pane, expand the /authenticateUser node.
Hint: Make sure that you are viewing the Page Flow Diagram. The Structure pane is
just below the System Navigator.
b. Select the paramNames[0] node.
c. In the Property Inspector, change the value key to ${param.lastName}.
d. Select the paramNames[1] node.
e. In the Property Inspector, change the value key to ${param.customerId}.
f. Select the resultLocation node.
g. In the Property Inspector, change the value key to
${sessionScope.customerName}.

Oracle JDeveloper 10g: Build Applications with ADF B-31

Practice 11-1 (continued)


8. Associate the logon page to the data action.
a. Open the logon page.
Hint: Double-click /logon page in the Page Flow Diagrammer.
b. Select the Source Editor.
Hint: The Source Editor is a tab at the bottom of the Visual Editor window.
c. Above the <table> tag insert the following:
<form action="authenticateUser.do">
d. Close the form tag </form> after the </table> tag.
Hint: The code should be like the following.
<form action="authenticateUser.do">
<table cellspacing="2" cellpadding="3" border="1" width="100%">
<tr>
<td>
<bean:message key="logon.lastname"/>
</td>
<td>
<input type="text" name="lastName"/>
</td>
</tr>
<tr>
<td>
<bean:message key="logon.customerid"/>
</td>
<td>
<input type="text" name="customerId"/>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<html:submit>
<bean:message key="logon.submitbutton"/>
</html:submit>
</td>
</tr>
</table>
</form>

e. Remove the link to the categories page that you added in an earlier practice.
f. Right-click the /logon page on the Page Flow Diagram, and choose the Refresh
Diagram from Page option. A page link should appear between l/ogon and
/authenticateUser.

Oracle JDeveloper 10g: Build Applications with ADF B-32

Practice 11-1 (continued)


g. Create a forward going from authenticateUser to categories. The Struts diagram should
look something like the diagram below:

9. Run the application starting at the welcome page. Try to log on with the following values of
CustomerLastName and CustomerId:
Welles 101
Pacino 102
Taylor 103
10. You will enhance this validation in a later practice.

Oracle JDeveloper 10g: Build Applications with ADF B-33

Practice 11-1 (continued)


SalesAppModuleImpl.java
public String findCustomers(String lastName, String
customerId)
{
ViewObjectImpl vo = this.getAuthenticateView();
vo.setWhereClauseParam(0,lastName);
vo.setWhereClauseParam(1,customerId);
vo.executeQuery();
AuthenticateViewRowImpl row =
(AuthenticateViewRowImpl)vo.first();
String customerName = null;
if (row != null)
{
customerName = row.getCustFirstName() + " " +
row.getCustLastName();
}
return customerName;
}

Oracle JDeveloper 10g: Build Applications with ADF B-34

Practice 12-1
Adding features to data pages.
Start JDeveloper, if necessary, and open the practice12 workspace.
1. In this step, you add navigation operations to the categories page. The buttons will enable
the user to navigate forward or backward through sets of category rows.
a. Open the categories data page.
Hint: Double-click the /categories page in the Page Flow Diagram.
b. In the Data Control pane, open the SalesAppModuleDataControl node and expand the
CategoriesView node, and then the Operations node.
c. Select the Previous Set item, and drag it to the Design Editor following the last object.
If prompted with an Add Form Element Confirmation dialog box, answer Yes.
d. Perform the same steps and add the Next Set operation and drag it next to the Previous
Set button.
Hint: Your page should look like the following.

e. You need to include the data table inside the form tag that you just added. Go to the
Source tab, find the <form> tag, and move it to just above the <table> tag.
f. Next, set the action property of the form to categories.do.
Hint: From the Visual Editor, right-click inside the form tag, and select the Select
Form tag from the context menu. After the form tag is selected, use the Property
Inspector to change the action property to categories.do. When you are done,
your code should look like the following.

Oracle JDeveloper 10g: Build Applications with ADF B-35

Practice 12-1
Categories.jsp
<form action="categories.do">
<table border="1" width="100%">
<tr>
<th>
<c:out value="${bindings.CategoriesView1.labels['CategoryName']}"/>
</th>
<th>
<c:out value="${bindings.CategoriesView1.labels
['CategoryDescription']}"/>
</th>
<th>
<c:out value="${bindings.CategoriesView1.labels['CategoryId']}"/>
</th>
</tr>
<c:forEach var="Row" items="${bindings.CategoriesView1.rangeSet}">
<tr>
<td>
<a href="categories.do?event=setCurrentRowWithKey&Arg0=
<c:out value='${Row.rowKeyStr}' />">
<c:out value="${Row['CategoryName']}"/></a></td>
<td>
<c:out value="${Row['CategoryDescription']}"/>&nbsp;
</td>
<td>
<c:out value="${Row['CategoryId']}"/>
</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="event_PreviousSet" value="PreviousSet"
<c:out value="${bindings.PreviousSet.enabledString}" />/>
<input type="submit" name="event_NextSet" value="NextSet"
<c:out value="${bindings.NextSet.enabledString}" />/>
</form>

Oracle JDeveloper 10g: Build Applications with ADF B-36

Practice 12-1
2. Modify the iterator so that the page does not display all the items at one time. This will make
the pages more user-friendly. If the users do not see the category they are looking for, they
can click one of the buttons to see the next set of records rather than having to scroll to see
all the categories.
a. In the Applications Navigator, click the categories.jsp node.
b. In the Structure pane, click the UIModel tab, which is the second tab at the top of the
Structure pane.

c. Click CategoriesViewIterator, and set the Range Size value to 5 in the Property
Inspector. This will restrict the number of categories displayed on a page to 5.
3. Add navigation operations to the products page.
a. Open the products data page.
b. Within the CategoriesView node, expand the ProductInformationView node, then the
Operations node and add Previous Set and Next Set items as you did for the categories
page. Do not forget to move the <form> tag and set the action property to
products.do.
4. Modify the products iterator to display 5 rows just like you did for the categories iterator.
5. Clean up the unnecessary columns from both pages.
a. In the table created for the view, select the first top left cell, right-click, select Table
from the context menu and select the Delete Column option.
b. This will remove the current_row column from the table.

Oracle JDeveloper 10g: Build Applications with ADF B-37

Practice 12-1 (continued)


6. Creating a master detail page navigation for the categories and products pages.
a. In the page flow, delete the link from categories to products that you created earlier.
b. Open the categories page in the Design Editor and delete the link and message bean.
c. Select the Operations node for the CategoriesView in the Data Control Palette.
d. Drag the setCurrentRowWithKey categories operation as a Find Row Link to the
CategoryName column. (You can choose any column.)

e. Move the <a href tag around to include the category name.
<a ref="categories.do?event=setCurrentRowWithKey&Arg0=
<c:out value='${Row.rowKeyStr}' />">
<c:out value="${Row.CategoryName}"/></a>

f. Add a forward between categories and products, and rename it


setCurrentRowWithKey.
Hint: Start by opening the Page Flow Diagram. Select the Forward icon from the
Component Palette, click the categories page, and then the products page. Click the
forward label (success) twice to edit the name. (Not double-click.)
g. Run the categories page, and select a category to test the detail page.
h. Use the link back to categories to select another category.
i. Close the browser.

Oracle JDeveloper 10g: Build Applications with ADF B-38

Practice 12-1 (continued)


7. Create a data page for ShoppingCartView that you created in an earlier practice.
a. Add the following entries in the ApplicationResources file:
link.products=continue shopping
link.categories=choose another category
b. Open the Page Flow Diagram and create a shoppingCart data page with the default
corresponding jsp.
c. Drag the ShoppingCartView data control as a read-only table to the page.
d. Select the Struts HTML link tag and drag it to the bottom of the page. Add a Struts
bean message tag to the link tag and set the key value as link.products. Specify
/products.do as the action value in the Property Inspector.
e. Select the Struts HTML link tag and drag it to the bottom of the page. Add a Struts
bean message tag to the link tag and specify link.categories as the key value.
Specify /categories.do as the action value in the Property Inspector.
8. The shoppingCartView is designed to hold items that the user chooses to buy from your
online store. The user adds the items by clicking a link on the item. The item is then added to
the shoppingCartView. The code to accept these items and add them to the cart is in the
shoppingCartViewImpl class. Rather than having you type all the code, the code is already
in the class. The instructions for this portion of the practice will be to step you through the
code.
a. Make the view object capable of using the FindByKey method. Setting this property to
true enables you to search the view object by Key. The benefit of using this technique
is that you do not have to iterate through the rows searching for a match. That function
is already written for you.
protected void create()
{
super.create();
setManageRowsByKey(true);
}
// end of create

Oracle JDeveloper 10g: Build Applications with ADF B-39

Practice 12-1 (continued)


b. You also need a method to add items to the cart when this method is called. The
method accepts two arguments: the productId and a quantity. The first step of
this method is to check to see if this product is already in your shoppingCart. You do
that by calling findCartItem(), which uses findBykey. If it does not find the
item, it adds it as a new row. The method adds a new row by calling createRow(),
insertRow(cartItem), and then calling fillInCartDetails(). This last
method sets the rest of the attributes to the values from the product. You will look at
that method next.

Oracle JDeveloper 10g: Build Applications with ADF B-40

Practice 12-1 (continued)


c. The fillInCartItemDetails() method instantiates a
ProductInformationView and sets its WHERE clause to the productId of the
current cartItem. It queries the view object to get the details of the product. It then
sets the productName and listPrice of the shoppingCartItem.

Oracle JDeveloper 10g: Build Applications with ADF B-41

Practice 12-1 (continued)


d. The findCartItem() method simply takes a productId as an argument, and
checks to see if it exists in the shoppingCart. If it exists, it returns the
shoppingCartItem row.

e. The cartTotal() method returns the total of all the items in the cart. To do this, it
creates a rowSetIterator of the shoppingCart and iterates through it,
summing the extendedTotal attributes as it does. At the end of the
RowSetIterator, it returns the total.

Oracle JDeveloper 10g: Build Applications with ADF B-42

Practice 12-1 (continued)


9. After the user has selected items and added them to the cart, you need to finalize the order;
that is, go through the checkout process. The code creates a single order for the
shoppingCart, and then creates an OrderItems row for each row in the
shoppingCart This method is in the SalesAppModuleImpl class.

Oracle JDeveloper 10g: Build Applications with ADF B-43

Practice 12-1 (continued)


10. Now that all the code is in place to add items to the cart, calculate the total, and even finalize
the order, you need code to get it all started. This method will be published in the application
module so that client applications can access it. All the other methods are used within the
context of this one method. This method is the addToCart method and is also in the
SalesAppModuleImpl class.

Oracle JDeveloper 10g: Build Applications with ADF B-44

Practice 12-1 (continued)


11. Now that the code is in place to complete your application, you can add the elements to add
products to the shoppingCart. The result will be a link on the product ID that forwards to a
DataAction. The DataAction will call the addToCart method, which adds the product to
the ShoppingCartView object.
a. Add a DataAction to the page flow and name it /addToCart.
Hint: Use the Component Palette, select DataAction, and click the Page Flow Diagram.
b. Drag the addToCart method from SalesAppModule to DataAction.
Hint: The addToCart method is in the Operations node of the application module.
Access it through the Data Control Palette.
c. Change the name of the parameter in the addToCart DataAction to param.prodId.
(Use the Structure pane and select paramNames[0].)
Hint: Make sure that the Page Flow Diagram is open. Expand the addToCart node in
the Structure pane. Click the paramNames(0) node and change the parameters
property in the Property Inspector.
d. Add a forward from the products page to the addToCart DataAction and name it
addToCart.
e. Add a forward from the addToCart DataAction back to the products page. Leave the
name as success.
12. Next, add href to the products page that uses the forward you just defined and passes
productId as an argument. Because this is a common activity, create a code snippet that
will make this easier.
a. Open the code snippet list on the Component Palette.
Hint: Select code snippet from the drop-down list of component types in the
Component Palette.
b. Right-click and select Add Component.
c. Name the component a href with an event and argument.
d. Enter the following code snippet:
<a href="myPage.do?event=myEvent&myArg=<c:out value="${Row.myValue}"
/>"> link words </a>

e. Click OK. You are now ready to use this snippet wherever you need.
f. From the Component Palette, select code snippets. In the Design Editor, place your
cursor just before the productId value in the read-only table. Now click the a href
item in the Component Palette. This adds your code snippet to the page.
g. Find the code in the Source Editor and change it for your specific application by
replacing myPage, myEvent, myArg, and myValue. Your code should look like:
<a href="products.do?event=addToCart&prodId=<c:out
value="${Row.ProductId}" />">
<c:out value="${Row['ProductId']}"/></a>

h. Add a forward from the products page to the shoppingCart page. Name the forward
viewCart.
Hint: Select the Struts Page Flow elements from the Component Palette drop-down list.
Click the forward icon, and then click the products page, followed by the shoppingCart
page.
13. In the Visual Editor on the products page, add an href that calls the forward to the
shoppingCart. The code should look like the following code (you can use the snippet again):
<a href="products.do?event=viewCart">View your Cart </a>

Oracle JDeveloper 10g: Build Applications with ADF B-45

Practice 12-1 (continued)


14. Build and test the application starting at the categories page.
a. Select a category and note that the products page is coordinated with that category.
b. Go back to the categories page and select another category. Observe the same behavior.
c. Click a product to add it to the shoppingCart.
d. See that the item is added to the cart.
e. Experiment with multiple items by clicking the same item multiple times.
f. When you are done, close the browser.

Oracle JDeveloper 10g: Build Applications with ADF B-46

Practice 13-1
In this practice, you enhance the views and create a new view.
Start JDeveloper, if necessary, and open the practice13 workspace.
1. Enhance the view objects to make the the UI more user-friendly.
a. Edit the CreditLimit attribute in the CustomersView. On the Control Hints tabbed
page, set the format type to currency and format to $0000.00.
b. Edit the UnitPrice and DiscountUnitPrice attributes in OrderItemsView. Set the format
type to currency and format to $0000.00.
c. Edit the OrderDate attribute in OrdersView. Set the format type to Simple Date and
format to yyyy-mm-dd.
d. Edit the ListPrice attribute in ProductInformationView. Set the format type to
currency and format to $0000.00.
e. Edit the ListPrice and ExtendedTotal attributes in ShoppingCartView. Set the format
type to currency and the format to $0000.00.
2. Add a validator for input fields by adding the validator plug-in to the Strutsconfig.xml file.
a. Open the Page Flow Diagram.
b. In the Structure pane, right-click the the top-level Struts Config node and choose New
> Plug In from the context menu. This will create a new plug-in node in the structure.
c. Select the new plug-in node and switch to the Property Inspector.
d. Set the className property for the plug-in to
org.apache.struts.validator.ValidatorPlugIn.
e. Now with the plug-in node still selected in the Structure pane bring up the context
menu and choose New > Set Property. This will create a child node under the plug-in
labeled as <set-property>.
f. Select the new <set-property> entry and switch to the Property Inspector.
g. Set the property property for this <set-property> entry in the inspector to pathnames.
h. Set the value property to the following (this can be changed to suit your application):
/WEB-INF/validator/validator-rules.xml,/WEBINF/validator/validations.xml.
i. The /WEB-INF/validator directory already has a copy of the Validator rules file.
That file has been copied for you from the basic version supplied with JDeveloper. The
file is delivered in %JDEV_HOME%/jakarta-struts/lib/validatorrules.xml.

Oracle JDeveloper 10g: Build Applications with ADF B-47

Practice 13-1 (continued)


j. Copy the predefined Validator error messages into your resources file. These messages
appear at the beginning of the validator-rules.xml file:
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1}
characters

Hint: The validator-rules.xml file is under the WEB-INF/validator node in


the ViewController project.
3. Modify the authenticateUser data action to use the logon form bean that you created in an
earlier practice.
a. Select the authenticateUser data action on the Struts diagram.
b. Change the input property to /logon.do.
c. Change the name property to logon.
Hint: Change those properties by using the Property Inspector window.
4. Set up form beans to use the correct superclass.
a. Open the Page Flow Diagram.
b. In the Structure pane, open the logon form bean.
c. In the Properties pane, change the type to
org.apache.struts.validator.DynaValidatorForm.
d. Select the WEB-INF/validator node in the Applications Navigator. Note that there is a
file named validations.xml file. This file holds the validation rules that you are
going to apply. Normally, you create this file by selecting the WEB-INF node, rightclicking, and selecting New from the context menu. You then select xml, new xml file
in the gallery.
e. Open the validations.xml file and examine the code. You should note that the
statements check whether the customerName field has a value and that the
customerId field is required, and whether it is an integer and has a value between 100
and 600. The xml validation code is on the following page.

Oracle JDeveloper 10g: Build Applications with ADF B-48

Practice 13-1 (continued)


<form-validation>
<formset>
<form name="logon">
<field
property="lastName"
depends="required">
<arg0 key="logon.lastname"/>
</field>
<field
property="customerId"
depends="required,integer,intRange">
<arg0 key="logon.customerid"/>
<arg1
name="intRange"
key="${var:min}"
resource="false"/>
<arg2
name="intRange"
key="${var:max}"
resource="false"/>
<var>
<var-name>min</var-name>
<var-value>100</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>600</var-value>
</var>
</field>
</form>
</formset>
</form-validation>

5. Modify the logon page to use the validator.


a. Run the logon page and provide some incorrect values to test Last Name and Customer
ID validation. Note how the page handles input errors.
b. Close the browser.
c. Change the form tag to the following:
<form action="authenticateUser.do" onsubmit="return
validateLogon(this);">
Hint: Double-click the logon page to open the Visual Editor. Select the Form tag by
clicking just inside the dotted red outline. In the Property Inspector add the code
onsubmit="return validateLogon(this);
d. Update the page to use JavaScript validation by inserting the following statement right
below the <head> tag:
<html:javascript formName="logon"/>
Hint: Click the Source tab on the Visual Editor. The code should look like the
following.

Oracle JDeveloper 10g: Build Applications with ADF B-49

Practice 13-1 (continued)


<html>
<head>
<html:javascript formName="logon"/>
<meta http-equiv="Content-Type"
content="text/html;
charset=windows-1252">
<title>untitled</title>
</head>
<body>

e. Run the logon page and provide some incorrect values to test Last Name and Customer
ID validation.
f. When you are done testing, close your browser.

Oracle JDeveloper 10g: Build Applications with ADF B-50

Practice 14-1
At this point, the pages that are built are displayed by using a default presentation, which is not
bad, but probably not good enough for an enterprise application. In this practice, you add a few
things that make the pages more user-friendly.
Start JDeveloper, if necessary, and open the practice14 workspace.
1. Create a heading page.
a. In the Page Flow Diagram, create a JSP page and name it /heading.jsp
b. Add Welcome to the top of the page. Use a messageBean for consistency.
c. Next add a JSTL out tag to get sessionScope.customerName.
${sessionScope.customerName}
Hint: You access the JSTL components from the Component Palette. Select JSTL as
the component type from the drop-down list. Select the c:out tag and add it to the
page. Enter the code above in the value property in the dialog box.
d. In the Component Palette, select CSS from the list and drag the JDeveloper CSS to the
page.
2. Include the heading page in all pages.
a. Select the logon page.
b. Select the JSP jsp:include tag and drag it to the top of the page.
c. Use the Browse button to find and select the heading page.
d. Repeat the operation for the categories, products, and shoppingCart pages.
3. Update the CSS to make your read-only tables more readable.
a. Select the CSS | jdeveloper.css node in the Web Content folder.
b. In the Structure pane, select the TH node.
c. In the Property Inspector, set the background-color value to #336699 or a color of your
choice.
d. Set the color to White.
e. Set the font-style key to italic, font-weight to bold, and text-align to center.
4. Update the categories page to use messageBeans for the headings.
a. Open the ApplicationResources file and add the following entries. Make sure to save
the file when you are done:
category.id= Category Id
category.name= Name
category.description= Description
b. Open the categories page in the Visual Editor.
c. If there is a currency column in the read-only table, select it, and
remove it from the table.(Right-click | table | Delete Column).
d. It there is no title message bean, add it. Set the title message bean style to Heading1
(H1). Make sure to exclude the jsp:include and error tags from the H1 style.

Oracle JDeveloper 10g: Build Applications with ADF B-51

Practice 14-1 (continued)


e. Delete all table headers (JSTL tags).
Hint: The default table headers use JSTL to derive the value for the heading. Remove
the JSTL so that you can replace the values with references to the resource file.
f. Drop a Struts bean message tag in each column header and set the key value to the
corresponding key value.
Hint: Select the Struts bean:message component from the Component Palette (under
Struts Bean). Add a bean to each of the columns in the table and set the key value to a
reference in the resources file.
5. Update the other pages in your application to follow the same style and standard:
shoppingCart
products
6. Add a total to the ShoppingCart.
a. Insert a new blank row at the bottom of the shoppingCart table.
b. Add a jstl:out tag to the last column in the new row.
c. Use ${sessionScope.cartTotal} as the value for the out tag.
7. Build, run, and test your application.

Oracle JDeveloper 10g: Build Applications with ADF B-52

Practice 15-1
In this practice, you will change the logon routine to use JAZN security authorization.
In earlier practices, you used a method in the SalesAppModuleImpl class to find customer
information based on a logon page. The method accepted a username and password, performed a
lookup in the Customers table, and returned a concatenated username. You then used that name to
display in the heading for each of the pages in your application. Now you will use another method
that gets the user ID from JAZN.
Start JDeveloper, if necessary, and open the practice15 workspace.
1. First, you will configure the application to use JAZN security for authentication.
a. Right-click the web.xml file and select properties to edit the deployment descriptor.
b. Select the Login Configuration node, and then select HTTP Basic Authentication for
the authentication type.
c. Add a new security role by selecting the Security Roles node. Click the add button and
enter users as a new role.
d. Next add a security constraint by clicking the Security Constraint node, and clicking the
New button at the bottom of the navigator.
e. Add a new Web resource and name it SalesApp.
f. Add a URL pattern, and set the value to /.
g. Next, click the Authorization tab and click users to authenticate that group to your
application.
h. Test the application. You can right-click on any page on the pageflow diagram and
select run. Because the entire application is protected, anywhere you choose to start
will require a JAZN logon. The valid user IDs are user with the password of 456,
SCOTT with a password of TIGER, and anonymous with any character as a
password. Try to use an invalid ID or password.
2. Now that you have JAZN working to authenticate users, add an action that will use the JAZN
authenticated user ID to look up customer information and store it in
sessionScope.customerName.
You will add a new path to the categories page, which will use this DataAction. In reality,
you may replace the current authenticateUser DataAction with this new one, but you should
be able to compare the two techniques.
a. Add a DataAction to the Page Flow Diagram and name it authenticateUserJAZN.
You can do this on the diagram or change the path in the Property Inspector.
b. Expand the SalesAppModule node in the Data Control Palette and drag the
findCustomerJAZN method to the new DataAction.
c. Select the authenticateUserJAZN node in the Structure pane and change the
resultLocation value to {sessionScope.customerName}. This will put the results of the
findCustomerJAZN method into the session variable customerName.
d. Add a Page Link from the Welcome.jsp page to the new DataAction.
e. Add a forward from the DataAction to the categories page.
3. Add users to the JAZN definition and test the application.
a. Add two new JAZN users. From the JDeveloper menu, select Run | Terminate |
Embedded OC4J Server, if the option is available. Next, select Tools | Embedded OC4J
Server Preferences. Under the Global node, expand the Authentication (JAZN) node.
Expand Realms | jazn.com and click the Users node. Add two users: user 101 with a
password of 101, and user 102 with a password of 102. Select the Roles node and click
users in the Roles pane. Click the Member Users tab and move users 101 and 102 to
the selected pane. Click OK.
Oracle JDeveloper 10g: Build Applications with ADF B-53

Practice 15-1
b. Right-click the welcome.jsp page and select Run from the context menu. When
prompted, enter a user ID and password. The valid user IDs are 101 and 102. The
passwords are the same as the user IDs.
c. Click the authenticateUserJAZN link. This is the new link that you just added.
d. Note that you are directed to the categories page and that the username is displayed at
the top of the page.
e. Experiment with other user IDs, including invalid IDs.
f. Close the application when you have done testing.

Oracle JDeveloper 10g: Build Applications with ADF B-54

Practice 16-1: Building a UIX XML Page


The goal of this practice is to build a UIX XML page, including ADF Business Components, and
then run the page using JDevelopers OC4J server The company would like to see what ADF UIX
technologies could do for their online ordering system. To enable them to make a better decision,
they have asked you to build a mock-up of the customers screen using UIX XML. They would
like to brand the pages and allow users to navigate and find out about products. Your job is to
create the page.
Start JDeveloper, and open the practice16 workspace.
Construct the UIX XML Page
1. In the JDeveloper menu, select the Open menu option and navigate to the practice16
workspace.
2. In the navigator, expand the practice16 node and select the ViewController node.
Right-click and select the New option.
3. In the New window, highlight the ADF UIX node, and in the right pane select the UIX XML
Page with Header, Footer, and Navigation option. Click OK to invoke the UIX XML Page
Wizard, which enables you to build the page.
4. Populate the wizard properties with the following values.
Step 1: File Name = Customer.uix
Step 2: Page Title = ADF Course Customer Page
Step 3: Corporate Branding = ..\public_html\images\exlibris.gif
Step 4: Product Branding = ..\public_html\images\product.gif
Step 5: Tab Bar = (Specify the selected tab index = 0) and add the following tabs.
Tab Text

Tab Destination

Customers

Products

Details

Step 6: Page Header Text = ADF Course Practice

Oracle JDeveloper 10g: Build Applications with ADF B-55

Practice 16-1: Building a UIX XML Page (continued)


Step 7: Global Buttons
Text

Destination URL

Image Location

Cart

..\public_html\images\cart.gif

Help

..\public_html\images\help.gif

Logon

..\public_html\images\login.gif

Step 8: Specify your own copyright information.


Click Finish and the Visual Editor will display your page.
5. Right-click on the page in the Visual Editor and select Run Customer.uix to see the page run
in a browser.

Oracle JDeveloper 10g: Build Applications with ADF B-56

Practice 16-2: Adding Data Components to a UIX XML Page


The goal of this practice is to include existing ADF Business Components on the Customer page.
The page uses a distinct data component and service named SalesAppModule and the
CustomerView1 view.
Add Data Components to the Customer Page
1. Open the Customer.uix page in the Visual Editor. In the Data Control Palette, expand the
SalesAppModule node, exposing the CustomerView1 and Operations nodes.
2. Select the CustomersView1 node and ensure that the Drag and Drop As: pull-down is set
to Read-Only Table.
3. Drag the CustomersView1 from the Data Control Palette to the center of the Customer.uix
page in the Visual Editor.
4. The columns from left to right should include Select, CustomerId, CustFirstName,
CustLastName, NLS Language, CreditLimit, CustEmail, and Status. You may double-click
each label and change the text property to something that you deem appropriate.
5. Right-click anywhere on the Visual Editor and run the Customer.uix page. Your page
should look similar to the following example.

Oracle JDeveloper 10g: Build Applications with ADF B-57

Practice 17-1
The purpose of this practice is to deploy a Struts application to OC4J. You will be manually
deploying the application created in practice 14 to a local OC4J server. The OC4J server will
actually be that which is installed with JDeveloper, but the deployment steps are the same for a
production deployment.
Start JDeveloper, and open the practice17 workspace.
1. The ADF framework requires version 1.4 of the Java run time. To make sure that this is the
default version on your machine, run java version from a command prompt. If the
version is not 1.4, change your path statement to ensure that the correct version is used. The
1.4 Java run time is delivered with JDeveloper and is the directory
<Jdev_Home>/jdk/bin.
2. First, install the OC4J server.
a. Open a command prompt, and navigate to the <JDEV_Home>\j2ee\home
directory. This is where the OC4J server is installed.
b. Type java -jar oc4j.jar install at the prompt to start the install of the
OC4J server.
c. Specify a password that you want to use (admin). You will need this password in the
next few steps.
d. Confirm you password.
3. Next, start the OC4J server.
a. Open a command prompt and navigate to the <JDEV_Home>\j2ee\home directory.
This is where the OC4J server is installed.
b. Type java -jar oc4j.jar at the prompt to start the OC4J server.
c. The server will automatically deploy any .war files that were included in the
deployment directories at install, and when finished will display Oracle
Application Server Containers for J2EE 10g (9.0.4.0.0)
initialized Oracle9iAS (9.0.2.0.0) Containers for J2EE
initialized.
4. Next, create a connection to the OC4J server.
a. Click the Connections tab on the navigator pane. Right-click Application Server and
select New Application Server Connection from the context menu.
b. Name the new connection OC4J. Select the StandaloneOC4J type and click Next.
c. Supply the username and password for the OC4J Connectionthe admin password is
the one that you have specified at install. Select the Deploy Password check box, and
then click Next to continue.
d. Accept the default ormi mappings for the server, and click Next.
e. Test the connection to ensure that the server is running and the username and password
are valid.
5. Set the Welcome.jsp as the default run target for the application.
a. Open the Page Flow Diagram for the application.
b. Right-click welcome.jsp on the diagram.
c. Choose Set as Default Run Target from the context menu.
6. Now create a deployment profile for the application.
a. Right-click the ViewController node, and select New from the context menu.
b. Create a New deployment profile by using the war file.
c. Specify shoppingApp as the deployment profile name.
d. Click OK to close the Deployment Profile Wizard.
Oracle JDeveloper 10g: Build Applications with ADF B-58

Practice 17-1 (continued)


7. Finally, deploy the .war file to the remote the OC4J server.
a. Right-click shoppingCart.deploy and select Deploy to > <Your OC4J
Connection Name>. JDeveloper will deploy the .war file. The status of the
deployment can be seen in the command window started in step 1.
b. Open a browser and navigate to http://localhost:8888. This should display Oracle9iAS
Containers for J2EE 9.0.2.0.0 Up and running. This is the home page of OC4J.
c. Append the context root for this application to the URL and the beginning JSP for this
application, that is, welcome.jsp. (The context root appears in the deployment log
window of JDeveloper.)
d. Test the application by navigating through it. It should be the same as when you ran it
locally.
e. Close the application when you are done.

Oracle JDeveloper 10g: Build Applications with ADF B-59

Vous aimerez peut-être aussi