SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
© 2009 Marty Hall




    JSF: Handling Events
              Originals of Slides and Source Code for Examples:
                   http://www.coreservlets.com/JSF-Tutorial/


                  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.




                                                                                                              © 2009 Marty Hall




For live training on JSF 1.x or 2.0, please see
courses at htt //
            t http://courses.coreservlets.com/.
                                     l t      /
    Taught by the author of Core Servlets and JSP, More
    Servlets and JSP and this tutorial Available at public
                 JSP,          tutorial.
     venues, or customized versions can be held on-site
                    at your organization.
    • Courses developed and taught by Marty Hall
           – Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom courses.
    • Courses developed and taught by EE Training: http://courses.coreservlets.com/
                Customized Java coreservlets.com experts (edited by Marty)
  Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
            JSP, JSF 1.x & JSF EJB3, Ruby/Rails
   Developed and taught by well-known author and developer. At public venues or onsite at your location.
                                          Contact hall@coreservlets.com for details
Topics in This Section
    • Comparing action controllers to event
      listeners
      li
    • Action listeners
    • V l change listeners
      Value h       li t
    • Using JavaScript to submit form
      –B
       Browser incompatibilities
               i      tibiliti
    • Combining action listeners and action
      controllers in the same GUI element



5




    Motivation
    • There are two varieties of user interface
      events
      – Events that start back-end processing
      – Events that affect only the format of the user interface
    • JSF categorizes code that handles these as
      action controllers and event listeners
      – Action controllers handle main form submission
         • Fire after bean has been populated (see previous section)
         • Fire after validation logic (see upcoming section)
         • Return strings that directly affect page navigation
      – Event listeners handle UI events
         • Oft fire before bean has been populated
           Often fi b f      b     h b           l t d
         • Often bypass validation logic
6
         • Never directly affect page navigation
Event Handlers vs. Ajax
    • Event handlers are one of the most
      convenient features of JSF
             i   f         f
      – Especially compared to Struts or regular MVC
    • However Ajax is often even better
      However,
      – Many situations where event handlers apply result in only
        a small number of elements changing
                                          g g
      – In that case, Ajax yields a more interactive user
        experience
         • Alth
           Although it fails i older b
                  h f il in ld browsers and if J
                                          d JavaScript i
                                                 S i t is
           disabled
      – See later lecture on Ajax4jsf


7




    JSF Flow of Control (Updated)
                                                                                                          faces-config.xml
                                                                                                           - beans declared in managed-bean section
                                                                                                           - mapping of return conditions
                                                       Blah.jsp                                              declared in navigation-rule section
                                                       (Runs bean getter methods)

                                                       Redisplay
                                                         form

                                              Do Side
                                               Effect                  Business
                                                                        Logic
                           Button or other control
                          referred to event listener
                                                                             results

                  submit form               Instantiate               Run Action              return    Choose     forward    result1.jsp
             POST request Bl h f
                        t Blah.faces           Bean                Controller Method        condition
                                                                                                diti     JSP                  result2.jsp
                                 Button referred to                     Store results of business
                                  action controller                     logic in bean                                         ...
                                            Run Setter                                                                        resultN.jsp
                                             Methods                                                                          (Use h:outputText
                                                                                                                              to display bean
                                                                                                                              properties)
                                                                                                                                      i )




8
Types of Event Listeners
    • ActionListener
      – Fired by submit buttons, image maps, and hypertext links
        with attached JavaScript
         • <h:commandButton value="..." .../>
         • <h:commandButton image="..." .../>
         • <h:commandLink .../>
      – Automatically submit the form
    • ValueChangeListener
      – Fired by combo boxes, checkboxes, radio buttons,
        textfields, and others
            fi ld     d h
         •   <h:selectOneMenu .../>
         •   <h:selectBooleanCheckbox.../>
         •   <h:selectOneRadio .../>
         •   <h:inputText .../>
9     – Do not automatically submit the form



                                                                                                 © 2009 Marty Hall




                     Action Listeners

                      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.
Using ActionListener in JSF
     • Some buttons submit the form and start
       backend
       b k d processing
                      i
       – Use <h:commandButton action="..." ...>
     • Other buttons affect only the UI
       – Use <h:commandButton actionListener="..." .../>
       – You usually want this process to occur before beans are
         populated and especially before validation occurs
          • Since forms are often incomplete when the UI is adjusted
       – U "i
         Use "immediate" to designate that listener fires before
                    di t " t d i t th t li t        fi b f
         beans are populated or validation is performed

             <h:commandButton actionListener="..."
                              immediate="true" .../>
11




     Implementing ActionListener in the
     Java Code
     • Listener is usually in the form bean class
       – But can b in separate class if you use FacesContext to
                  be i            l                   C
         get the request or session object and look up the form
         bean explicitly
     • Takes an ActionEvent as an argument
       – Void return type (not String as in action controllers)
       – ActionEvent is in javax.faces.event
                           javax faces event
       – ActionEvent has a getComponent method that lets you
         obtain the UIComponent reference
          • F
            From the UIComponent, you can get the component ID,
                 th UIC            t            t th      t ID
            renderer, and other low-level information
       – Sample code
          public void someMethod(ActionEvent event) {
            doSomeSideEffects();
          }
12
Example: Letting the User Disable
     Certain UI Controls
     • Every UI control has a “disabled” property
       that is false by default
        h i f l b d f l
     • Use button with attached ActionListener to
       disable or reenable certain controls
     • Specific example
       – Collect name and job title to display a sample resume
       – Create comboboxes that let user select foreground and
         background colors
           <h:selectOneMenu value="..." disabled="..." ...>
             <f:selectItems value="..."/>
           </h:selectOneMenu>
           • Value for f:selectItems should be a SelectItem array
       – Have button that disables or reenables the comboboxes
