© 2009 marty hall

Upload: mahendravadar

Post on 30-May-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 2009 Marty Hall

    1/39

    2009 Marty Hall

    JSF 2.0: Ajax Support

    Originals of Slides and Source Code for Examples:

    http://www.coreservlets.com/JSF-Tutorial/jsf2/

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Topics in This Section

    MotivationAjax in general

    Ajax integrated with JSF 2.0

    Overview

    execute: specifying elements to process on server

    event: specifying user events to respond to

    onevent: specifying JavaScript side effects

    Limitations on the use of h:outputText with Ajax

    5

  • 8/14/2019 2009 Marty Hall

    2/39

    2009 Marty Hall

    Motivation

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Why Ajax?

    HTML and HTTP are weak on- nteract ve

    Coarse-grained updates

    Ever one wants to use a browserNot an application that requires SW installation

    Real browser-based active contentFailed: Java Applets Not universally supported; cant interact with the HTML

    Serious alternative: Flash (and Flex) Not yet universally supported; limited power

    New and unproven Microsoft Silverli ht JavaFX Adobe AIR (formerly Apollo)

    7

  • 8/14/2019 2009 Marty Hall

    3/39

    Traditional Web Apps vs.

    n requen arge up a es requen sma up a es

    8 Dia rams fromA ax in Action b Dave Crane et al Mannin Press. See recommended books in next lecture.

    Google Home Page

    9

  • 8/14/2019 2009 Marty Hall

    4/39

    Ajax Jobs (as of Sept. 2009)

    Indeed.com compiles data from many jobs sites

    10

    Why Ajax in JSF

    Why a JSF-specific Ajax library?There are tons of Ajax libraries already (jQuery, DWR,

    GWT, etc.). Why invent a new one for JSF?

    -Client side

    You can update JSF elements (h:outputText, h:inputText,h:selectOneMenu, etc.)

    It would be very unwieldy if Ajax updates were entirely separateelements from the Ajax UI elements

    ou on t ave to wr te ava cr pt

    Server side A ax calls know about JSF mana ed beans

    Including reading form fields and setting bean properties

    You dont have to write servlets and parse parameters11

  • 8/14/2019 2009 Marty Hall

    5/39

    2009 Marty Hall

    f:ajax Overview

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Simplest Form

    Code

    n erpre a onWhen the pushbutton is pressed, go to server, run the

    ,id1, send that value back to the client, then replace thatelement in the DOM with the new value.

    13

  • 8/14/2019 2009 Marty Hall

    6/39

    General Form

    Code< :comman utton act on= >

    :comman u on

    Attributes render

    The elements to redisplay on the page. Often h:outputText

    execute .

    elements such as h:inputText or h:selectOneMenu.

    event . ., ,onevent

    A JavaScript function to run when event is fired14

    Ajax Testing

    JavaScript is notoriously inconsistent ou ope t at t e mp ementat on too t s nto

    account, and hid the browser differences. Nevertheless,JSF 2.0 is a specification, not an implementation, so

    eren mp emen a ons cou e e er or worse a s.

    Test on multiple browsers

    If ou field an internal a lication test on all officiallsanctioned browsers on all supported operating systems.

    If you field an external application, test on as many. , , ,

    Firefox implementation, and Safari. Test regularly on IE and Firefox. Test on a wider set of

    browsers before de lo in . Usage: http://www.w3schools.com/browsers/browsers_stats.asp

    This is needed for any Ajax application, not just for JSF 2.15

  • 8/14/2019 2009 Marty Hall

    7/39

    2009 Marty Hall

    render:Specifying Elements to

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    The render attribute of f:ajax

    Code summary

    Idea -

    should be returned from server and replaced in DOM

    Details There are four special values: @this, @form, @none, and

    @all. However, these are more often used for the executeattribute than the render attribute. See execute section.

    Unless you use , the real ID isformId:elementId. See first example for default version, andsecond exam le for re endId="false".

    Value for render (and execute and event) can be JSFexpressions instead of literal strings

    17

  • 8/14/2019 2009 Marty Hall

    8/39

    Facelets Code

    Random Number (with render="fId:eId")

    < :ou pu ex va ue= num er enera or.num er

    id="numField1"/>

    < : orm>

    When the pushbutton is pressed, go to server and get bean whose name isnumberGenerator(since it is session scoped, use existing instance if available,

    otherwise instantiate it). Then, run the randomize method. Then, compute thevalue of the getNumbermethod. Send that value back to the client and insert it

    18

    into the DOM in the place where the h:outputText is. Note that the actual id of theDOM element resulting from h:outputText is numForm:numField1 (the form id plusthe element id). JSF does this automatically unless you say prependId="false" onthe form.

    Bean Code@ManagedBean

    @SessionSco ed

    public class NumberGenerator implements Serializable {

    private double number = Math.random();

    private double range = 1.0;

    public double getRange() {

    return(range);

    public void setRange(double range) {

    this.range = range;

    }

    public double getNumber() {

    return(number);

    }

    ublic void randomize

    Request scope (the default) would work here, but itwould be slightly inefficient since there is no need toreinstatiate the class for every request. However,since there is ersistent data we cant use a lication

    number = range * Math.random();

    }

    }19

    ,scope because it would be shared by multiple users.So, we use session scope. In general in Webapplications, session scoped data should beSerializable.

  • 8/14/2019 2009 Marty Hall

    9/39

    Results

    20

    Using prependId="false"

    Code summary

    eaUse the element id directly, not formId:elementId.

    This means that you cant re-use an id within the page.However, normal HTML programmers are already usedto using unique ids, so this is no great hindrance.

    Many people find this form slightly more convenient21

  • 8/14/2019 2009 Marty Hall

    10/39

    Facelets Code

    Random Number (with prependId="false")

    < :ou pu ex va ue= num er enera or.num er

    id="numField2"/>

    < : orm>

    22

    This example uses the same Java code (NumberGenerator) as the previous example, so the code is not repeated.

    Results

    23

  • 8/14/2019 2009 Marty Hall

    11/39

    2009 Marty Hall

    execute:Specifying Elements to

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    The execute attribute of f:ajax

    Code summary

    Idea n or space-separate st o s o e ements t at

    should be sent to the server for execution.

    h:inputText processed normally (setters, validation, etc.)

    DetailsThere are 4 special values: @this, @form, @none, @all

    @this. The element enclosing f:ajax. Default.

    @form. The h:form enclosing f:ajax. Very convenient if youhave multiple fields to send. Shown in later example.

    @none. Nothing sent. Useful if the element you renderchanges values each time you evaluate it.

    @all. All JSF UI elements on page.25

  • 8/14/2019 2009 Marty Hall

    12/39

    Facelets Code

    Random Number (with execute="someId")

    Range:

    = .

    id="rangeField"/>

    < :comman Bu on>< r >

    26

    Bean Code@ManagedBean

    @SessionSco ed

    public class NumberGenerator implements Serializable {

    private double number = Math.random();

    private double range = 1.0;

    public double getRange() {

    return(range);

    public void setRange(double range) {

    this.range = range;

    }

    public double getNumber() {

    return(number);

    }

    ublic void randomize

    This is the same bean code as in previous examples.But shown again to emphasize that setRange(corresponding to the h:inputText element specifiedwith execute will be called before randomize the

    number = range * Math.random();

    }

    }27

    action of the h:commandButton that surrounds f:ajax).

  • 8/14/2019 2009 Marty Hall

    13/39

    Results

    28

    Using execute="@form"

    Code summary

    eaSend all elements of current form to server to process.

    ,(performs validation, calls setter methods, etc.)

    DetailsConvenient if you have several input fields and dont

    want to list each one in render. Also, input fields dont

    need ex licit ids when ou use form.29

  • 8/14/2019 2009 Marty Hall

    14/39

    Facelets Code

    Bank Customer Lookup (with execute="@form")

    Customer ID:

    Password:



    30

    I didnt need to give explicit ids to the input fields. JSF generates ids automatically when no id specified.Since @form was given, JSF finds all elements in current form and sends them to server for processing.

    Bean Code@ManagedBean

    private String message = "";

    return(message);

    }

    public void setMessage(String message) {

    this.message = message;

    31

  • 8/14/2019 2009 Marty Hall

    15/39

    Bean Code (Continued)

    public String showBalance() {

    if (!password.equals("secret")) {

    message = "Incorrect password";

    } else {

    CustomerLookupService service =

    customer = service.findCustomer(customerId);

    if (customer == null) {

    message = "Unknown customer";

    } else {

    message =

    String.format("Balance for %s %s is $%,.2f",

    customer.getFirstName(),

    customer.getLastName(),

    customer.getBalance());

    }

    return(null);

    }

    }32

    The message starts off as an empty String. Once the button is pressed, showBalance changes themessage to either an error message or a string showing the balance. Then JSF replaces theh:outputText value in the DOM with the new message.

    Bean Code (Continued)public String showBalance() {

    if (!password.equals("secret")) {

    message = "Incorrect password";

    } else {

    CustomerLookupService service =

    customer = service.findCustomer(customerId);

    if (customer == null) {

    message = "Unknown customer";} else {

    message =

    String.format("Balance for %s %s is $%,.2f",

    customer.getFirstName(),

    customer.getLastName(),

    customer.getBalance());

    }

    return(null);

    }

    }33

    This is same supporting class as shown in previous section on annotations. CustomerSimpleMap is just alookup table of a few customers, and is shown in the previous section (plus is in the downloadable source code).

  • 8/14/2019 2009 Marty Hall

    16/39

  • 8/14/2019 2009 Marty Hall

    17/39

    2009 Marty Hall

    event:Specifying User Events

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    The event attribute of f:ajax

    Code summary

    Idea e name o t e ava cr pt event to respon to. ou

    dont include on, so it is mouseover, keyup, blur, etc.

    Defaults

    If unspecified, default event used. See next slide.

    High-level events JSF adds 2 extras: action & valueChange. See next slide.

    a bunch of components

    Adds Ajax behavior on default event for each wrapped component37

  • 8/14/2019 2009 Marty Hall

    18/39

    Default Events

    actionh:commandButton, h:commandLink

    Note that action is part of JSF, and not a nativeJavaScri t event name. It means button has been invokedin any way (clicking on it, ENTER if it has focus, keyboardshortcut, etc.)

    h:inputText, h:inputSecret, h:inputTextarea, all radio

    button, checkbox, & menu items (h:selectOneMenu, etc.) Again, this event is added by JSF and is not a native

    JavaScript event name. Different browsers handle

    change differently, so this unifies the behavior. Also note that it is valueChange, not valuechange. The

    native JavaScript events are all lower case (mouseover,keyup, etc.)

    38

    Example 1: Chained Combo

    IdeaUse h:selectOneMenu to make a list of US states

    When the user selects a state, a list of corresponding,

    When city selected, population of that city is displayed

    A roachState list

    (valueChange is default event)

    ty st

    Bean Make managed bean session scoped so that city entry

    gets sent to same bean that already stored state39

  • 8/14/2019 2009 Marty Hall

    19/39

    Facelets Code

    Population Lookup (with chained comboboxes)

    State:


    Cit :


    Po ulation:

    40

    Bean Code@ManagedBean

    public class LocationBean implements Serializable {

    private String state, city;

    =

    public String getState() {

    } Make city list disabled(grayed out) initially. Enableit when the state is selected.

    this.state = state;

    isCityListDisabled = false;

    41

  • 8/14/2019 2009 Marty Hall

    20/39

    Bean Code (Continued)

    public String getCity() {

    }

    this.city = city;

    }

    public boolean isCityListDisabled() {

    return(isCityListDisabled);

    Although this is called setCity, the Stringpassed to setCity and returned from getCityreally represents the population. That isbecause, for combo boxes and list boxes,JSF lets you have one value displayed to theend user and a different value passed to thesetter method. See the SelectItem array innearbyStates in upcoming slide.

    42

    Bean Code (Continued)public List getStates() {

    states.add(new SelectItem("--- Select State ---"));

    for(StateInfo stateData: StateInfo.getNearbyStates()) {

    . .

    }

    return(states);

    Put dummy value at the top of the listso that any real user selection isconsidered a change

    43

    This part uses the one-argument version of the SelectItem constructor. In JSF, that means thatthe value displayed to the end user and the value passed to the bean setter method are thesame. The upcoming city example will use two different values per entry.

  • 8/14/2019 2009 Marty Hall

    21/39

    Bean Code (Continued)

    public SelectItem[] getCities() {

    { new SelectItem("--- Choose City ---")};

    if(!isCityListDisabled && (state != null)) {

    .

    if(state.equals(stateData.getStateName())) {

    cities = stateData.getCities();

    }

    } Result of first Ajax request: i.e., valuefrom the first combo box (of states)

    return(cities);

    }

    Value is a SelectItem[] that will go inthe second combo box (of cities).

    44

    Suppporting Class (StateInfo)public class StateInfo {

    private SelectItem[] cities;

    , ...

    this.stateName = stateName;

    this.cities = cities;

    public String getStateName() {

    }Value is a SelectItem array

    return(cities);

    }45

  • 8/14/2019 2009 Marty Hall

    22/39

    Suppporting Class (StateInfo)

    private static StateInfo[] nearbyStates =

    " " ,

    new SelectItem("unknown",

    "--- Choose City ---"),

    " " " ", ,

    new SelectItem("57907", "Frederick"),

    new SelectItem("57698", "Gaithersburg"),

    " " " ", ,

    // other states

    };

    public static StateInfo[] getNearbyStates() {

    return(nearbyStates);

    JSF lets ou have dual-value entries in combo boxes and list boxes. The values

    }

    46

    .on the right (city names) are displayed to the end user. But if youprogrammatically ask for the selected value, you get the value on the left(corresponding populations). That is, the value on the left is passed to the beansetter method. So, when the Ajax request fires for the valueChangeevent for thesecond combo box, the population gets passed to setCity.

    Results

    47

  • 8/14/2019 2009 Marty Hall

    23/39

    Example 2: On-the-Fly

    IdeaThe user types a temperature in Fahrenheit into textfield

    As the value is being entered, the corresponding values in

    ApproachTem erature field

    ,explicitly in event

    We want to update two output fields, so list both forrender

    Bean Temp (in F) passed each time, so use request scope

    48

    Facelets Code

    On-the-Fly Temperature Converter

    Temperature in Fahrenheit:


    Temperature in Celsius:


    Temperature in Kelvin:


    49

  • 8/14/2019 2009 Marty Hall

    24/39

    Bean Code

    @ManagedBean

    private String cTemp, kTemp;

    return(cTemp);

    }

    public String getkTemp() {

    return(kTemp);

    public String getfTemp() {""

    }

    50

    Bean Code (Continued)public void setfTemp(String fTemp) {

    - -

    try {

    f = Double.parseDouble(fTemp);

    cTemp = "Invalid";

    kTemp = "Invalid";

    if (f >= -459.4) {

    double c = (f - 32)*(5.0/9.0);

    =

    cTemp = String.format("%.2f", c);

    kTemp = String.format("%.2f", k);

    }

    }51

  • 8/14/2019 2009 Marty Hall

    25/39

    Results

    52

    2009 Marty Hall

    onevent:Specifying JavaScript

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/14/2019 2009 Marty Hall

    26/39

    The onevent attribute of f:ajax

    Code summary

    Idea e name o a ava cr pt unct on to ca at var ous

    stages of the Ajax submission and response. Functionshould take one argument (e.g., function blah(data) {})

    Details on argument to JavaScript functionThe status property (e.g., data.status in example above)

    Either "begin", "complete", or "success" (in that order)

    The source property (e.g., data.source) The DOM event that tri ered the A ax re uest

    responseCode, responseText, responseXML The values in XHR object. Omitted for begin event.

    54

    Example: Showing Getting

    IdeaYou have slow server operation

    Display animated GIF (& message) when request sent

    Approach

    http://ajaxload.info/ lets you build your own

    Display image plus message in region with display: none So it is hidden initially

    When request begins, change to display: inline Use onevent handler and be in status

    When request finishes successfully, make display: none Use onevent handler and success status

    55

  • 8/14/2019 2009 Marty Hall

    27/39

    Facelets Code

    .

    This file defines the onevent handlerthat is referred to on next page.

    In this simple example, we load style sheets and JavaScript files the normal XHTML way.

    56

    However, if you have pages in several folders that use the same resources (especially withui:composition), this standard approach is inconvenient since the relative URL to the resourcescould be different for each of the pages. So, JSF 2.0 adds h:outputScript, h:outputStyleSheet,and an option for h:graphicImage. These let you load resources (scripts, style sheets, andimages) with the same syntax, regardless of where the loading page is situated in your app.These approaches will be covered in the later section on page templating.

    Facelets Code (Continued)

    =" "

    style="display: none; font-size: 60%">

    Loadin data from server...

    This s an is hidden initiall It is made visible in.the first call to the onevent handler (for the beginstatus) and hidden again in a later call to theonevent handler (for the success status).

    57

  • 8/14/2019 2009 Marty Hall

    28/39

    JavaScript Code

    function showWorkingIndicator(data) {

    showIndicatorRegion(data, " orkingIndicator");

    }

    function showIndicatorRegion(data, regionId) {

    if (data.status == "begin") {

    This is the specific function referred to in

    onevent. It is not reusable since it refers tothe specific id of the region. ExperiencedJavaScript developers could also make an

    showElement(regionId);

    } else if (data.status == "success") {

    hideElement(regionId);

    captures the id, and use that for the oneventhandler.

    This is the reusable function called above.

    }

    function showElement(id) {

    . . .

    = "inline";

    }These make the hidden region visible andinvisible. Experienced JavaScript

    developers might use a library like jQuery orProtototype and then use shortcut methods

    unc on e emen

    document.getElementById(id).style.display

    = "none";

    }58

    like $(id).show() and $(id).hide().

    Bean Code@ManagedBean

    public String showBalance() {

    try {

    .

    } catch(InterruptedException ie) {}

    return(super.showBalance());

    }

    Works the same as the previousbankin exam le exce t for the extrafive-second delay.

    59

  • 8/14/2019 2009 Marty Hall

    29/39

    Results

    60

    2009 Marty Hall

    h:out utText with A ax

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/14/2019 2009 Marty Hall

    30/39

    Main Point

    General pointNot all uses of or

    #{bean.prop} can be updated with Ajax , ,

    the places it can be used

    SpecificsYou can use to dynamically build

    content that could go inside an existing HTML element E. ., between and

    You cannot directly use to

    dynamically change attributes of HTML elements

    programming, as with the last example where we changedthe display property

    62

    #{bean.prop}

    Overview of usageCan be used to generate

    HTML content

    Com lete HTML ta s

    HTML attributes

    Examples#{someBean.someProperty}#{bean.startTag}blah, blah #{bean.endTag}

    " " .

    63

  • 8/14/2019 2009 Marty Hall

    31/39

    Overview of usageCan be used to generate

    HTML content

    Examples

    blah, blah

    Violates XML s ntax rules

    64

    Violates XML syntax rules

    65

  • 8/14/2019 2009 Marty Hall

    32/39

    Example: #{bean.prop}

    IdeaEvery time page is loaded, use different colors and

    different text for a specified region

    To generate colors

    To generate text #{textGenerator.randomText}

    Color generation cannot be ajaxified

    66

    Facelets Code

    " ".

    #{textGenerator.randomText}

    67

  • 8/14/2019 2009 Marty Hall

    33/39

    Bean Code

    @ManagedBean

    public class TextGenerator {

    private String[] colors =" " " " " " " ", , ,

    private String[] phrases =

    { "Blah, blah, blah. ",

    " ", , . ,

    "Foo, bar, baz. "

    };

    68

    Bean Code (Continued)public String getRandomColor() {

    .

    }

    int numPhrases = 1+ RandomUtils.randomInt(20);

    String text = "";

    =

    text += RandomUtils.randomElement(phrases);

    }

    return text

    }

    69

  • 8/14/2019 2009 Marty Hall

    34/39

    Results

    70

    Example:

    IdeaEvery time page is loaded, use different colors and

    different text for a specified region

    To generate colors

    Similar for endCell to output

    To enerate text

    PointColor generation still cannot be ajaxified

    Even though colors built with h:outputText, once you add

    id, it will become a span, so cannot output a start tag71

  • 8/14/2019 2009 Marty Hall

    35/39

    Facelets Code

    =" ".

    escape="false"/>

    72

    Bean Codepublic String getStartCell() {

    String.format("",

    getRandomColor());

    }

    return("");

    }

    73

  • 8/14/2019 2009 Marty Hall

    36/39

    Results

    74

    Example: Ajaxifying

    IdeaWhen you press the button, change the text (without

    reloading page). Color does not change until page reloads

    To generate colors

    Cannot be ajaxified, so go back to simpler approach of 1st example

    To generate text < =" ".

    id="foo"/>

    PointSome uses of #{} and

    cannot be updated with Ajax75

  • 8/14/2019 2009 Marty Hall

    37/39

    Facelets Code

    76

    Uses same bean code as firstdynamic-color example.

    Results

    77

  • 8/14/2019 2009 Marty Hall

    38/39

    2009 Marty Hall

    Wrap-Up

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Summary

    Format

    Defaults render: noneexecute: @this

    event: action for buttons and links, valueChange fortextfields, text areas, select menus, list boxes

    onevent: none

    79

  • 8/14/2019 2009 Marty Hall

    39/39

    2009 Marty Hall

    Questions?

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.