Вы находитесь на странице: 1из 37

Working with Managed Beans and JavaServer Faces

Copyright 2008, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following: Define key JavaServer Faces (JSF) terms Describe the JSF architecture with Application Development Framework (ADF) Differentiate between managed and backing beans Create and reference managed beans Set and use managed properties Use context objects to access the application

7-2

Copyright 2008, Oracle. All rights reserved.

Agenda
Key Terms and Concepts Expression Language (EL) Managed Beans and Properties

7-3

Copyright 2008, Oracle. All rights reserved.

JSF Review
JSF simplifies Web development because it: Is component-based, not markup-based Offers automatic event and state handling Can be used for a diverse client base, and not just HTML Is designed with tooling in mind Is applicable to a wide spectrum of programmer types

7-4

Copyright 2008, Oracle. All rights reserved.

Key Terms
UI component: JSF is component based. Managed bean: It includes objects maintained by the JSF inversion of control mechanism. Expression Language: It holds the key to bind the data. Life cycle: It involves the process of how JSF works.

7-5

Copyright 2008, Oracle. All rights reserved.

JSF Architecture

Markup

Device renderer

<f:view> <h:inputText required="true" value="#{emp.name}" /> </f:view>

JSF Page
UI component Expr. language Managed bean

J2EE persistence layer/JDBC

RDBMS

7-6

Copyright 2008, Oracle. All rights reserved.

Standard Component Model for Web Development


JSF provides the UI component. JSF components:
Have properties and can raise events Can be nested Offer predictable rendering and follow the event-handling life cycle

Basic library of UI components Core and HTML Third-party component libraries

7-7

Copyright 2008, Oracle. All rights reserved.

JSF Expression Language


EL connects UI components: To model properties for data:
<h:inputText id="lastName required="true" value="#{customer.lastName}"/>

To create Web-tier application object methods for handling events:


<h:commandButton id="save value="Save Changes" action="#{customerHandler.saveAll}"/>

7-8

Copyright 2008, Oracle. All rights reserved.

Summary of Key Elements


Renderer
displays
translates value verifies value updates generates

Event
consumes

UI Component
contains

Contained in

View

Event listener
manipulates executes selects

Converter
generates

Validator
generates

Model objects
specialized

Backing bean Message


generates

Action method
outcome

Navigation

7-9

Copyright 2008, Oracle. All rights reserved.

JSF Suggestions
Use only JSF:
Use components, not HTML, for creating the layout. Exploit the rendered property for conditional display.

Manage all (non-model) states through JSF managed beans; try not to access the session or request directly.

FacesContext fctx = FacesContext.getCurrentInstance(); Application application = fctx.getApplication(); ELContext elctx = fctx.getELContext(); ExpressionFactory exprfactory = application.getExpressionFactory(); ValueExpression valueExpression = exprfactory.createValueExpression(elctx,"#{mybean}",Object.class); MyBean myBean = (MyBean) valueExpression.getValue(elctx);

7 - 10

Copyright 2008, Oracle. All rights reserved.

Agenda
Key Terms and Concepts Expression Language (EL) Managed Beans and Properties

7 - 11

Copyright 2008, Oracle. All rights reserved.

EL Used in Managed Beans


<managed-bean> <managed-bean-name>userbean</managed-bean-name> <managed-bean-class>com.oracle.sample.User</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>userType</property-name> <value>#{reference['USER_TYPES'].['EMPLOYEE']}</value> </managed-property> </managed-bean>

Managed properties

Java code

FacesContext fctx = FacesContext.getCurrentInstance(); Application application = fctx.getApplication(); ELContext elctx = fctx.getELContext(); ExpressionFactory exprfactory = application.getExpressionFactory(); ValueExpression valueExpression = exprfactory.createValueExpression(elctx,"#{userbean}",Object.class); User user = (User) valueExpression.getValue(elctx);

7 - 12