13




     Steps in Using JSF
     1) Create a bean
       A) Properties for form data
       B) Action controller and event listener methods
       C) Placeholders for results data
     2) Create an input form
       A) Input fields refer to bean properties
       B) Button specifies action controller method that will return condition
       C) Button or other GUI control specifies event listener method
     3) Edit faces-config.xml
       A) Declare the bean
       B) S if navigation rules
          Specify    i ti   l
     4) Create results pages
       – Output form data and results data with h:outputText
     5) P
        Prevent di
                direct access to JSP pages
       – Use a filter that redirects blah.jsp to blah.faces
14
Step 1: Create Bean
     • (A) Properties for form data
     p
     package coreservlets;
          g              ;
     import javax.faces.model.*;
     import javax.faces.event.*;
     public class ResumeBean implements Serializable {
       ...
       private String fgColor = "BLACK";
       private String bgColor = "WHITE";
       private SelectItem[] availableColorNames =
         { new SelectItem("BLACK"),
               SelectItem( BLACK ),
           new SelectItem("WHITE"),
           new SelectItem("SILVER"),
           new SelectItem("RED"),
           new SelectItem("GREEN"),
           new S l tIt ("BLUE") }
               SelectItem("BLUE") };
       public String getFgColor() { return(fgColor); }
       public void setFgColor(String fgColor) {
         this.fgColor = fgColor;
       } ...

15     public SelectItem[] getAvailableColors() {...}




      Step 1: Create Bean
     • (A) Properties for form data
       ...
       private String name = "";
       private String jobTitle = "";
       ...
       public String getName() { return(name); }

       public void setName(String name) {
         this.name = name;
       }

       public St i
         bli String getJobTitle() { return(jobTitle); }
                      tJ bTitl ()     t   (j bTitl )

       public void setJobTitle(String jobTitle) {
         this.jobTitle = j
              j          jobTitle;
                                 ;
       }

16
Step 1: Create Bean
     • (B) Event listener and action controller methods

       public boolean isColorSupported() {
         return(isColorSupported);
       }

       public void toggleColorSupport(ActionEvent event) {
         isColorSupported = !isColorSupported;
       }
                                                                 Action listener

       public String showPreview() {            Action controller
         if (isColorSupported && fgColor.equals(bgColor)) {
           return("same-color");
         } else {
           return("success");
           ret rn("s ccess")
         }
       }
17




      Step 2: Create Input Form
     • New features
        – Use h:selectOneMenu to create combobox
        – Use f:selectItems to populate list
        – Use h:commandButton
           • With actionListener and immediate
              – Designates event listener code to fire when button clicked
        – Change the label (value) of the button depending on what
          the button will do
           • In this case, button is a toggle
     • Example code
       <h:commandButton
           value="#{someBean.buttonLabel}"
             l   "#{    B     b tt L b l}"
           actionListener="#{someBean.doSideEffect}"
           immediate="true"/>
18
Step 2: Create Input Form
     • (A) Input fields
     <h:form>
       ...
       Foreground color:
       <h:selectOneMenu value="#{resumeBean.fgColor}"
                         disabled="#{!resumeBean.colorSupported}">
                         di bl d "#{!       B      l S      t d}">
         <f:selectItems value="#{resumeBean.availableColors}"/>
       </h:selectOneMenu>
       <BR>
       Background color:
       <h:selectOneMenu value="#{resumeBean.bgColor}"
                         disabled="#{!resumeBean.colorSupported}">
         <f:selectItems value="#{resumeBean.availableColors}"/>
                                #{                          } /
       </h:selectOneMenu><BR>
       ...
       Name:
       <h:inputText value="#{resumeBean name}"/><BR>
                    value= #{resumeBean.name} /><BR>
       Job Title:
       <h:inputText value="#{resumeBean.jobTitle}"/><P>
19
     </h:form>




      Step 2: Create Input Form
     • (B) Action controller
        – Even when you have event listeners, you almost always
          have action controllers
           • As before these invoke business logic and participate in
                before,
             navigation flow (via navigation-rule entries in config file)
           • Setter methods and validation fire before action controller

     <h:form>
       ...
       <h:commandButton value="Show P
       <h       dB tt     l   "Sh   Preview"
                                        i "
                        action="#{resumeBean.showPreview}"/>
     </h:form>



20
Step 2: Create Input Form
     • (C) Event listener
        – Event listeners perform side effects, and then form is
          redisplayed
           • They do not usually invoke normal business logic setter
                                                           logic,
             methods are not usually fired, and they never participate in
             navigation flow (navigation-rule entries do not apply)
           • You usually use "immediate" to say that setter methods do
                               immediate
             not fire
     <h:form>
       ...
       <h:commandButton
           value="#{resumeBean.colorSupportLabel}"
           actionListener="#{resumeBean.toggleColorSupport}"
           immediate="true"/>
     </h:form>
21




      Steps 2-4: Initial Result
     • File is tomcat_dir/webapps/jobs/customize.jsp
     • URL i h
             is http://localhost/jobs/customize.faces
                     //l   lh   /j b /      i f




22
Step 2: Result of Clicking Button
      (Independent of Action Controller)




23




      Step 3: Edit faces-config.xml
     • (A) Declaring bean
        – Note session scope so changes persist
     …
     <faces-config>
                 g
       <managed-bean>
         <managed-bean-name>resumeBean</managed-bean-name>
         <managed-bean-class>
           coreservlets.ResumeBean
         </managed-bean-class>
         <managed-bean-scope>session</managed-bean-scope>
       </managed-bean>
     …
     </faces-config>



24
Step 3: Edit faces-config.xml
     • (B) Specifying navigation rules

     …
     <faces-config>
                 g
       …
       <navigation-rule>
         <from-view-id>/customize.jsp</from-view-id>
         <navigation-case>
         <   i ti         >
           <from-outcome>same-color</from-outcome>
           <to-view-id>/WEB-INF/results/same-color.jsp</to-view-id>
         </navigation-case>
         <navigation-case>
           <from-outcome>success</from-outcome>
           <to-view-id>/WEB-INF/results/show-preview.jsp</to-view-id>
         </navigation case>
         </navigation-case>
       </navigation-rule>
     </faces-config>
