03 Managed Beans

download 03 Managed Beans

of 23

Transcript of 03 Managed Beans

  • 8/3/2019 03 Managed Beans

    1/23

    2009 Marty Hall

    JSF: Managed BeansOriginals of Slides and Source Code for Examples:

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

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

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

    2009 Marty Hall

    For live training on JSF 1.x or 2.0, please seecourses a p: courses.coreserv e s.com .Taught by the author ofCore Servlets and JSP, More

    , .venues, or customized versions can be held on-site

    at your organization.

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

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

    Courses developed and taught by Marty HallJava 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom courses.

    Courses developed and taught by coreservlets.com experts (edited by Marty)Spring, Hibernate/JPA, EJB3, Ruby/Rails

    Contact [email protected] for details

  • 8/3/2019 03 Managed Beans

    2/23

    Topics in This Section

    Using beans to represent requestparameters

    Data that came from the form submission

    Data that came from the business logic

    Outputting bean properties

    JSP 2.0 expression language

    5

    2009 Marty Hall

    Background: Beans

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

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

  • 8/3/2019 03 Managed Beans

    3/23

    What Are Beans?

    Java classes that follow certain conventions ust ave a zero-argument empty constructor

    You can satisfy this requirement either by explicitlydefining such a constructor or by omitting all constructors

    ou ave no pu c ns ance var a es e s I hope you already follow this practice and use accessor

    methods instead of allowing direct access to fields

    called getXxx and setXxx

    If class has method getTitle that returns a String, class is

    Boolean properties use isXxxinstead of getXxx

    Unlike in Struts, JSF beans need extend no special class" ",

    Beans that represent the form (form parameters, action controllermethods, event handling methods, placeholders for results data).

    7

    Why You Should Use Accessors,

    To be a bean, you cannot have public fields

    So, you should replacepublic double speed;

    wprivate double speed;

    public double getSpeed() {

    return(speed);

    }

    public void setSpeed(double newSpeed) {

    speed = newSpeed;

    }

    You should do this in allyour Java codeanyhow. Why?

    8

  • 8/3/2019 03 Managed Beans

    4/23

    Why You Should Use,

    You can put constraints on values

    public void setSpeed(double newSpeed) {if (newSpeed < 0) {

    sendErrorMessage(...);

    newSpeed = Math.abs(newSpeed);

    }

    speed = newSpeed;

    }

    If users of your class accessed the fields directly, then

    they would each be responsible for checking constraints.

    9

    Why You Should Use,

    You can change your internalrepresentation without changing interface

    // Now using metric units (kph, not mph)

    public void setSpeed(double newSpeed) {

    =

    }

    u c vo se pee n ou e new pee

    speedInKPH = newSpeed;

    }

    10

  • 8/3/2019 03 Managed Beans

    5/23

    Why You Should Use,

    You can perform arbitrary side effects

    public double setSpeed(double newSpeed) {speed = newSpeed;

    updateSpeedometerDisplay();

    }

    If users of your class accessed the fields directly, thenthey would each be responsible for executing side effects.

    inconsistent from actual values.

    11

    Beans Should Be Serializable-

    Some servers support distributed Webapp ca ons Load balancing used to send different requests to different

    machines. Sessions should still work even if different hosts are hit.

    Some servers suport persistent sessions Session data written to disk and reloaded when server is restarted

    (as long as browser stays open). Tomcat 5 and 6 support this

    To support both, beans that will be session-scoped. .

    There are no methods in this interface; it is just a flag:public class MyBean implements Serializable

    ...}

    Builtin classes like String and ArrayList are already Serializable12

  • 8/3/2019 03 Managed Beans

    6/23

    2009 Marty Hall

    Updated Flow

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

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

    JSF Flow of Control (Updated)faces-config.xml- beans declared in managed-bean section

    Blah.jsp(Runs bean getter methods)

    -

    declared in navigation-rule section

    submit form

    Instantiate return ChooseRun Action forward result1.jsp

    Run SetterMethods

    Business

    Logic

    results

    POST request Blah.faces Bean condition JSPController Method result2.jsp

    ...

    resultN.jsp(Use h:outputText

    to display bean

    Store results of business

    logic in bean

    propert es)

    14

  • 8/3/2019 03 Managed Beans

    7/23

    JSF Flow of Control (Simplified)

    A form is displayed v

    Bean instantiated. If bean getter methods return non-empty,

    values filled in textfield The form is submitted to itself r g na an ACTION are ttp: a . aces

    A bean is instantiated

    Listed in the managed-beans section of faces-config.xml e se er me o s g ven n : npu ex e c. are execu e

    Values passed to setter methods are the values in textfieldswhen form is submitted

    The action controller method is invoked Listed in the action attribute of h:commandButton

    The action method returns a condition A string that matches from-outcome in the navigation rules in

    aces-con g.xm A results page is displayed

    Page uses h:outputText to output bean properties15

    Assumes bean is

    request-scoped

    Steps in Using JSF

    1) Create a beanA) Properties for form data

    B) Action controller method

    C) Placeholders for results data

    2) Create an input formA) Input fields refer to bean properties

    3) Edit faces-config.xmlA) Declare the bean

    B) Specify navigation rules

    4) Create results pages Out ut form data and results data with h:out utText

    5) Prevent direct access to JSP pages Use a filter that redirects blah.jsp to blah.faces

    16

  • 8/3/2019 03 Managed Beans

    8/23

    2009 Marty Hall

    Example

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

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

    Example: Using Beans

    Original URL: ttp: ostname s - eans reg ster. aces

    When form submitted, three possible results Error messa e re ille al email address Error message re illegal password Success

    Action controller obtains request data from within bean Output pages access bean properties

    a n po n s Defining a bean with properties for the form data Declarin beans in faces-confi .xml Outputting bean properties

    18

  • 8/3/2019 03 Managed Beans

    9/23

    Main Points of This Example

    Add two new sections to the beans Placeholders for results data (Still have action controller method as before)

    public class MyBean {

    public String getCustomerId() {}

    ublic void setCustomerId Strin id

    Assume textfield refers to

    customerId property.

    public String doBusinessLogic() {}

    public String getBalance() {}

    }Assume balance is calculated

    b business lo ic based on the

    Use h:inputText to associate textfield with property

    customer id.

    Use h:outputText to output bean properties

    19

    Step 1: Create a Bean

    (A) Properties for form data a r o getter setter met o s or eac request parameter

    If input form says value="#{name.foo}", then beanshould have getFoo and setFoo methods.

    Bean instantiated (assuming request scope) Getter methods called (e.g., getFoo in above example) ,

    is placed into textfield I.e., textfields are prepopulated with bean default values

    When form submitted A new copy of the bean is instantiated

    (assuming request scope)

    Values from textfields passed to setter methods . .,

    Strings converted to other types as with jsp:setProperty Form redisplayed if there are errors: see validation section

    20

  • 8/3/2019 03 Managed Beans

    10/23

    Step 1: Create a Bean

    (B) Action controller method Method can directly access bean properties

    Since controller is inside same class that stores therequest parameters erent rom truts, w ere one o ect stores t e request ata t e

    form bean that extends ActionForm) and a different object has thecontroller (the class that extends Action and has execute)

    Method also invokes business lo ic takes results andstores them in placeholders reserved for output values

    (C) Additional properties for output values e n y e ac on con ro er me o

    21

    Step 1: Example Code(1A) Form data

    public class RegistrationBean implements Serializable {private String email = "user@host";private String password = "";

    public String getEmail() {return(email);

    }

    If you expect to ever

    make bean session-scoped

    public void setEmail(String email) {this.email = email;

    }

    public String getPassword() {return(password);

    }

    this.password = password;}

    22

  • 8/3/2019 03 Managed Beans

    11/23

    Step 1: Example Code

    (1B) Action controller method

    public String register() {

    if ((email == null) ||(email.trim().len th() < 3) ||

    (email.indexOf("@") == -1)) {

    suggestion = SuggestionUtils.getSuggestionBean();

    return("bad-address");

    } else if ((password == null) ||

    (password.trim().length() < 6)) {

    suggestion = SuggestionUtils.getSuggestionBean();

    " - "

    } else {

    return("success");

    }

    }

    23

    Step 1: Example Code

    (1C) Placeholder for storing results Note that action controller method called business logic and placed

    the result in this placeholder

    private SuggestionBean suggestion;

    return(suggestion);

    }

    24

  • 8/3/2019 03 Managed Beans

    12/23

    Step 1: Example Code

    package coreservlets;import java.io.*;

    public class SuggestionBean implements Serializable {private String email;rivate Strin assword

    public SuggestionBean(String email, String password) {this.email = email;

    .}

    public String getEmail() {return(ema );

    }

    public String getPassword() {return(password);

    }}

    25

    Step 1: Example Code

    package coreservlets;

    public class SuggestionUtils {private static String[] suggestedAddresses =

    { "[email protected]"," ". ,"[email protected]","[email protected]" };

    private static String chars ="abcdefghijklmnopqrstuvwxyz0123456789#@$%^&*?!";

    public static SuggestionBean getSuggestionBean() {

    String password = randomString(chars, 8);return(new SuggestionBean(address, password));

    }...

    }

    26

  • 8/3/2019 03 Managed Beans

    13/23

    Step 2: Create Input Form

    Similar to previous example, except : npu a ags g ven a va ue a r u e en y ng

    the corresponding bean property Example code

    Email address:


    asswor :


    .

    27

    Step 2: Result

    File is tomcat_dir/webapps/jsf-beans/register.jsp

    s ttp:// oca ost/ s - eans/reg ster. aces

    The user@host value comes from the bean

    28

  • 8/3/2019 03 Managed Beans

    14/23

    Step 3: Edit faces-config.xml

    (A) Declare bean

    registrationBean

    coreservlets.RegistrationBean

    request

    29

    Step 3: Edit faces-config.xml

    (B) Define navigation rules

    /register.jsp

    bad-address

    /WEB-INF/results/bad-address. s

    bad-password

    WEB-INF results bad- assword. s < to-view-id>

    success

    - - - . - -

    30

  • 8/3/2019 03 Managed Beans

    15/23

    Step 4: Create Results Pages

    Use h:outputText to access bean properties

    31

    Step 4: Create Results Pages /jsf-beans/WEB-INF/results/bad-address.jsp

    < >< =" "> < >< >

    The address

    "< =" " >".

    is not of the form username@hostname (e.g.,

    ).

    Please try again.

    32

  • 8/3/2019 03 Managed Beans

    16/23

    Step 4: Example Result for Bad

    Input

    33

    Step 4: Example Result for Bad

    Output

    34

  • 8/3/2019 03 Managed Beans

    17/23

    Step 4: Create Results Pages

    /jsf-beans/WEB-INF/results/bad-password.jsp

    Illegal Password

    The password""s oo s or ; mus con a n a eas s x c arac ers.Here is a possible password:.

    Please try again.< f:view>35

    Step 6: Example Result for Bad

    Input

    36

  • 8/3/2019 03 Managed Beans

    18/23

    Step 4: Example Result for Bad

    Output

    37

    Step 4: Create Results Pages

    /jsf-beans/WEB-INF/results/success.jsp

    SuccessYou have registered successfully.Email Address:

    Password:

    38

  • 8/3/2019 03 Managed Beans

    19/23

    Step 6: Example Result for

    Input

    39

    Step 6: Example Result for

    Output

    40

  • 8/3/2019 03 Managed Beans

    20/23

    Step 5: Prevent Direct Access

    Use filter that captures url-pattern *.jsp No changes from previous example

    41

    Alternative Approaches

    Preview: using the JSP 2.0 EL output pages on y sp ay ean propert es rat er t an

    manipulating a form or using form elements): Why bother with f:view and associated taglib declaration? y use :ou pu ex an assoc a e ag ec ara on

    when the JSP 2.0 EL is simpler?

    If you use the JSP 2.0 EL, you must:. . ., ,

    Use the JSP 2.0 declaration for web.xml (see later section)

    Pros of sticking with JSF ou m g use orm e emen s or or ren erers or

    custom components or other JSF stuff in the future h:outputText escapes < and > with < and >

    ros o us ng Shorter, simpler, more readable, already familiar

    42

  • 8/3/2019 03 Managed Beans

    21/23

    Using the JSP 2.0 Expression

    Standard JSF approach" " " " . .

    Success

    You have registered successfully.Email Address:

    :ou pu ex va ue= reg s ra on ean.emaPassword:

    43

    Using the JSP 2.0 Expression

    JSP 2.0 approach Omit taglib declarations and f:view tags

    Shorten expression that outputs bean properties

    Success

    .

    Email Address: ${registrationBean.email}

    Password: ${registrationBean.password}

    44

  • 8/3/2019 03 Managed Beans

    22/23

    Looking Ahead

    Algorithm for password length was clumsy ce to ave u t n c ec ng or text e engt s

    Already supported in JSF See validation section

    Algorithm for checking legal emailaddresses was primitive and easily fooled Supported in MyFaces via Tomahawk extensions

    See section on MyFaces extensions

    o passwor an ema were wrong,

    only one was reported Better to redisplay form and say what was wrong

    See section on validation45

    Summary

    Create a bean roper es or eac reques parame er Action controller method Placeholders to hold results objects

    Refer to bean properties in input form

    - Use managed-bean declaration Bean lifecycle (assuming request scope)

    Getter methods called for initial textfield values

    Instantiated again when form submitted Setter methods called for each input field Action controller method called after setter method

    Use h:outputText to output bean properties The JSP 2.0 expression language is also possible46

  • 8/3/2019 03 Managed Beans

    23/23

    2009 Marty Hall

    Questions?

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

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