Copyright 2008, Oracle. All rights reserved.

Expression Language: Examples


#{somevar}: Value of the variable named somevar
Checks at different scopes until it finds a match If no match is found, tries the managed bean named somevar

#{param.somevar}: Value of the request parameter named somevar #{requestScope.somevar}: Value of the request attribute named somevar #{sessionScope.somevar}: Value of the session attribute named somevar #{cookie.somevar}: Value of the cookie named somevar

7 - 13

Copyright 2008, Oracle. All rights reserved.

More Expression Language


#{user.name} and #{user["name"]}: Check at different scopes until a match is found
The name property of the scoped variable user

#{resources.rowLockedError}: The entry with the rowLockedError key in the Map named resources #{user[name]}: The user bean property whose name is given by the value of the name property #{user.addresses[0]}: The first element in the addresses collection property of user #{bindings}: A scoped variable named bindings #{bindings.empTable.labels}: The labels property of the entry with the empTable key in the Map named bindings
Copyright 2008, Oracle. All rights reserved.

7 - 14

Immediate EL Syntax: ${}


It is evaluated immediately. It can only be used within template text or as the value of a JSP tag attribute.
<fmt:formatNumber value="${sessionScope.cart.total}"/>

Code example: JSP value attribute references EL that gets the total price from the session-scoped bean named cart. The JSP engine evaluates the expression, converts it, and passes the returned value to the tag handler. Immediate evaluation expressions are always read-only value expressions. The example can only get the total price from the cart bean; it cannot set the total price.

7 - 15

Copyright 2008, Oracle. All rights reserved.

Deferred EL Syntax: #{}


It is evaluated at other phases of a page life cycle as defined by the technology that uses the expression (JSF).
<h:inputText id="name" value="#{customer.name}" />

Code example: JSF value attribute references EL that points to the name property of the customer bean.
First request: #{customer.name} evaluated during the Render Response phase of the life cycle. EL gets the value of name from the customer bean, as is done in the immediate evaluation. Postback: JSF evaluates the expression at different phases of the life cycle, during which the value is retrieved from the request, validated, and propagated to the customer bean.

Deferred EL can be value expressions that can be used to read and write data.
Copyright 2008, Oracle. All rights reserved.

7 - 16

Agenda
Key Terms and Concepts Expression Language (EL) Managed Beans and Properties

7 - 17

Copyright 2008, Oracle. All rights reserved.

Managed Beans
Managed beans are optional and can be used to:
Hold presentation and navigation logic Store state (for example, information about the authenticated user) Execute a Java routine (for example, by clicking a button) Define a handler for event listeners

Managed beans are not the same as backing beans. Backing beans are a specialized type of managed bean that:
Contain getter and setter methods for UI components Have a one-to-one relationship with a page

7 - 18

Copyright 2008, Oracle. All rights reserved.

Defining Managed Beans


Can be any Java object, such as maps and lists, as long as it has an empty constructor Are defined in faces-config.xml for JSF and in adfcconfig.xml or other task flow metadata files for ADF Are defined with various scopes:
Application Session Request None

Have a lazy initialization by JSF, as needed

7 - 19

Copyright 2008, Oracle. All rights reserved.

Using Managed Beans


Definition:

<managed-bean> <managed-bean-name>userbean</managed-bean-name> <managed-bean-class>com.oracle.sample.User</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>

Usage on a page:

<h:inputText value="#{userbean.name}"/>

Usage in Java code:

FacesContext fctx = FacesContext.getCurrentInstance(); Application application = fctx.getApplication(); ELContext elctx = fctx.getELContext(); ExpressionFactory exprfactory = application.getExpressionFactory(); ValueExpression valueExpression = exprfactory.createValueExpression(elctx,"#{userbean}",Object.class); User user = (User) valueExpression.getValue(elctx);

7 - 20

Copyright 2008, Oracle. All rights reserved.