25




      Step 4: Create Results Pages
     • WEB-INF/results/same-color.jsp
        – R lt pages apply to action controller, not event listener
          Results       l t     ti      t ll       t     t li t

     <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
     <%@ taglib uri="http://java sun com/jsf/html" prefix="h" %>
                uri="http://java.sun.com/jsf/html"
     <f:view>
     <!DOCTYPE …>
     <HTML>
     …
     You chose
     "<h:outputText value="#{resumeBean.fgColor}"/>"
     as both the foreground and background color.
                     g              g
     <P>
     You don't deserve to get a job, but I suppose
     we will let you <A HREF="customize.faces">try again</A>.
     …
     </HTML>
     </f:view>
26
Step 4: Create Results Pages
     • WEB-INF/results/show-preview.jsp
     <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
                           //             /  /
     <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
     <f:view>
     <!DOCTYPE …>
     <HTML>
     …
     <BODY TEXT="<h:outputText value="#{resumeBean.fgColor}"/>"
            BGCOLOR="<h:outputText value="#{resumeBean.bgColor}"/>">
             GCO O     :output e t a ue #{ esu e ea .bgCo o } /
     <H1 ALIGN="CENTER">
     <h:outputText value="#{resumeBean.name}"/><BR>
     <SMALL><h:outputText value="#{resumeBean.jobTitle}"/>
     </SMALL></H1>
     Experienced <h:outputText value="#{resumeBean.jobTitle}"/>
     seeks challenging position doing something.
     <H2>Employment History</H2>
     Blah, blah, bl h bl h Yadda, yadda, yadda, yadda.
     Bl h bl h blah, blah. Y dd        dd      dd    dd
     …
     </HTML>
27   </f:view>




      Step 4: Example Result for
      Same Colors




28
Step 4: Example Result for
     Different Colors




29




     Step 5: Prevent Direct Access
     to JSP Pages
     • Use filter that captures url-pattern *.jsp
       – No changes from previous examples




30
© 2009 Marty Hall




        Value Change Listeners

                       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.




     Using ValueChangeListener in JSP
     • ActionListener was attached to button
       –F
        Form was automatically submitted when clicked
                   t   ti ll     b itt d h     li k d
     • ValueChangeListener is attached to
       combobox, listbox, radio button, checkbox,
                   ,    ,             ,         ,
       textfield, etc.
       – Form not automatically submitted
       – Need to add JavaScript to submit the form
          onclick="submit()" or onchange="submit()"
       – Event incompatibility between Firefox and IE
          • Firefox Netscape and Opera fire the onchange events
            Firefox, Netscape,
            when the combobox selection changes, radio button is
            selected, or checkbox is checked/unchecked
          • Internet Explorer fires event after selection changes, but
            only when another GUI control receives the input focus
               l h         th           t l       i    th i   tf
                 – Older IE versions behave differently! Test on multiple browsers!

32
Implementing ValueChangeListener
     in Java Code
     • Listener is usually in the form bean class
       – As discussed previously
     • Takes a ValueChangeEvent as an argument
       – Useful ValueChangeEvent methods
          • getComponent (as mentioned for ActionEvent)
          • getOldValue (previous value of GUI element)
          • getNewValue (
              tN V l (current value of GUI element)
                                t l      f      l    t)
             – Needed since bean has probably not been populated
             – Value for checkbox is of type Boolean
             – Value for radio button or textfield corresponds to request parameter
       – Sample code
          public void someMethod(ValueChangeEvent event) {
            boolean flag =
                       g
              ((Boolean)event.getNewValue()).booleanValue();
            takeActionBasedOn(flag);
33
          }




     Example: Changing the Colors
     Listed for FG and BG Colors
     • h:selectOneMenu uses f:selectItems to get
       list f
       li of combobox entries
                  b b        i
     • Use checkbox to invoke
       ValueChangeListener
     • Have listener toggle the definition of the
       lists
       – Color names
       – RGB values




34
Steps in Using JSF
     1) Create a bean
       A) Properties for form data
       B) Action controller and event listener methods
       C) Placeholders for results data
     2) Create an input form
       A) Input fields refer to bean properties
       B) Button specifies action controller method that will return condition
       C) Button or other GUI control specifies event listener method
     3) Edit faces-config.xml
       A) Declare the bean
       B) S if navigation rules
          Specify    i ti   l
     4) Create results pages
       – Output form data and results data with h:outputText
     5) P
        Prevent di
                direct access to JSP pages
       – Use a filter that redirects blah.jsp to blah.faces
