8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
1/61
Advanced JavaServerFacesTopics
Web Programming
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
2/61
FacesContext
2Web Programming
In the previous chapter:
FacesContext was used to object in accessing a Map of the objectscurrently in the user session.
An instance of the FacesContext object can be obtained by callingthe FacesContext.getCurrentInstance() method.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
3/61
FacesContext and the
Component Tree
3Web Programming
For each views using JSF UI elements, there is acorresponding component tree that models it. The JSF
specification requires that all implementations of JSF storethis component tree inside the FacesContext object.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
4/61
Component Tree
4Web Programming
Allows developers access to all of the user interfacecomponents and their data.
Also allows developers to:
Programatically add components to the view. Change or add converters or validators dynamically.
Remove components.
Most often used to provide screen redirection within the
Faces framework.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
5/61
Component Tree
5Web Programming
Example:
...
String targetPage = "/newPage.jsp";
FacesContext context = FacesContext.getCurrentInstance();
context.getApplication().getViewHandler().createView(context, targetPage);
...
The createView method creates a copy of the component tree thatmakes up the targetPage and places it as the current viewcomponent tree.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
6/61
FacesContext and the
External Context
6Web Programming
The ExternalContext object accessible throughFacesContext gives us access to the environment the
framework is running on. For a web application, it gives us access to:
The HttpServletRequest object representing the current request.
A Map of the object stored in the user session.
The ServletContext object representing the context of the whole webapplication.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
7/61
FacesContext and the
External Context
7Web Programming
(Web application continued)
To retrieve the HttpServletRequest object:
FacesContext context = FacesContext.getCurrentInstance();HttpServletRequest request =(HttpServletRequest)context.getExternalContext()
.getRequest(); No way to have direct access to the actual HttpSession object
associated with our session, but the objects stored within it can beaccessed through a Map object:
Map sessionMap = context.getExternalContext().getSessionMap();
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
8/61
FacesContext and the
External Context
8Web Programming
(Web application continued)
To retrieve the ServletContext representing our entire application:
ServletContext servletContext =(ServletContext)context.getExternalContext().getContext();
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
9/61
JSF Standard Validators
9Web Programming
JSF provides us with a set of validators that we can use out-of-the-box for our application.
Three standard validators:
DoubleRangeValidator: Checks if the value in the input field isconvertible into double and that it is within the supplied minimumand maximum values.
JSP Tag: validateDoubleRange
Attributes: minimum, maximum
LengthValidator: Checks if the value in the input field is convertibleinto a String and that its length is within the supplied minimum andmaximum values.
JSP Tag: validateLength
Attributes: minimum, maximum
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
10/61
JSF Standard Validators
10Web Programming
(Standard validators continued)
LongRangeValidator: Checks if the value in the input field isconvertible into a long and that it is within the supplied minimum andmaximum values.
JSP Tag: validateLongRange
Attributes: minimum, maximum
The JSP tags for the validators can all be found inside thecore tag library. To use them, we add the following line tothe top of the page:
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
11/61
Using the Standard Validators
11Web Programming
Insert the JSP tag for the validator inside the body of theinput component to be validated.
Example:
...
...
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
12/61
Using the Standard Validators
12Web Programming
(Example continued)
This is the JSP code for the login page we implemented in theprevious lesson using JSF, with some modifications:
The tag defining the password field () was changed such that the
tag no longer closed itself on the same line it was declared. It now makes use ofa matching tag to close itself.
The tag defining the validation to be performed () was insertedbetween the opening and closing tags.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
13/61
Customized Validation
13Web Programming
Three ways:
Extend the class of the UI component that accepts our input so thatwe could override its validate method.
Non-portable
Create an external validation method.
Create our own separate Validator implementations, register them inthe framework, then plug it into the UI component.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
14/61
External Validation Method
14Web Programming
Creating an external validation method
Similar to the one to create an application method that will handleaction events:
We also need to create a method adhering to a set of rules inside a JavaBean
managed by the framework and later bind that method to the appropriate UIcomponent.
The method that we create must conform to the following rules:
The method must be declared public, with a return type of void.
There is no limitation to the method name.
It must take the following parameters in this order: FacesContext ctxt, UIInputcomponent, Object value.
It must be declared to throw a ValidatorException.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
15/61
External Validation Method
15Web Programming
(Creating continued)
To create a custom validation method for our password field in theprevious example, one that would accept only alternating letters andnumbers:
public void validatePassword(FacesContext ctxt, UIInput component, Object value)throws ValidatorException
For the method implementation, we can make use of data providedthrough the parameters:
The FacesContext object provides us access to external resources such as theobjects in request and session scope, as well as other objects within the Faces
framework. The UIInput object is the instance of the input component that requires validation;
having an instance of this object gives us access to the component's state.
The Object value is the value inside the component that requires validation.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
16/61
External Validation Method
16Web Programming
(Creating continued)
Implementation of our method:
public void validatePassword(FacesContext ctxt, UIInput component, Object value)throws ValidatorException {
if (null == value)return;
if ( ! (isPasswordValid(value.toString() ) ) {FacesMessage message = new FacesMessage(Input error, Password is not
valid);throw new ValidatorException(message);
}
}
protected boolean isPasswordValid(String password) {... FacesMessage: Models a message within the Faces framework. The first
parameter passed into its constructor is a summary, the second the details ofthe actual message.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
17/61
External Validation Method
17Web Programming
(Creating continued)
To be able to actually display the generated error message,developers should add an or tag in theJSP page.
...
... : Displays messages only for a specific component, indicated by
the value in the for attribute. An tag will display all themessages available for all the components in the page
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
18/61
Separate Validator
Implementation
18Web Programming
Create a separate class that implements the Validatorinterface.
Defines one method: a validate method Public
Returns void
Parameters are instances of the FacesContext, UIInput, and Object classes
No difference with that of an external validation method in terms ofinternal method implementation.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
19/61
External vs. Separate
19Web Programming
Difference: how they are used.
An external validation method is used more for validation codespecific to a particular component.
A separate Validator implementation is used to contain general-
purpose validation code that will be reused extensively within yourapplication(s).
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
20/61
Separate Validator
Implementation
20Web Programming
Registering a Validator component
To use a custom Validator component, we must first register it sothat it can be recognized by the JSF Framework.
This is done by placing a configuration entry in the faces-config.xmlfile.
Example:
A validator for checking the password
fieldAlternatingValidatorjedi.sample.jsf.validator.AlternatingValidator
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
21/61
Separate Validator
Implementation
21Web Programming
Using a validator component
To use the Validator component that we just registered, we makeuse of the tag and supply in its validatorId attribute ourvalidator's id.
Example:
...
...
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
22/61
Separate Validator
Implementation
22Web Programming
Adding attributes to our validator
Add a property within our class for each of the attributes it wouldsupport and implement get and set methods for each of them.
Include an entry for each of the attributes within our configurationentry for the validator.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
23/61
23Web Programming
package jedi.sample.jsf.validator;
public class AlternatingValidator implements Validator {private Integer interval;
public Integer getInterval() {return interval;
}
public void setInterval(Integer interval) {this.interval = interval;
}
public void validate(FacesContext ctxt, UIInput component, Object value)throws ValidatorException {
if (null == value || interval == null)return;
if ( ! (isPasswordValid(value.toString() ) ) {FacesMessage message = new FacesMessage(Input error, Password is not valid);
throw new ValidatorException(message);}
}
protected boolean isPasswordValid(String password) {...
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
24/61
24Web Programming
A validator for checking the password fieldAlternatingValidatorjedi.sample.jsf.validator.AlternatingValidator
intervaljava.lang.Integer
___________________________________________________________________________
...
...
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
25/61
Converters
25Web Programming
Convert the values given by the user from their native stringrepresentation into the appropriate format or type usedinternally by the server.
Bi-directional: They can also be used to change how internal
data is displayed to the user.
Define a getAsString() and getAsObject() method that canbe called by the framework at the appropriate time.
getAsString: Called to provide a String representation to the data.
getAsObject: Used to convert the String into the type required.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
26/61
Converters
26Web Programming
Associated to input types by making use of the converterattribute built-in into some of the input components providedby Faces.
Components that support the converter attribute:
inputText
inputSecret
inputHidden
OutputText
Example:
To modify an inputText tag so that it naturally allows for Integerconversion:
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
27/61
Converters
27Web Programming
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
28/61
Converters
28Web Programming
Of this set of converters:
Most of the converter sets are non-configurable.
DateTimeConverter and NumberConverter, however, can make useof special tags, which may allow a developer to customize their
behavior.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
29/61
DateTimeConverter
29Web Programming
Can be used to convert user input into instances ofjava.util.Date.
Provides a number of attributes with which the developercan specify the format used in the conversion.
Format specified is enforced when the user supplies his input. Ifviolated, a conversion error will occur, and the framework will haltfurther processing of data.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
30/61
DateTimeConverter
30Web Programming
Attributes made available using tag:
dateStyle: One of the date styles defined in java.text.DateFormat.Possible values are: default, short, long, medium, or full.
parseLocale: Locale to use during conversion.
pattern: Formatting pattern to be used in conversion. If a value forthis attribute is specified, the system will ignore any values fordateStyle, timeStyle, and type.
timeStyle: One of the time styles defined in java.text.DateFormat.Possible values are: default, short, medium, long, or full.
timeZone: Time zone to use.
type: A String that defines whether the output will be a data or timeinstance, or both. The possible values are: date, time, and both.Default value is date.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
31/61
DateTimeConverter
31Web Programming
Example: usage of the DateTimeConverter:
Create a blank web application ready for JSF.
Create a simple bean that will hold the date we will input later.
import java.util.Date;
public class DateBean {private Date date;
public Date getDate() {return date;
}
public void setDate(Date date) {this.date = date;
}}
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
32/61
DateTimeConverter
32Web Programming
(Example continued)
Add its configuration entry in the faces-config.xml.
This bean serves as the backing model for our date conversion exampledateBeanjedi.sample.DateBeanrequest
date
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
33/61
DateTimeConverter
33Web Programming
(Example continued)
Create the JSP file that will generate the view.
Date :
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
34/61
DateTimeConverter
34Web Programming
(Example continued)
Notes for the sample JSP page:
For our DateTimeConverter, we have specified a pattern of M/d/yy. Since theconverter enforces this pattern on the user, the user will have to input somethinglike 1/13/06 as a date before he can continue.
We have added a required attribute with a true value for our input field. Thisensures that the user cannot post blank inputs.
We have made use of an tag associated with our dateField input.This makes sure that any messages generated by the input field (like thosegenerated by conversion errors) are displayed.
The action attribute for the commandButton has deliberately been left blank, so
we can focus solely on the messages generated by the converter.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
35/61
DateTimeConverter
35Web Programming
(Example continued)
Loading the web application into a compatible server and accessingthe page:
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
36/61
DateTimeConverter
36Web Programming
(Example continued)
Trying out an input of January 13, 2006 would result in the following:
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
37/61
DateTimeConverter
37Web Programming
(Example continued)
Entering a date in the proper format would result in no change to ourpage, which indicates that the data was successfully converted andstored in our bean.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
38/61
DateTimeConverter
38Web Programming
(Example continued)
What if we did not use the converter?
Date :
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
39/61
DateTimeConverter
39Web Programming
(Example continued)
Now, entering a date of any format will cause an error:
This is because the property associated with our input field is a Date object. Theframework cannot automatically change the String representation of the inputinto a date, so it looks for a Converter object that will handle it. Since nonewere found, it threw a null error.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
40/61
NumberConverter
40Web Programming
Used to convert number inputs and enforce specialformatting on them.
Attributes:
currencyCode: An ISO 4217 currency code to be applied when
formatting currency.
currencySymbol: The currency symbol to use when formattingcurrency.
groupingUsed: Indicates whether a grouping symbol will be used.
integerOnly: Indicates whether the integer part only of the numberwill be displayed or stored.
locale: Locale used.
maxIntegerDigits: The maximum number of digits shown or usedwhen handling the integer part of the number.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
41/61
NumberConverter
41Web Programming
(Attributes continued)
maxFractionDigits: The maximum number of digits that will beshown or used when handling the decimal part of the number.
minFractionDigits: The minimum number of digits that will be shown
or used when handling the decimal part of the number. minIntegerDigits: The minimum number of digits that will be shown
or used when handling the integer part of the number.
pattern: The pattern to be used when formatting or displaying thenumber.
type: Indicates whether the number to be converted is treated as acurrency, percent, or number. Possible values are currency, percent,and number.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
42/61
NumberConverter
42Web Programming
(Attributes continued)
Any patterns or symbols indicated in the attributes are enforced asrules on the user, and if violated, a conversion error will occur andfurther processing of the data will halt.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
43/61
Custom Converters
43Web Programming
Can be created by creating a class which implements theConverter interface. This interface defines two methods:
public Object getAsObject(FacesContext ctxt, UIComponentcomponent, String input)
public Object getAsString(FacesContext ctxt, UIComponentcomponent, Object source)
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
44/61
Custom Converters
44
Web Programming
Sample scenario:
We have a form page that requires the user to input a monetaryamount.
We would like to store this input as a Double object so as to facilitate
easier processing later on. The input field must be flexible enough to handle straight number
inputs (ex. 2000), or inputs that include grouping symbols (2,000).Since the page will revert control back to itself, the data should beredisplayed as having grouping symbols.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
45/61
getAsObject
45
Web Programming
Called by the framework on the associated converter when itneeds to convert the user's input from its string representationinto another object type.
Concept: Perform processing operations on the provided
String parameter and return the Object that will represent it onthe server side.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
46/61
46
Web Programming
public Object getAsObject(FacesContext facesContext, UIComponent uIComponent,String str) {
Double doubleObject = null;try {
doubleObject = Double.valueOf(str);} catch (NumberFormatException nfe) {
//if exception occurs, one probable cause is existence of grouping symbol
//retrieve an instance of a NumberFormat object//and make it recognize grouping symbols
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setGroupingUsed(true);
// use the NumberFormat object to retrieve the numerical value of the inputtry {
Number number = formatter.parse(str);if (number.doubleValue()
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
47/61
47
Web Programming
} catch (ParseException pe) {// if code reaches this point, none of the supported formats were followed.// create an error message and display it to the user through the exception object
FacesMessage message = new FacesMessage("Unsupported format","This field supports only numbers (5000), or numbers with commas (5,000)");
throw new ConverterException(message);}
}
return doubleObject;
}
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
48/61
getAsString
48
Web Programming
Makes Converters bi-directional: It dictates the Stringrepresentation of the relevant internal data.
Concept: Display the amount stored within the Double objectas a number with grouping symbols.
Simpler because we know with certainty the exact format ofour input.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
49/61
49
Web Programming
public String getAsString(FacesContext context, UIComponent component, Objectsource) {
Double doubleValue = (Double)obj;
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setGroupingUsed(true);
return formatter.format(doubleValue);
}
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
50/61
Using the Custom Converter
50
Web Programming
After we have created our custom converter:
Configure the framework so that it can recognize its existence. Adda configuration entry in the faces-config.xml.
Configuration entries for converters come after all entries for validators, butbefore any entries for managed beans.
Custom converter for accepting monetary inputmyConverterjedi.sample.MyCustomConverter
Specify its converter id within an tag:
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
51/61
Value Binding
51
Web Programming
(Example continued)
The JSF page is able to associate the loginPage identifier to aninstance of a LoginPageBean due to our entry in the faces-config.xml. The relevant entry is presented below:
This bean serves as the backing model for our login formloginPagejedi.sample.LoginPageBeanrequest...
Since the LoginPageBean is declared to be a managed bean in the framework,an instance of LoginPageBean will be created and placed in the configuredscope (if one doesn't already exist) when the JSF page is evaluated. On pagesubmission, the values that the user has entered would be automatically placedwithin the bean's properties.
Registering Action Handlers
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
52/61
Registering Action Handlersto View Components
52Web Programming
JSF introduces the concept of event-based programminginto the web environment.
Some of the UI components that JSF provides will, given theappropriate user action or input, generate events that can beprocessed by action handlers.
Registering Action Handlers
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
53/61
Registering Action Handlersto View Components
53Web Programming
Example:
To "register" a handler for a commandButton component:
...
...
The # notation binds a method named performLogin found in a bean referencedwith the name loginPage to our button. This time, instead of storing the value forthe component, the bound method acts as the action handler for the button click.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
54/61
Page Navigation
54Web Programming
JSF determines the next screen that will be displayed to theuser upon form submission using the return value of themethod that serves as the action handler for the submitbutton.
The String value is looked up against navigation rules defined withinthe configuration file.
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
55/61
Page Navigation
55Web Programming
Example:/login.jsfAny failure result should bring the user to an error page
failure/error.jspSuccessful login should bring user to welcome pagesuccess/welcome.jsp
So, if the performLogin method were to return a value or outcome of"failure", the user will be redirected to error.jsp.
P N i i
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
56/61
Page Navigation
56Web Programming
(Example continued)
As an alternative to using an action handler, it is also possible tostatically provide the navigation rule to be called:
...
...
Oth JSF C t T
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
57/61
Other JSF Component Tags
57Web Programming
Acts in a way similar to that of the tag in the Strutsframework.
Exposes messages from the application into the output text.
Displays an HTML element.
Takes in an array (or collection of objects) and iterates over them,automatically creating the necessary and elements.
Defines a child tag named . Content placed inside the body of a tag form the template for the
column definition for each row in the table.
Oth JSF C t T
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
58/61
Other JSF Component Tags
58Web Programming
( continued)
Example:
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
59/61
Other JSF Component Tags
59Web Programming
( continued)
HTML equivalent
Ewan
Coba
DevonShire
California
San Diego
Oth JSF C t T
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
60/61
Other JSF Component Tags
60Web Programming
( continued)
Attributes include (but are not limited to):
value: Defines the collection or array to be iterated over. This could either be aproperty inside a managed bean or a method in a bean that will return thenecessary content.
var: Defines the name of the variable which will expose the contents of thecollection or array being iterated over. This variable is visible only within the tag.
border, cellspacing: Standard HTML table attributes.
rowClasses: A comma-delimited list of CSS styles that will alternately be appliedto each of the rows in the table.
Oth JSF C t T
8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter10 Advanced JSF
61/61
Other JSF Component Tags
61Web Programming
Container tags like only allow JSF tags within theirbody. This means that custom tags or even JSTL tags will not workinside of them. This can be circumvented with the use of the tag