Accessing One Managed Bean from Another Managed Bean


There are three major ways: Using value binding Using variable resolver Having the reference property
<managed-bean> <managed-bean-name>person</managed-bean-name> <managed-bean-class>demo.PersonBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-bean> <managed-bean> <managed-bean-name>bank</managed-bean-name> <managed-bean-class>demo.BankBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-bean>

7 - 21

Copyright 2008, Oracle. All rights reserved.

Hard-Coded Access
Both value binding and variable resolvers hard code values.

FacesContext fctx = FacesContext.getCurrentInstance(); Application application = fctx.getApplication(); ELContext elctx = fctx.getELContext(); ExpressionFactory exprfactory = application.getExpressionFactory(); ValueExpression valueExpression = exprfactory.createValueExpression(elctx,"#{bank}",Object.class); BankBean bank = (BankBean) valueExpression.getValue(elctx);

ELResolver elResolver = fctx.getApplication().getELResolver(); BankBean b = (BankBean) elResolver.getValue(elctx,null,bank");

7 - 22

Copyright 2008, Oracle. All rights reserved.

Using Properties to Access Values


Add a property to one managed bean that references the second managed bean.

<managed-bean> <managed-bean-name>Person</managed-bean-name> <managed-bean-class>demo.PersonBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>bank</property-name> <property-class>demo.BankBean</property-class> <value>#{bank}</value> </managed-property> <managed-bean> <managed-bean> <managed-bean-name>bank</managed-bean-name> <managed-bean-class>demo.BankBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-bean>

7 - 23

Copyright 2008, Oracle. All rights reserved.

Managed Properties
Managed properties: Are managed bean variables that are exposed through getter and setter methods Are configured in faces-config.xml Can take the following possible values:
Null Literal string Lists and maps Value-binding Expression Language (EL)

7 - 24

Copyright 2008, Oracle. All rights reserved.

Managed Properties: Examples


Literal string:
<managed-bean> <managed-property> <property-name>label</property-name> <value>Hello World</value> </managed-property>

EL accessing managed bean:


<managed-bean> <managed-property> <property-name>label</property-name> <value>#{Userbean['firstname']}</value> </managed-property>

7 - 25

Copyright 2008, Oracle. All rights reserved.

JSF Value Binding


JSF pages can create value bindings to the ADF binding container using EL accessing the bindings object.
#{bindings.firstName.inputValue}

The bindings object is created by the ADF servlet filter that is defined in the web.xml file. The ADF servlet filter is mapped to *.jsp and *.jspx file types. The bindings object needs to be configured as a managed property before it can be used in managed beans.

7 - 26

Copyright 2008, Oracle. All rights reserved.

Writing Code That Interacts with Bindings


Getting access to the binding in the code (best practice): Inject the #{bindings} object into the managed bean.
<managed-bean> <managed-bean-name>EditPageBean</managed-bean-name> <managed-bean-class>view.backing.EditPageBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>bindings</property-name> <value>#{bindings}</value> </managed-property> </managed-bean>

Add getters and setters for oracle.binding.BindingContainer.

JDeveloper will do this automatically if you let it maintain backing beans for you.

7 - 27

Copyright 2008, Oracle. All rights reserved.

Accessing the Bindings


Include process logic or write conditional logic to return one of the multiple outcomes depending on certain criteria. For example, return null if there is an error in the processing, or another outcome value if the processing was successful.

FacesContext fctx = FacesContext.getCurrentInstance(); Application application = fctx.getApplication(); ELContext elctx = fctx.getELContext(); ExpressionFactory exprfactory = application.getExpressionFactory(); ValueExpression valueExpression = exprfactory.createValueExpression (elctx,"#{bindingsSomeAttrBind.inputvalue}"}",Object.class); Object myValue = valueExpression.getValue(elctx);

7 - 28

Copyright 2008, Oracle. All rights reserved.

Writing Code That Interacts with Bindings


Using the bindings object:

AttributeBinding deptBinding = (AttributeBinding)getBindings().getControlBinding("DepartmentName"); String departmentName = (String)deptBinding.getInputValue();

BindingContainer bindings = getBindings(); OperationBinding operationBinding = bindings.getOperationBinding("First"); Object result = operationBinding.execute(); OperationBinding operationBinding = getBindings().getOperationBinding("findDepartmentManagerId"); Map params = operationBinding.getParamsMap(); params.put("searchTerm","Sales"); Number deptManager = operationBinding.execute();

7 - 29

Copyright 2008, Oracle. All rights reserved.

Configuring ADF Binding Access for Managed Beans


Create a managed property and set the value to #{bindings}. In managed beans, create an instance variable with the same name as the managed property. Make sure that the variable type is oracle.binding.BindingCo ntainer. Create setter and getter methods for the instance variable. Binding is automatically configured on the basis of declarative method binding.
7 - 30

Copyright 2008, Oracle. All rights reserved.

Getting and Setting Bound Data


Access the value of a CoreSelectOne ADF Faces list based on the returned selected index, which is accessed from ValueChangeListener.
01. CoreSelectOneChoice singleSelectItem = (CoreSelectOneChoice) valueChangeEvent.getSource(); 02. int SelectedIndx = ((Integer) singleSelectItem.getValue()).intValue(); 03. DCIteratorBinding iter = ((DCBindingContainer)bindings). findIteratorBinding(SupplierView11"); 04. Row rw = iter.getRowAtRangeIndex(SelectedIndx); 05. valueToPrint = "The selected value is "+rw.getAttribute(AddressId");

7 - 31

Copyright 2008, Oracle. All rights reserved.

Executing Methods in ADF


Methods are defined in the pageDef file as operation bindings. The operation can be accessed and executed from ADF Faces. ADF Business Components uses methods on the ADF binding for Create, Read, Update, Delete (CRUD).

01. OperationBinding operationBinding = (OperationBinding)bindings.getOperationBinding (addItemToCart"); 02. Map params = operationBinding.getParamsMap(); 03. params.put(productId,); 04. Object result = operationBinding.execute();

7 - 32

Copyright 2008, Oracle. All rights reserved.

Executing Bound Methods on the JSF Page Load


Actions in the executable section are invoked when the page loads. Actions bind to methods or actions in the bindings definition. You can use EL to determine the condition that is on when the action is executed.

7 - 33

Copyright 2008, Oracle. All rights reserved.

Context Objects
FacesContext:
Is a static class that provides access to information such as application messages, render kits, ViewRoots, ExternalContext, and so on Represents the current request that is processed Provides access to the world outside JSF Is a context object to support ADF Facesspecific functionality:
Partial page rendering (PPR) Skinning Oracle Help Dialog framework support

ExternalContext:

ADFFacesContext:

7 - 34

Copyright 2008, Oracle. All rights reserved.

JavaServer Faces Backing Beans


Backing beans are a type of managed bean. Use one backing bean per page, if needed.
This gives you one place to manage the code. It contains logic and properties for some UI components. JDeveloper can create this backing bean for you, but you may want your own superclass.

Prune the contents of the backing bean; code interesting objects only. Place backing beans in the request scope. Use consistent naming and packaging.

7 - 35

Copyright 2008, Oracle. All rights reserved.

Summary
In this lesson, you should have learned how to: Define key JSF terms Describe the JSF architecture with ADF Differentiate between managed and backing beans Create and reference managed beans Set and use managed properties Use context objects to access the application

7 - 36

Copyright 2008, Oracle. All rights reserved.

Practice 7 Overview: Working with JSF and Managed Beans


This practice covers the following topics: Adding a method to delete order line items Creating a managed bean to track selected line items Including a button to initiate delete

7 - 37

Copyright 2008, Oracle. All rights reserved.

Вам также может понравиться