35




     Step 1: Create Bean (ResumeBean)
     • (A) Code for color choices
      p
      private SelectItem[] availableColorNames =
                        []
        { new SelectItem("BLACK"),
          new SelectItem("WHITE"),
          new SelectItem("SILVER"),
          new SelectItem("RED"),
          new SelectItem("GREEN")
              SelectItem("GREEN"),
          new SelectItem("BLUE") };
      private SelectItem[] availableColorValues =
          { new SelectItem("#000000"),
            new SelectItem( #FFFFFF ),
                SelectItem("#FFFFFF"),
            new SelectItem("#C0C0C0"),
            new SelectItem("#FF0000"),
            new SelectItem("#00FF00"),
            new SelectItem("#0000FF") };
      private b l
        i t boolean i U i C l N
                      isUsingColorNames = t
                                          true;
      public SelectItem[] getAvailableColors() {
        if (isUsingColorNames) {
          return(availableColorNames);
        } else {
          return(availableColorValues);
        }
36    }
Step 1: Create Bean
     • (B) Event listener
        – When checkbox selected, change color choices to return
          RGB values instead of color names
        – Action controller, action listener, and other form data
                 controller         listener
          shown in previous example
     public void changeColorMode(ValueChangeEvent event) {
       boolean flag =
         ((Boolean)event.getNewValue()).booleanValue();
       setUsingColorNames(!flag);
     }




37




      Step 2: Create Input Form
      (and Specify Event Listener)
     • New features
        – Use h:selectBooleanCheckbox to create checkbox
        – Use valueChangeListener to designate event listener code
        – Use onclick to automatically submit form when checkbox
          value changes
           • You could use onchange on Firefox, but with onchange in
             Internet Explorer, input focus also has to move
             I t    tE l        i   tf       l h t
     • Example code
     <h:selectBooleanCheckbox
         valueChangeListener="#{resumeBean.changeColorMode}"
         onclick="submit()"
         immediate="true"/>       Client-side JavaScript code


38
Step 2: Initial Result
     • File is tomcat_dir/webapps/jobs/customize.jsp
     • URL i h
             is http://localhost/jobs/customize.faces
                     //l   lh   /j b /      i f




39




     Steps 2: Result of Changing Checkbox
     (Independent of Action Controller)




40
Steps 3-5
     • Unchanged from previous slides




41




                                                                                                  © 2009 Marty Hall




                  Combining Action
                 Listeners and Action
                 Controllers for Same
                        Button
                       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.
Motivation
     • Usually, action listeners and action
       controllers are attached to different buttons
             ll             h d    diff      b
     • Sometimes, you are forced to use both
       – Li
         Listeners have access to low-level details of GUI object
                   h              l   l l d il f            bj
            • Renderer, client ID, etc.
            • Especially relevant when we cover custom components
     • Most common example:
       server-side image maps
       – h:commandButton with image instead of value results in
         image map
       – Actual incoming request parameter names are clientID x
                                                     clientID.x
         and clientID.y
            • Only listener can discover the client ID
43




     Example: Choosing Background
     Color from Image Map
     • Display grayscale color bar to user
     • Let them click on desired color for
       background
     • B ild corresponding RGB value
       Build           di           l
       –   Read the clientID.x value
       –   Normalize to 0-256 based on image width
                         0 256
       –   Output as hex digits into #RRGGBB string
       –   Done in action listener
     • Forward to JSP page
       – Done in action controller


44
Steps in Using JSF
     1) Create a bean
       A) Properties for form data
       B) Action controller and event listener methods
       C) Placeholders for results data
     2) Create an input form
       A) Input fields refer to bean properties
       B) Button specifies action controller method that will return condition
       C) Button or other GUI control specifies event listener method
     3) Edit faces-config.xml
       A) Declare the bean
       B) S if navigation rules
          Specify    i ti   l
     4) Create results pages
       – Output form data and results data with h:outputText
     5) P
        Prevent di
                direct access to JSP pages
       – Use a filter that redirects blah.jsp to blah.faces
45




     Step 1: Create Bean
     • (A) Form data
     package coreservlets;

     ...

     public class ColorBean {
       p
       private String bgColor = "WHITE";
                    g g                ;

       public String getBgColor() { return(bgColor); }

       public void setBgColor(String b C l ) {
         bli    id      C l (S i     bgColor)
         this.bgColor = bgColor;
       }



46
Step 1: Create Bean
     • Listener looks up x value and creates color
     public void selectGrayLevel(ActionEvent event) {
       FacesContext context = FacesContext.getCurrentInstance();
       String clientId = event.getComponent().getClientId(context);
       HttpServletRequest request =
         (HttpServletRequest)context.getExternalContext().getRequest();
         (         l        )                   l      ()           ()
       String grayLevelString = request.getParameter(clientId + ".x");
       int grayLevel = 220;
       try {
         grayLevel = Integer.parseInt(grayLevelString);
                 l                   (        l   i )
       } catch(NumberFormatException nfe) {}
       // Image is 440 pixels, so scale.
       grayLevel = (256 * grayLevel) / 440;
       String rVal = I t
       St i    V l   Integer.toString(grayLevel, 16)
                              t St i (    L   l 16);
       setBgColor("#" + rVal + rVal + rVal);
     }

     • Controller designates output page
       public String showPreview() {
         return("success");
47
       }




      Step 2: Create Input Form
     • Specify both action and actionListener
        – Listener runs first and has access to low-level internals
        – Also use h:commandButton with image instead of value
            • Results in server side image map
                         server-side
     • Code
     <h:form>
       ...
       <h:commandButton
           image="images/GrayBar.gif"
           actionListener="#{colorBean.selectGrayLevel}"
                   #{                     } /
           action="#{colorBean.showPreview}"/>
     </h:form>

48
Step 2: Result
     • File is tomcat_dir/webapps/jobs/customize-bg.jsp
     • URL i h
             is http://localhost/jobs/customize-bg.faces
                     //l   lh   /j b /      i b f




49




      Step 3: Edit faces-config.xml
     • Declaring bean
     …
     <faces-config>
       ...
       <managed-bean>
          <managed-bean-name>colorBean</managed-bean-name>
          <managed-bean-class>
            coreservlets.ColorBean
                    l      l
          </managed-bean-class>
          <managed-bean-scope>request</managed-bean-scope>
       </managed-bean>
       </       d b   >
       …
     </faces-config>



50
Step 3: Edit faces-config.xml
     • Specifying navigation rules
     …
     <faces-config>
       …
       <navigation-rule>
       <   i ti      l >
         <from-view-id>/customize-bg.jsp</from-view-id>
         <navigation-case>
           <from-outcome>success</from-outcome>
           <from outcome>success</from outcome>
           <to-view-id>
             /WEB-INF/results/show-preview2.jsp
           </to-view-id>
           </to view id>
         </navigation-case>
       </navigation-rule>
     </faces-config>


51




         Step 4: Create Results Pages
     • WEB-INF/results/show-preview2.jsp

     <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
     <%@ taglib uri="http://java.sun.com/jsf/html" p
       @   g            p //j           /j /       prefix="h" %>
     <f:view>
     <!DOCTYPE ...>
     <HTML>
     <HEAD><TITLE>Preview of Background Color</TITLE></HEAD>
     <BODY BGCOLOR="<h:outputText value="#{colorBean.bgColor}"/>">
     <H1 ALIGN="CENTER">Preview of Background Color</H1>
     Experienced employee
     seeks challenging position doing something.
     <H2>Employment History</H2>
     Blah, blah, blah, blah. Yadda, yadda, yadda, yadda.
     …
     </HTML>
     </f:view>
52
Step 4: Example Result




53




     Step 5: Prevent Direct Access
     to JSP Pages
     • Use filter that captures url-pattern *.jsp
       – No changes from previous examples




54
Summary
     • Event listeners are used to handle events that
       affect only the user interface
       – Typically fire before beans are populated and validation is
         performed
           • Use immediate="true" to designate this behavior
                 immediate= true
       – Form is redisplayed after listeners fire
           • No navigation rules apply
     • Action listeners
       – Attached to buttons, hypertext links, or image maps
       – Automatically submit the form
     • V l change li t
       Value h    listeners
       – Attached to radio buttons, comboboxes, list boxes, checkboxes,
         textfields, etc.
       – Require onclick="submit()" or onchange="submit()" to submit form
           • Test carefully on all expected browsers
55




                                                                                                   © 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.

Weitere ähnliche Inhalte

Andere mochten auch (9)

hibernate
hibernatehibernate
hibernate
 
Java_Comb
Java_CombJava_Comb
Java_Comb
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Java-Events
Java-EventsJava-Events
Java-Events
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
slides6
slides6slides6
slides6
 
javabeans
javabeansjavabeans
javabeans
 
swingbasics
swingbasicsswingbasics
swingbasics
 
servlets
servletsservlets
servlets
 

Ähnlich wie 06-Event-Handlingadvansed

J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical OverviewSvetlin Nakov
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...varunsunny21
 
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces Skills Matter
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Fahad Golra
 
Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2tahirraza
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011Arun Gupta
 
JSF and Seam
JSF and SeamJSF and Seam
JSF and Seamyuvalb
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overviewsohan1234
 
Web Applications of the future: Combining JEE6 & JavaFX
Web Applications of the future: Combining JEE6 & JavaFXWeb Applications of the future: Combining JEE6 & JavaFX
Web Applications of the future: Combining JEE6 & JavaFXPaul Bakker
 
Jsf2 composite-components
Jsf2 composite-componentsJsf2 composite-components
Jsf2 composite-componentsvinaysbk
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring applicationJayasree Perilakkalam
 

Ähnlich wie 06-Event-Handlingadvansed (20)

JSF2 and JSP
JSF2 and JSPJSF2 and JSP
JSF2 and JSP
 
Jsf Framework
Jsf FrameworkJsf Framework
Jsf Framework
 
J2 Ee Overview
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
 
Struts Action
Struts ActionStruts Action
Struts Action
 
Jsf+ejb 50
Jsf+ejb 50Jsf+ejb 50
Jsf+ejb 50
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
 
JSF 2.0 Preview
JSF 2.0 PreviewJSF 2.0 Preview
JSF 2.0 Preview
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
 
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
 
Seam Glassfish Perspective
Seam Glassfish PerspectiveSeam Glassfish Perspective
Seam Glassfish Perspective
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
 
Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2
 
Eureka moment
Eureka momentEureka moment
Eureka moment
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
JSF and Seam
JSF and SeamJSF and Seam
JSF and Seam
 
Jsf
JsfJsf
Jsf
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Web Applications of the future: Combining JEE6 & JavaFX
Web Applications of the future: Combining JEE6 & JavaFXWeb Applications of the future: Combining JEE6 & JavaFX
Web Applications of the future: Combining JEE6 & JavaFX
 
Jsf2 composite-components
Jsf2 composite-componentsJsf2 composite-components
Jsf2 composite-components
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring application
 

Mehr von Arjun Shanka

Mehr von Arjun Shanka (17)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
AWTEventModel
AWTEventModelAWTEventModel
AWTEventModel
 
javainterface
javainterfacejavainterface
javainterface
 

Kürzlich hochgeladen

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Kürzlich hochgeladen (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

06-Event-Handlingadvansed

  • 1. © 2009 Marty Hall JSF: Handling Events Originals of Slides and Source Code for Examples: http://www.coreservlets.com/JSF-Tutorial/ 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. © 2009 Marty Hall For live training on JSF 1.x or 2.0, please see courses at htt // t http://courses.coreservlets.com/. l t / Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public JSP, tutorial. venues, or customized versions can be held on-site at your organization. • Courses developed and taught by Marty Hall – Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom courses. • Courses developed and taught by EE Training: http://courses.coreservlets.com/ Customized Java coreservlets.com experts (edited by Marty) Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. JSP, JSF 1.x & JSF EJB3, Ruby/Rails Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets.com for details
  • 2. Topics in This Section • Comparing action controllers to event listeners li • Action listeners • V l change listeners Value h li t • Using JavaScript to submit form –B Browser incompatibilities i tibiliti • Combining action listeners and action controllers in the same GUI element 5 Motivation • There are two varieties of user interface events – Events that start back-end processing – Events that affect only the format of the user interface • JSF categorizes code that handles these as action controllers and event listeners – Action controllers handle main form submission • Fire after bean has been populated (see previous section) • Fire after validation logic (see upcoming section) • Return strings that directly affect page navigation – Event listeners handle UI events • Oft fire before bean has been populated Often fi b f b h b l t d • Often bypass validation logic 6 • Never directly affect page navigation
  • 3. Event Handlers vs. Ajax • Event handlers are one of the most convenient features of JSF i f f – Especially compared to Struts or regular MVC • However Ajax is often even better However, – Many situations where event handlers apply result in only a small number of elements changing g g – In that case, Ajax yields a more interactive user experience • Alth Although it fails i older b h f il in ld browsers and if J d JavaScript i S i t is disabled – See later lecture on Ajax4jsf 7 JSF Flow of Control (Updated) faces-config.xml - beans declared in managed-bean section - mapping of return conditions Blah.jsp declared in navigation-rule section (Runs bean getter methods) Redisplay form Do Side Effect Business Logic Button or other control referred to event listener results submit form Instantiate Run Action return Choose forward result1.jsp POST request Bl h f t Blah.faces Bean Controller Method condition diti JSP result2.jsp Button referred to Store results of business action controller logic in bean ... Run Setter resultN.jsp Methods (Use h:outputText to display bean properties) i ) 8
  • 4. Types of Event Listeners • ActionListener – Fired by submit buttons, image maps, and hypertext links with attached JavaScript • <h:commandButton value="..." .../> • <h:commandButton image="..." .../> • <h:commandLink .../> – Automatically submit the form • ValueChangeListener – Fired by combo boxes, checkboxes, radio buttons, textfields, and others fi ld d h • <h:selectOneMenu .../> • <h:selectBooleanCheckbox.../> • <h:selectOneRadio .../> • <h:inputText .../> 9 – Do not automatically submit the form © 2009 Marty Hall Action Listeners 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.
  • 5. Using ActionListener in JSF • Some buttons submit the form and start backend b k d processing i – Use <h:commandButton action="..." ...> • Other buttons affect only the UI – Use <h:commandButton actionListener="..." .../> – You usually want this process to occur before beans are populated and especially before validation occurs • Since forms are often incomplete when the UI is adjusted – U "i Use "immediate" to designate that listener fires before di t " t d i t th t li t fi b f beans are populated or validation is performed <h:commandButton actionListener="..." immediate="true" .../> 11 Implementing ActionListener in the Java Code • Listener is usually in the form bean class – But can b in separate class if you use FacesContext to be i l C get the request or session object and look up the form bean explicitly • Takes an ActionEvent as an argument – Void return type (not String as in action controllers) – ActionEvent is in javax.faces.event javax faces event – ActionEvent has a getComponent method that lets you obtain the UIComponent reference • F From the UIComponent, you can get the component ID, th UIC t t th t ID renderer, and other low-level information – Sample code public void someMethod(ActionEvent event) { doSomeSideEffects(); } 12
  • 6. Example: Letting the User Disable Certain UI Controls • Every UI control has a “disabled” property that is false by default h i f l b d f l • Use button with attached ActionListener to disable or reenable certain controls • Specific example – Collect name and job title to display a sample resume – Create comboboxes that let user select foreground and background colors <h:selectOneMenu value="..." disabled="..." ...> <f:selectItems value="..."/> </h:selectOneMenu> • Value for f:selectItems should be a SelectItem array – Have button that disables or reenables the comboboxes 13 Steps in Using JSF 1) Create a bean A) Properties for form data B) Action controller and event listener methods C) Placeholders for results data 2) Create an input form A) Input fields refer to bean properties B) Button specifies action controller method that will return condition C) Button or other GUI control specifies event listener method 3) Edit faces-config.xml A) Declare the bean B) S if navigation rules Specify i ti l 4) Create results pages – Output form data and results data with h:outputText 5) P Prevent di direct access to JSP pages – Use a filter that redirects blah.jsp to blah.faces 14
  • 7. Step 1: Create Bean • (A) Properties for form data p package coreservlets; g ; import javax.faces.model.*; import javax.faces.event.*; public class ResumeBean implements Serializable { ... private String fgColor = "BLACK"; private String bgColor = "WHITE"; private SelectItem[] availableColorNames = { new SelectItem("BLACK"), SelectItem( BLACK ), new SelectItem("WHITE"), new SelectItem("SILVER"), new SelectItem("RED"), new SelectItem("GREEN"), new S l tIt ("BLUE") } SelectItem("BLUE") }; public String getFgColor() { return(fgColor); } public void setFgColor(String fgColor) { this.fgColor = fgColor; } ... 15 public SelectItem[] getAvailableColors() {...} Step 1: Create Bean • (A) Properties for form data ... private String name = ""; private String jobTitle = ""; ... public String getName() { return(name); } public void setName(String name) { this.name = name; } public St i bli String getJobTitle() { return(jobTitle); } tJ bTitl () t (j bTitl ) public void setJobTitle(String jobTitle) { this.jobTitle = j j jobTitle; ; } 16
  • 8. Step 1: Create Bean • (B) Event listener and action controller methods public boolean isColorSupported() { return(isColorSupported); } public void toggleColorSupport(ActionEvent event) { isColorSupported = !isColorSupported; } Action listener public String showPreview() { Action controller if (isColorSupported && fgColor.equals(bgColor)) { return("same-color"); } else { return("success"); ret rn("s ccess") } } 17 Step 2: Create Input Form • New features – Use h:selectOneMenu to create combobox – Use f:selectItems to populate list – Use h:commandButton • With actionListener and immediate – Designates event listener code to fire when button clicked – Change the label (value) of the button depending on what the button will do • In this case, button is a toggle • Example code <h:commandButton value="#{someBean.buttonLabel}" l "#{ B b tt L b l}" actionListener="#{someBean.doSideEffect}" immediate="true"/> 18
  • 9. Step 2: Create Input Form • (A) Input fields <h:form> ... Foreground color: <h:selectOneMenu value="#{resumeBean.fgColor}" disabled="#{!resumeBean.colorSupported}"> di bl d "#{! B l S t d}"> <f:selectItems value="#{resumeBean.availableColors}"/> </h:selectOneMenu> <BR> Background color: <h:selectOneMenu value="#{resumeBean.bgColor}" disabled="#{!resumeBean.colorSupported}"> <f:selectItems value="#{resumeBean.availableColors}"/> #{ } / </h:selectOneMenu><BR> ... Name: <h:inputText value="#{resumeBean name}"/><BR> value= #{resumeBean.name} /><BR> Job Title: <h:inputText value="#{resumeBean.jobTitle}"/><P> 19 </h:form> Step 2: Create Input Form • (B) Action controller – Even when you have event listeners, you almost always have action controllers • As before these invoke business logic and participate in before, navigation flow (via navigation-rule entries in config file) • Setter methods and validation fire before action controller <h:form> ... <h:commandButton value="Show P <h dB tt l "Sh Preview" i " action="#{resumeBean.showPreview}"/> </h:form> 20
  • 10. Step 2: Create Input Form • (C) Event listener – Event listeners perform side effects, and then form is redisplayed • They do not usually invoke normal business logic setter logic, methods are not usually fired, and they never participate in navigation flow (navigation-rule entries do not apply) • You usually use "immediate" to say that setter methods do immediate not fire <h:form> ... <h:commandButton value="#{resumeBean.colorSupportLabel}" actionListener="#{resumeBean.toggleColorSupport}" immediate="true"/> </h:form> 21 Steps 2-4: Initial Result • File is tomcat_dir/webapps/jobs/customize.jsp • URL i h is http://localhost/jobs/customize.faces //l lh /j b / i f 22
  • 11. Step 2: Result of Clicking Button (Independent of Action Controller) 23 Step 3: Edit faces-config.xml • (A) Declaring bean – Note session scope so changes persist … <faces-config> g <managed-bean> <managed-bean-name>resumeBean</managed-bean-name> <managed-bean-class> coreservlets.ResumeBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> … </faces-config> 24
  • 12. Step 3: Edit faces-config.xml • (B) Specifying navigation rules … <faces-config> g … <navigation-rule> <from-view-id>/customize.jsp</from-view-id> <navigation-case> < i ti > <from-outcome>same-color</from-outcome> <to-view-id>/WEB-INF/results/same-color.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/WEB-INF/results/show-preview.jsp</to-view-id> </navigation case> </navigation-case> </navigation-rule> </faces-config> 25 Step 4: Create Results Pages • WEB-INF/results/same-color.jsp – R lt pages apply to action controller, not event listener Results l t ti t ll t t li t <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java sun com/jsf/html" prefix="h" %> uri="http://java.sun.com/jsf/html" <f:view> <!DOCTYPE …> <HTML> … You chose "<h:outputText value="#{resumeBean.fgColor}"/>" as both the foreground and background color. g g <P> You don't deserve to get a job, but I suppose we will let you <A HREF="customize.faces">try again</A>. … </HTML> </f:view> 26
  • 13. Step 4: Create Results Pages • WEB-INF/results/show-preview.jsp <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> // / / <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <!DOCTYPE …> <HTML> … <BODY TEXT="<h:outputText value="#{resumeBean.fgColor}"/>" BGCOLOR="<h:outputText value="#{resumeBean.bgColor}"/>"> GCO O :output e t a ue #{ esu e ea .bgCo o } / <H1 ALIGN="CENTER"> <h:outputText value="#{resumeBean.name}"/><BR> <SMALL><h:outputText value="#{resumeBean.jobTitle}"/> </SMALL></H1> Experienced <h:outputText value="#{resumeBean.jobTitle}"/> seeks challenging position doing something. <H2>Employment History</H2> Blah, blah, bl h bl h Yadda, yadda, yadda, yadda. Bl h bl h blah, blah. Y dd dd dd dd … </HTML> 27 </f:view> Step 4: Example Result for Same Colors 28
  • 14. Step 4: Example Result for Different Colors 29 Step 5: Prevent Direct Access to JSP Pages • Use filter that captures url-pattern *.jsp – No changes from previous examples 30
  • 15. © 2009 Marty Hall Value Change Listeners 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. Using ValueChangeListener in JSP • ActionListener was attached to button –F Form was automatically submitted when clicked t ti ll b itt d h li k d • ValueChangeListener is attached to combobox, listbox, radio button, checkbox, , , , , textfield, etc. – Form not automatically submitted – Need to add JavaScript to submit the form onclick="submit()" or onchange="submit()" – Event incompatibility between Firefox and IE • Firefox Netscape and Opera fire the onchange events Firefox, Netscape, when the combobox selection changes, radio button is selected, or checkbox is checked/unchecked • Internet Explorer fires event after selection changes, but only when another GUI control receives the input focus l h th t l i th i tf – Older IE versions behave differently! Test on multiple browsers! 32
  • 16. Implementing ValueChangeListener in Java Code • Listener is usually in the form bean class – As discussed previously • Takes a ValueChangeEvent as an argument – Useful ValueChangeEvent methods • getComponent (as mentioned for ActionEvent) • getOldValue (previous value of GUI element) • getNewValue ( tN V l (current value of GUI element) t l f l t) – Needed since bean has probably not been populated – Value for checkbox is of type Boolean – Value for radio button or textfield corresponds to request parameter – Sample code public void someMethod(ValueChangeEvent event) { boolean flag = g ((Boolean)event.getNewValue()).booleanValue(); takeActionBasedOn(flag); 33 } Example: Changing the Colors Listed for FG and BG Colors • h:selectOneMenu uses f:selectItems to get list f li of combobox entries b b i • Use checkbox to invoke ValueChangeListener • Have listener toggle the definition of the lists – Color names – RGB values 34
  • 17. Steps in Using JSF 1) Create a bean A) Properties for form data B) Action controller and event listener methods C) Placeholders for results data 2) Create an input form A) Input fields refer to bean properties B) Button specifies action controller method that will return condition C) Button or other GUI control specifies event listener method 3) Edit faces-config.xml A) Declare the bean B) S if navigation rules Specify i ti l 4) Create results pages – Output form data and results data with h:outputText 5) P Prevent di direct access to JSP pages – Use a filter that redirects blah.jsp to blah.faces 35 Step 1: Create Bean (ResumeBean) • (A) Code for color choices p private SelectItem[] availableColorNames = [] { new SelectItem("BLACK"), new SelectItem("WHITE"), new SelectItem("SILVER"), new SelectItem("RED"), new SelectItem("GREEN") SelectItem("GREEN"), new SelectItem("BLUE") }; private SelectItem[] availableColorValues = { new SelectItem("#000000"), new SelectItem( #FFFFFF ), SelectItem("#FFFFFF"), new SelectItem("#C0C0C0"), new SelectItem("#FF0000"), new SelectItem("#00FF00"), new SelectItem("#0000FF") }; private b l i t boolean i U i C l N isUsingColorNames = t true; public SelectItem[] getAvailableColors() { if (isUsingColorNames) { return(availableColorNames); } else { return(availableColorValues); } 36 }
  • 18. Step 1: Create Bean • (B) Event listener – When checkbox selected, change color choices to return RGB values instead of color names – Action controller, action listener, and other form data controller listener shown in previous example public void changeColorMode(ValueChangeEvent event) { boolean flag = ((Boolean)event.getNewValue()).booleanValue(); setUsingColorNames(!flag); } 37 Step 2: Create Input Form (and Specify Event Listener) • New features – Use h:selectBooleanCheckbox to create checkbox – Use valueChangeListener to designate event listener code – Use onclick to automatically submit form when checkbox value changes • You could use onchange on Firefox, but with onchange in Internet Explorer, input focus also has to move I t tE l i tf l h t • Example code <h:selectBooleanCheckbox valueChangeListener="#{resumeBean.changeColorMode}" onclick="submit()" immediate="true"/> Client-side JavaScript code 38
  • 19. Step 2: Initial Result • File is tomcat_dir/webapps/jobs/customize.jsp • URL i h is http://localhost/jobs/customize.faces //l lh /j b / i f 39 Steps 2: Result of Changing Checkbox (Independent of Action Controller) 40
  • 20. Steps 3-5 • Unchanged from previous slides 41 © 2009 Marty Hall Combining Action Listeners and Action Controllers for Same Button 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.
  • 21. Motivation • Usually, action listeners and action controllers are attached to different buttons ll h d diff b • Sometimes, you are forced to use both – Li Listeners have access to low-level details of GUI object h l l l d il f bj • Renderer, client ID, etc. • Especially relevant when we cover custom components • Most common example: server-side image maps – h:commandButton with image instead of value results in image map – Actual incoming request parameter names are clientID x clientID.x and clientID.y • Only listener can discover the client ID 43 Example: Choosing Background Color from Image Map • Display grayscale color bar to user • Let them click on desired color for background • B ild corresponding RGB value Build di l – Read the clientID.x value – Normalize to 0-256 based on image width 0 256 – Output as hex digits into #RRGGBB string – Done in action listener • Forward to JSP page – Done in action controller 44
  • 22. Steps in Using JSF 1) Create a bean A) Properties for form data B) Action controller and event listener methods C) Placeholders for results data 2) Create an input form A) Input fields refer to bean properties B) Button specifies action controller method that will return condition C) Button or other GUI control specifies event listener method 3) Edit faces-config.xml A) Declare the bean B) S if navigation rules Specify i ti l 4) Create results pages – Output form data and results data with h:outputText 5) P Prevent di direct access to JSP pages – Use a filter that redirects blah.jsp to blah.faces 45 Step 1: Create Bean • (A) Form data package coreservlets; ... public class ColorBean { p private String bgColor = "WHITE"; g g ; public String getBgColor() { return(bgColor); } public void setBgColor(String b C l ) { bli id C l (S i bgColor) this.bgColor = bgColor; } 46
  • 23. Step 1: Create Bean • Listener looks up x value and creates color public void selectGrayLevel(ActionEvent event) { FacesContext context = FacesContext.getCurrentInstance(); String clientId = event.getComponent().getClientId(context); HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest(); ( l ) l () () String grayLevelString = request.getParameter(clientId + ".x"); int grayLevel = 220; try { grayLevel = Integer.parseInt(grayLevelString); l ( l i ) } catch(NumberFormatException nfe) {} // Image is 440 pixels, so scale. grayLevel = (256 * grayLevel) / 440; String rVal = I t St i V l Integer.toString(grayLevel, 16) t St i ( L l 16); setBgColor("#" + rVal + rVal + rVal); } • Controller designates output page public String showPreview() { return("success"); 47 } Step 2: Create Input Form • Specify both action and actionListener – Listener runs first and has access to low-level internals – Also use h:commandButton with image instead of value • Results in server side image map server-side • Code <h:form> ... <h:commandButton image="images/GrayBar.gif" actionListener="#{colorBean.selectGrayLevel}" #{ } / action="#{colorBean.showPreview}"/> </h:form> 48
  • 24. Step 2: Result • File is tomcat_dir/webapps/jobs/customize-bg.jsp • URL i h is http://localhost/jobs/customize-bg.faces //l lh /j b / i b f 49 Step 3: Edit faces-config.xml • Declaring bean … <faces-config> ... <managed-bean> <managed-bean-name>colorBean</managed-bean-name> <managed-bean-class> coreservlets.ColorBean l l </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </ d b > … </faces-config> 50
  • 25. Step 3: Edit faces-config.xml • Specifying navigation rules … <faces-config> … <navigation-rule> < i ti l > <from-view-id>/customize-bg.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <from outcome>success</from outcome> <to-view-id> /WEB-INF/results/show-preview2.jsp </to-view-id> </to view id> </navigation-case> </navigation-rule> </faces-config> 51 Step 4: Create Results Pages • WEB-INF/results/show-preview2.jsp <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" p @ g p //j /j / prefix="h" %> <f:view> <!DOCTYPE ...> <HTML> <HEAD><TITLE>Preview of Background Color</TITLE></HEAD> <BODY BGCOLOR="<h:outputText value="#{colorBean.bgColor}"/>"> <H1 ALIGN="CENTER">Preview of Background Color</H1> Experienced employee seeks challenging position doing something. <H2>Employment History</H2> Blah, blah, blah, blah. Yadda, yadda, yadda, yadda. … </HTML> </f:view> 52
  • 26. Step 4: Example Result 53 Step 5: Prevent Direct Access to JSP Pages • Use filter that captures url-pattern *.jsp – No changes from previous examples 54
  • 27. Summary • Event listeners are used to handle events that affect only the user interface – Typically fire before beans are populated and validation is performed • Use immediate="true" to designate this behavior immediate= true – Form is redisplayed after listeners fire • No navigation rules apply • Action listeners – Attached to buttons, hypertext links, or image maps – Automatically submit the form • V l change li t Value h listeners – Attached to radio buttons, comboboxes, list boxes, checkboxes, textfields, etc. – Require onclick="submit()" or onchange="submit()" to submit form • Test carefully on all expected browsers 55 © 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.