SlideShare a Scribd company logo
1 of 107
Download to read offline
JavaServer Faces (JSF)

        Atul Kahate

     (akahate@gmail.com)

           JavaServer Faces (JSF) |
                 Atul Kahate          1
What is JSF?
 JSF is a standard Java framework for building
 user interfaces for Web applications
 Created as a Java Community Process (JCP) –
 and hence has higher chances of being a
 success
 Attempts to make client-side development
 browser-independent and also includes
 features such as state management, etc

                JavaServer Faces (JSF) |
                      Atul Kahate            2
JSF Characteristics
 Server-side
 User-interface related
 Component framework
   Components are UI-related, Validations-
   related, Error handling-related, etc




                JavaServer Faces (JSF) |
                      Atul Kahate            3
JSF Application Features
 Similar to JSP-servlet application
 Has a deployment descriptor (web.xml),
 JSP files, tag libraries, static resources,
 etc
 See next slide



                JavaServer Faces (JSF) |
                      Atul Kahate          4
JSF Features Elaborated
 JSP pages: Form the UI
 Deployment descriptor: Indicates use of
 JSF
 Swing-like enhanced UI
 Managed backing beans: Used to hold
 data entered by the user
 Superior validation
              JavaServer Faces (JSF) |
                    Atul Kahate          5
JSF and MVC
 Similar to Swing and other GUI frameworks:
   Model = Properties of an application (e.g. user
   name in an user object)
   View = UI components that specify what events
   occurred (e.g. value changed or button clicked)
   Controller = External event listeners that are
   attached to the UI to handle events




                  JavaServer Faces (JSF) |
                        Atul Kahate                  6
JSF Advantages
 Based on MVC
 Well-defined programming model and tag libraries
 Sun Standard
 Helps reusability
 UI development is easier, faster
 Event handling is easier
 Separates behavior and presentation of information



                   JavaServer Faces (JSF) |
                         Atul Kahate                  7
JSF Drawbacks
 Complex without the use of an IDE
 Still growing
 Applications without using MVC are tough to
 build
 Confusion in file naming (pages are saved
 with .jsp but accessed as .jsf or .faces)
 Absence of regular expressions in validations
 Does not support GET method
                 JavaServer Faces (JSF) |
                       Atul Kahate               8
JSF Parts
 JSF has three parts:
   Set of pre-fabricated User Interface
   components
   Event-driven programming model
   Component model with the facility for
   allowing third-party components



                JavaServer Faces (JSF) |
                      Atul Kahate          9
JSF Application Lifecycle
 There are six phases
 1.   Restore view
 2.   Apply request values
 3.   Process validations
 4.   Update model values
 5.   Invoke application
 6.   Render response
  There are two types of requests
 1.   Initial request
 2.   Postback requests

                      JavaServer Faces (JSF) |
                            Atul Kahate          10
JSF Request Types
1.   Initial request
       Very first request for a page
       First time, so no UI processing/validations
       Deals with Restore view and Render
       response phases
2.   Postback request
       User has submitted a form
       All the six phases are dealt with here
                   JavaServer Faces (JSF) |
                         Atul Kahate             11
JSF Configuration
 A JSF application is a standard Java EE application,
 with the need for the following configuration files
 Entry in the web.xml file                 Enables the Faces controller servlet when
                                           a URL pattern such as /faces/* is
                                           received
 JSF configuration file faces-config.xml   Allows for the configuration of the JSF
                                           application – at par with web.xml file,
                                           and is located in the WEB-INF/ folder
 WEB-INF directory containing              Actual JSF libraries jsf-api.jar and jsf-
                                           impl.jar

                                           Apache commons libraries, such as
                                           commons-beanutils.jar, commns-
                                           collections.jar, commons-
                                           digester.jar, commons-logging.jar
                                           JSTL jar files: jstl.jar and standard.jar
                                 JavaServer Faces (JSF) |
                                       Atul Kahate                                     12
Converting a JSP to a JSF
 The first thing to do in order to convert a JSP page
 into a JSF page for better view is to add the following
 two taglibs:
 <%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f” %>
 <%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h” %>
 Then add a <f:view> tag in the body of the JSP
    This tag becomes the base UI component of the component
    tree in memory of the server when the page is requested for
    viewing
 If the page also takes user input, we also need to
 add a <h:form> tag as a child element of the above
 tag
    Subsequent HTML form element tags would be
    <h:inputText>, <h:commandButton>, etc
                          JavaServer Faces (JSF) |
                                Atul Kahate                    13
Example
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<f:view>
  <html>
    <body>
      <h:form>
       <h2>A simple JSF Page</h2>

         <h:inputText value="#{modelBean.username}" />
         <h:commandButton value="Click here" />
       </h:form>
    </body>
  </html>
</f:view>

                              JavaServer Faces (JSF) |
                                    Atul Kahate               14
JSF UI Component Tree – 1
 A JSF page like the above causes a UI component tree on the
 server, exactly matching with the components specified in the
 page

                 HtmlInputText                     HtmlCommandButton




                                      HtmlForm



                                      UIViewRoot



                        JavaServer Faces (JSF) |
                              Atul Kahate                              15
JSF UI Component Tree – 2
 Once a tree like the above is created
 and loaded in the server’s memory, it is
 possible to interact with the server-side
 UI components, and manipulate them
 directly



               JavaServer Faces (JSF) |
                     Atul Kahate          16
JSF Request Processing
Lifecycle
 Sequence of events when a request is sent to
 a JSF page is called as the JSF request
 processing lifecycle, or simply JSF lifecycle
 Example:
 <h:inputText value=“#{modelBean.username}” />
  This specifies that when the form is submitted, the
  value entered by the user in the input text box
  should be passed on to the corresponding
  property in the server-side JavaBean named
  modelBean

                  JavaServer Faces (JSF) |
                        Atul Kahate                17
JSF Navigation Model – 1

                         View
                      (JSF pages)




      Controller                           Model
    (Faces servlet)                    (Managed beans)




                      JavaServer Faces (JSF) |
                            Atul Kahate                  18
JSF Navigation Model – 2
 Like Struts, JSF design is also based on an MVC
 approach
 Model is bound to methods and properties in the
 managed beans as specified in the faces-
 config.xml file
 Controller is a servlet, that responds to all requests
 that have a certain URL pattern, such as /faces/*,
 as defined in web.xml file
    The controller prepares an object, called as JSF context,
    which contains all accessible application data and routes the
    client to the appropriate view component (page)
 View is the set of JSF pages

                       JavaServer Faces (JSF) |
                             Atul Kahate                       19
JSF Navigation Model – 3
 The navigation model is based on a set
 of navigation rules
 Example
   If something is a success then pass control
   to something-1; else to something-2
 Achieved by specifying appropriate
 rules in the faces-config.xml file (See
 next slide)
                JavaServer Faces (JSF) |
                      Atul Kahate            20
JSF Navigation Model – 3
<navigation-rule>
  <from-view-id>/page1.jsp</from-view-id>
  <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/page2.jsp</to-view-id>
  </navigation-case>
  <navigation-case>
    <from-outcome>failure</from-outcome>
    <to-view-id>/page3.jsp</to-view-id>
  </navigation-case>
</navigation-rule>
                  JavaServer Faces (JSF) |
                        Atul Kahate          21
JSF Case Study – Login

 D:Atul-personalLecturesSICSRWeb
     TechnologiesWT-2JSFJSF-
      SimpleLogin (in NetBeans)


              JavaServer Faces (JSF) |
                    Atul Kahate          22
Application Logic
 The application should accept the user
 ID and password from the user and
 display a welcome page
 The actual user ID and password logic
 would not be built in initially



              JavaServer Faces (JSF) |
                    Atul Kahate           23
index.jsp
 <%@page contentType="text/html"%>
 <%@page pageEncoding="UTF-8"%>
 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
 <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
 <html>
   <f:view>
   <head>
     <title>JSF Login Page Example</title>
   </head>
   <body bgcolor="pink">
     <h:form>
        <h1 align="center">The Login Page</h1>
        <table border="1" bordecolor="maroon" cellspacing="1" cellpadding="1" align="center">
             <tr>
                <td>
                  <h:outputLabel for="txtName">
                     <h:outputText value="Name" />
                  </h:outputLabel>
                </td>
                <td><h:inputText id="txtName" value="#{UserBean.name}" /></td>
             </tr>
             <tr>
                <td>
                  <h:outputLabel for="txtPassword">
                     <h:outputText value="Password" />
                  </h:outputLabel>
                </td>
                <td><h:inputSecret id="txtPassword" value="#{UserBean.password}" /></td>
             </tr>
          <tr align="center">
             <td colspan="2">
                <h:commandButton id="cmdLogin" value="Login" action="login" />
             </td>
          </tr>
        </table>
      </h:form>
   </body>
 </html>
 </f:view>




                                                                      JavaServer Faces (JSF) |
                                                                            Atul Kahate          24
Understanding the JSP – 1
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


  These taglib directives refer to the JSTL tags
      jsf/core – Core library, contains custom action
      elements that represent JSF objects (which are
      independent of the page markup language)
      Jsf/html – HTML library, contains custom action
      elements that represent JSF objects (which are to
      be rendered as HTML elements)
                        JavaServer Faces (JSF) |
                              Atul Kahate                     25
Understanding the JSP – 2
<f:view>

  This is an action element
  A view in JSF is the grouping of components
  that make a specific UI screen
  The view contains an instance of the
  javax.faces.component.UIViewRoot class
  It does not display anything, but it is a
  container for other view components (e.g.
  input fields, buttons, etc)

                 JavaServer Faces (JSF) |
                       Atul Kahate              26
Understanding the JSP – 3
<h:form>


  Represents a form component
  Acts as a container for all input
  components that hold values that needs
  to be processed together
    Examples: <h:inputText>,
    <h:inputSecret>, <h:commandButton>
               JavaServer Faces (JSF) |
                     Atul Kahate          27
Understanding the JSP – 4
<h:outputLabel for="txtName">
          <h:outputText value="Name" />
</h:outputLabel>




  Identifies a component that generates
  an HTML label

                  JavaServer Faces (JSF) |
                        Atul Kahate          28
Understanding the JSP – 5
<h:inputText id="txtName" value="#{UserBean.name}" />



  Generates a text box with id txtName
  The value that user enters here would
  populate an attribute called as name of
  a server-side JavaBean titled UserBean


                      JavaServer Faces (JSF) |
                            Atul Kahate                 29
Understanding the JSP – 6
<h:commandButton id="cmdLogin" value="Login" action="login" />



   Generates a command button with type
   as submit or reset
   The action attribute here has relevance,
   as explained later


                         JavaServer Faces (JSF) |
                               Atul Kahate                       30
How is this linked to the next
page (welcome.jsp)?
                        index.jsp

  …
  <h:commandButton id … action = “login” />
  …



                                                                   faces-config.xml
                  1                               …
                                                  <navigation-rule>
                                                   <from-view-id>/index.jsp<from-view-id>
                                                   <navigation-case>                         2
                                                     <from-outcome>login</from-outcome>
                                                     <to-view-id>/welcome.jsp</to-view-id>
                   3                               …



                       welcome.jsp

  …
  <h:commandButton id … action = “login” />
  …



                                              JavaServer Faces (JSF) |
                                                    Atul Kahate                                  31
UserBean.java
 /*
  * UserBean.java
  *
  * Created on September 25, 2007, 4:34 PM
  *
  * To change this template, choose Tools | Template Manager
  * and open the template in the editor.
  */

 package com.jsf.login;

 /**
  *
  * @author AtulK
  */
 public class UserBean {

     private String name;
     private String password;

     public String getName() {
       return name;
     }

     public void setName(String userName) {
       name = userName;
     }

     public String getPassword() {
       return password;
     }

     public void setPassword(String userPassword) {
       password = userPassword;
     }
                                                      JavaServer Faces (JSF) |
 }
                                                            Atul Kahate          32
Role of UserBean.java
                                             index.jsp

            <html>
             …
             <td><h:inputText id = “txtName” value = “#{UserBean.name}” /></td>
             …




     Whatever the user enters on the
    screen in the text box is passed to
       the JavaBean’s set method



                                          UserBean.java

                       public class UserBean {
                        private String name;
                        …

                           public String get ame () {
                             return name;
                           }

                           public void set ame (String userName) {
                             name = username;
                           }

                           …
                       }


                                           JavaServer Faces (JSF) |
                                                 Atul Kahate                      33
welcome.jsp
 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
 <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

 <html>
   <f:view>
      <head>
         <title>Welcome to JSF!</title>
      </head>

      <body>
        <h:form>
          <h1 align="center">
             <h:outputText id="txtUserName" value="Welcome #{UserBean.name}!" />
          </h1>
        </h:form>

      </body>
   </f:view>
 </html>

                               JavaServer Faces (JSF) |
                                     Atul Kahate                               34
Managed Beans and
Navigation




         JavaServer Faces (JSF) |
               Atul Kahate          35
Managed Beans
 We know that the model in MVC is
 many times made up of JavaBeans
 A JavaBean in JSF is called as a
 managed bean




             JavaServer Faces (JSF) |
                   Atul Kahate          36
Temperature Conversion




          JavaServer Faces (JSF) |
                Atul Kahate          37
Requirement
 Accept temperature in Celsius and
 convert it into Fahrenheit

 D:Atul-personalLecturesSICSRWeb
 TechnologiesWT-
 2JSFTemperatureConversion (or in
 NetBeans 6.0 JSF-Temperature-
 Conversion)
              JavaServer Faces (JSF) |
                    Atul Kahate          38
index.jsp
 <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
      <html>
        <head>
           <title>Celsius converter</title>
        </head>
        <body>
           <f:view>
              <h:form>
                 <table width="30%" height="30%" border="2" cellspacing="0" cellpadding="5">
                    <tr>
                       <td colspan="2">
                          <h:message for="celsiusEdit" />
                       </td>
                    </tr>
                    <tr>
                       <td>
                          <h:inputText id="celsiusEdit" value="#{pageBean.celsius}"/>
                       </td>
                       <td><b>
                            <h:outputText value="Celsius"/>
                       </b></td>
                    </tr>
                    <tr>
                       <td colspan="2">
                          <h:commandButton action="#{pageBean.convertToFahrenheit}" value="Convert"/>
                       </td>
                    </tr>
                    <tr>
                       <td>
                          <h:outputText value="#{pageBean.fahrenheit}"/>
                       </td>
                       <td><b>
                            <h:outputText value="Fahrenheit"/>
                       </b></td>
                    </tr>
                 </table>
              </h:form>
           </f:view>
        </body>
      </html>




                                                               JavaServer Faces (JSF) |
                                                                     Atul Kahate                        39
Understanding index.jsp – 1
<td colspan="2">
      <h:message for="celsiusEdit" />
</td>


  Space reserved for possible error
  messages



                    JavaServer Faces (JSF) |
                          Atul Kahate          40
Understanding index.jsp – 2
<td>
<h:inputText id="celsiusEdit“ value="#{pageBean.celsius}"/>
</td>


 Text box called as celsiusEdit would be
 created, which maps to the celsius
 property of the pageBean


                      JavaServer Faces (JSF) |
                            Atul Kahate                       41
Understanding index.jsp – 3
<td><b>
<h:outputText value="Celsius"/>
</b></td>


 HTML label would get created




                  JavaServer Faces (JSF) |
                        Atul Kahate          42
Understanding index.jsp – 4
<td colspan="2">
  <h:commandButton
      action="#{pageBean.convertToFahrenheit}" value="Convert"/>
</td>


 An HTML button would created, which
 would call the convertToFahrenheit
 method of the pageBean

                        JavaServer Faces (JSF) |
                              Atul Kahate                      43
Understanding index.jsp – 5
<td>
  <h:outputText value="#{pageBean.fahrenheit}"/>
</td>



 Would display the value of the property
 fahrenheit of the pageBean


                     JavaServer Faces (JSF) |
                           Atul Kahate             44
Understanding index.jsp – 6
<td><b>
   <h:outputText value="Fahrenheit"/>
</b></td>



  Would create a label




                        JavaServer Faces (JSF) |
                              Atul Kahate          45
faces-config.xml
 <?xml version="1.0"?>
 <!DOCTYPE faces-config PUBLIC
  "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
  "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

 <faces-config>
       <managed-bean>
                 <description>
                           Simple backing bean.
                 </description>
                 <managed-bean-name>pageBean</managed-bean-name>
                 <managed-bean-class>com.iflex.PageBean</managed-bean-
 class>
                 <managed-bean-scope>request</managed-bean-scope>
       </managed-bean>
 </faces-config>

                           JavaServer Faces (JSF) |
                                 Atul Kahate                             46
pageBean.java
 /*
  * PageBean.java
  *
  * Created on September 20, 2007, 5:28 PM
  *
  * To change this template, choose Tools | Template Manager
  * and open the template in the editor.
  */
 package com.iflex;
 public class PageBean {
                private Double celsius = null;
                private Double fahrenheit = null;
               public PageBean(){
                                       System.out.println("PageBean()");
               }
               public void setCelsius(Double celsius){
                                       System.out.println("setCelsius");
                                       this.celsius = celsius;
               }
               public Double getCelsius(){
                                      System.out.println("getCelsius");
                                      return celsius;
               }
               public void setFahrenheit(Double fahrenheit){
                                      System.out.println("setFahrenheit");
                                      this.fahrenheit = fahrenheit;
               }
               public Double getFahrenheit(){
                                     System.out.println("getFahrenheit");
                                     return fahrenheit;
               }
               public void convertToFahrenheit(){
                                      System.out.println("convertToFahrenheit");
                                      setFahrenheit(new Double(getCelsius().doubleValue() * 1.8 + 32));
               }
 }




                                                                  JavaServer Faces (JSF) |
                                                                        Atul Kahate                       47
Exercises
 Modify the temperature conversion example by
 reversing the logic (accept temperature in F, convert
 to C)
 Accept the number of dollars the user has got, and
 convert that into the equivalent Indian Rupees (USD
 1 = INR 43.10)
   NetBeans USDToINR
 Accept two numbers from the user and tell the user
 which is greater among the two
   NetBeans USDToINR

                   JavaServer Faces (JSF) |
                         Atul Kahate                  48
Message Bundles

   D:AtulLecturesSICSRWeb
 TechnologiesWT-2JSFJSF-More-
            Examples

             JavaServer Faces (JSF) |
                   Atul Kahate          49
What are Message Bundles?
 When we implement a Web application, it is a good
 idea to collect all message strings in a central
 location
 Helps keeping messages consistent and also makes
 in application localization/internationalization easier
 Example
    indexWindowTitle=Hi there!
    thankYouWindowTitle=Thank you for submitting your
    information


                     JavaServer Faces (JSF) |
                           Atul Kahate                     50
Using Message Bundle – Step 1
 Add a properties file to your application
 (e.g. messages.properties file in Source
 packages -> com.corejsf)
 indexWindowTitle=Using Textfields and Textareas
 thankYouWindowTitle=Thank you for submitting your information
 thankYouPageTitle=Thank You!
 indexPageTitle=Please enter the following personal information
 namePrompt=Name:
 submitPrompt=Submit your information



                        JavaServer Faces (JSF) |
                              Atul Kahate                         51
Using Message Bundle – Step 2
 Make references to properties defined
 earlier in your JSP as needed
 (index.jsp)
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <title>
            <h:outputText value = "#{msgs.indexWindowTitle}" />
         </title>
      </head>
      <body>
         <h1><h:outputText value="#{msgs.indexPageTitle}" /></h1>

        <h:form>
            <table>
              <tr>
                 <td>
                    <h:outputText value = "#{msgs.namePrompt}" />
                 </td>
                 <td>
                    <h:inputText value = "#{user.name}" />
                 </td>
              </tr>
            </table>
            <h:commandButton value="#{msgs.submitPrompt}" action="thankYou" />
        </h:form>
      </f:view>
   </body>
 </html>




                                                                                 JavaServer Faces (JSF) |
                                                                                       Atul Kahate          52
Using Message Bundle – Step 3
 The other JSP (thankYou.jsp)
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <html>
   <f:view>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>
         <h:outputText value = "#{msgs.thankYouWindowTitle}" />
      </title>
   </head>
   <body>

        <h1><h:outputText value="#{msgs.namePrompt}" />
        <h:outputText value="#{user.name}" /></h1>

        </f:view>
   </body>
 </html>


                                          JavaServer Faces (JSF) |
                                                Atul Kahate                 53
Using Message Bundle – Step 4
 Code the Bean (UserBean.java)
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 /**
  *
  * @author atulk
  */
 public class UserBean {

     private String name;

     public String getName() {
       return name;
     }

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

 }




                                                 JavaServer Faces (JSF) |
                                                       Atul Kahate          54
Using Message Bundle – Step 5
 Add references to the config file (faces-config.xml)
 <?xml version='1.0' encoding='UTF-8'?>

 <!-- =========== FULL CONFIGURATION FILE ================================== -->

 <faces-config version="1.2"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

   <navigation-rule>
     <from-view-id>/index.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <managed-bean>
     <managed-bean-name>user</managed-bean-name>
     <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <application>
      <resource-bundle>
         <base-name>com.corejsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
   </application>
 </faces-config>


                                                     JavaServer Faces (JSF) |
                                                           Atul Kahate                                                        55
Various JSF UI-related Tags

   D:AtulLecturesSICSRWeb
 TechnologiesWT-2JSFJSF-More-
            Examples

             JavaServer Faces (JSF) |
                   Atul Kahate          56
index-UIExample.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value="#{msgs.indexWindowTitle}" />
         </title>
      </head>

      <body>
        <h:outputText value="#{msgs.indexPageTitle}" styleClass="emphasis" />
        <h:form>
          <table>
             <tr>
               <td>
                  <h:outputText value="#{msgs.namePrompt}" />
               </td>
               <td>
                  <h:inputText value="#{form.name}" />
               </td>
             </tr>

               <tr>
                 <td>
                    <h:outputText value="#{msgs.contactMePrompt}" />
                 </td>
                 <td>
                    <h:selectBooleanCheckbox value="#{form.contactMe}" />
                 </td>
               </tr>

               <tr>
                 <td>
                    <h:outputText value="#{msgs.bestDayPrompt}" />
                 </td>
                 <td>
                    <h:selectManyMenu value="#{form.bestDaysToContact}">
                      <f:selectItems value="#{form.daysOfTheWeekItems}" />
                    </h:selectManyMenu>
                 </td>
               </tr>

               <tr>
                 <td>
                    <h:outputText value="#{msgs.yearOfBirthPrompt}" />
                 </td>
                 <td>
                    <h:selectOneListbox size="5" value="#{form.yearOfBirth}">
                      <f:selectItems value="#{form.yearItems}" />
                    </h:selectOneListbox>
                 </td>
               </tr>

               <tr>
                 <td>
                    <h:outputText value="#{msgs.colorPrompt}" />
                 </td>
                 <td>
                    <h:selectManyCheckbox value="#{form.colors}">
                      <f:selectItems value="#{form.colorItems}" />
                    </h:selectManyCheckbox>
                 </td>
               </tr>

               <tr>
                 <td>
                    <h:outputText value="#{msgs.languagePrompt}" />
                 </td>

                 <td>
                    <h:selectManyListbox value="#{form.languages}">
                      <f:selectItems value="#{form.languageItems}" />
                    </h:selectManyListbox>
                 </td>
               </tr>

              <tr>
                 <td>
                    <h:outputText value="#{msgs.educationPrompt}" />
                 </td>
                 <td>
                    <h:selectOneRadio value="#{form.education}" layout="pageDirection">
                      <f:selectItems value="#{form.educationItems}" />
                    </h:selectOneRadio>
                 </td>
              </tr>
            </table>

            <h:commandButton value="#{msgs.buttonPrompt}" action="showInformation" />

         </h:form>
     </body>
   </f:view>
 </html>




                                                                                          JavaServer Faces (JSF) |
                                                                                                Atul Kahate          57
showMoreInformation-
UIExample.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value="#{msgs.indexWindowTitle}" />
         </title>
      </head>



      <body>
        <h:outputFormat value="#{msgs.thankYouLabel}">
          <f:param value="#{form.name}" />
        </h:outputFormat>

         <p>

         <table>

            <tr>
               <td><h:outputText value="#{msgs.contactMeLabel}" /></td>
               <td><h:outputText value="#{form.contactMe}" /></td>
            </tr>

            <tr>
               <td><h:outputText value="#{msgs.bestDayLabel}" /></td>
               <td><h:outputText value="#{form.bestDaysConcatenated}" /></td>
            </tr>

            <tr>
               <td><h:outputText value="#{msgs.yearOfBirthLabel}" /></td>
               <td><h:outputText value="#{form.yearOfBirth}" /></td>
            </tr>

            <tr>
               <td><h:outputText value="#{msgs.languageLabel}" /></td>
               <td><h:outputText value="#{form.languagesConcatenated}" /></td>
            </tr>

            <tr>
               <td><h:outputText value="#{msgs.colorLabel}" /></td>
               <td><h:outputText value="#{form.colorsConcatenated}" /></td>
            </tr>

            <tr>
               <td><h:outputText value="#{msgs.educationLabel}" /></td>
               <td><h:outputText value="#{form.education}" /></td>
            </tr>

         </table>
      </body>
   </f:view>
 </html>




                                                                                 JavaServer Faces (JSF) |
                                                                                       Atul Kahate          58
faces-config.xml
 <?xml version='1.0' encoding='UTF-8'?>

 <!-- =========== FULL CONFIGURATION FILE ================================== -->

 <faces-config version="1.2"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

   <navigation-rule>
     <from-view-id>/index.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <navigation-rule>
     <from-view-id>/index-UIExample.jsp</from-view-id>
     <navigation-case>
        <from-outcome>showInformation</from-outcome>
        <to-view-id>/showMoreInformation-UIExample.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <managed-bean>
     <managed-bean-name>user</managed-bean-name>
     <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <managed-bean>
     <managed-bean-name>form</managed-bean-name>
     <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <application>
      <resource-bundle>
         <base-name>com.corejsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
   </application>
 </faces-config>




                                                                                     JavaServer Faces (JSF) |
                                                                                           Atul Kahate                        59
RegisterForm.java
 /*
  * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 package com.corejsf;

 import java.text.DateFormatSymbols;
 import java.util.*;

 import javax.faces.model.SelectItem;


 /**
  *
 * @author atulk
 */
 public class RegisterForm {


    enum Education {
       HIGH_SCHOOL, BACHELOR, MASTER, DOCTOR
    };

    private String name;
    private boolean contactMe;
    private Integer [] bestDaysToContact;
    private Integer yearOfBirth;
    private String [] colors;
    private String [] languages;
    private Education education;

    public Integer [] getBestDaysToContact () {
         return bestDaysToContact;
    }


    public void setBestDaysToContact(Integer[] bestDaysToContact) {
       this.bestDaysToContact = bestDaysToContact;
    }

    public String[] getColors() {
         return colors;
    }

    public void setColors(String[] colors) {
         this.colors = colors;
    }

    public boolean isContactMe() {
         return contactMe;
    }

    public void setContactMe(boolean contactMe) {
         this.contactMe = contactMe;
    }


    public Education getEducation() {
       return education;
    }

    public void setEducation(Education education) {
         this.education = education;
    }


    public String[] getLanguages() {
       return languages;
    }

    public void setLanguages(String[] languages) {
         this.languages = languages;
    }

    public String getName() {
       return name;
    }

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

    public Integer getYearOfBirth() {
         return yearOfBirth;
    }

    public void setYearOfBirth(Integer yearOfBirth) {
         this.yearOfBirth = yearOfBirth;
    }

    public Collection <SelectItem> getYearItems () {
         return birthYears;
    }


    public SelectItem [] getDaysOfTheWeekItems () {
       return daysOfTheWeek;
    }

    public Map <String, Object> getLanguageItems () {
         return languageItems;
    }


    public SelectItem [] getColorItems () {
       return colorItems;
    }

    public SelectItem [] getEducationItems () {
         return educationItems;
    }

    public String getBestDaysConcatenated () {
       return concatenate (bestDaysToContact);
    }

    public String getLanguagesConcatenated () {
         return concatenate (languages);
    }

    public String getColorsConcatenated () {
         return concatenate (colors);
    }


    private static String concatenate (Object [] values) {
        if (values == null) {
             return "";
         }
         StringBuilder r = new StringBuilder();

         for (Object value : values) {
             if (r.length () > 0) {
                 r.append(',');
             }
             r.append(value.toString());
         }

         return r.toString();
    }


    private static SelectItem [] colorItems = {
        new SelectItem ("Red"),
         new SelectItem ("Blue"),
         new SelectItem ("Yellow"),
         new SelectItem ("Green"),
         new SelectItem ("Orange"),
         new SelectItem ("White"),
         new SelectItem ("Black"),
         new SelectItem ("Grey")
    };

    private static SelectItem [] educationItems = {
        new SelectItem (Education.HIGH_SCHOOL, "High School"),
         new SelectItem (Education.BACHELOR, "Bachelor's"),
         new SelectItem (Education.MASTER, "Master's"),
         new SelectItem (Education.DOCTOR, "Doctorate")
    };

    private static Map <String, Object> languageItems;


    static {
        languageItems = new LinkedHashMap <String, Object> ();

         languageItems.put ("English", "en");
         languageItems.put ("French", "fr");
         languageItems.put ("Russian", "ru");
         languageItems.put ("Italian", "it");
         languageItems.put ("Spanis", "es");
    }

    private static Collection <SelectItem> birthYears;

    static {
         birthYears = new ArrayList <SelectItem> ();
         for (int i = 1900; i < 2000; i++) {
             birthYears.add (new SelectItem (i));
         }
    }


    private static SelectItem [] daysOfTheWeek;

    static {
         DateFormatSymbols symbols = new DateFormatSymbols ();
         String [] weekdays = symbols.getWeekdays ();
         daysOfTheWeek = new SelectItem [7];
         for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
             daysOfTheWeek [i - 1] = new SelectItem (new Integer (i), weekdays [i]);
         }
    }
    }




                                                                                       JavaServer Faces (JSF) |
                                                                                             Atul Kahate          60
messages.properties
 # To change this template, choose Tools | Templates
 # and open the template in the editor.
 indexWindowTitle=Using JSF UI Features
 indexPageTitle=Please enter the following information

 namePrompt=Name:
 contactMePrompt=Contact me
 bestDayPrompt=What is the best day to contact you?
 yearOfBirthPrompt=What year were you born?
 buttonPrompt=Submit information
 languagePrompt=Select the languages you speak:
 educationPrompt=Select your highest education level:
 emailAppPrompt=Select your email application:
 colorPrompt=Select your favourite colors:

 thankYouLabel=Thank you {0}, for your information
 contactMeLabel=Contact me:
 bestDayLabel=Best day to contact you:
 yearOfBirthLabel=Your year of birth:
 colorLabel=Colors:
 languageLabel=Languages:
 educationLabel=Education:




                                             JavaServer Faces (JSF) |
                                                   Atul Kahate          61
Messages




           JavaServer Faces (JSF) |
                 Atul Kahate          62
JSF Messages
 During the JSF life cycle, any object can
 create a message and add it to a queue of
 messages maintained by the faces context
 At the end of the life cycle (i.e. in the Render
 Response phase), we can display those
 messages in a view
 Usually, messages are associated with a UI
 component and are used to show validation
 errors
                  JavaServer Faces (JSF) |
                        Atul Kahate             63
Message Types
 Information
 Warning
 Error
 Fatal




               JavaServer Faces (JSF) |
                     Atul Kahate          64
Message Details
 All messages can contain a summary and a detail
   Example: summary could be Invalid entry and detail could
   be Age > 100 is not accepted
 Two JSF tags are used for message handling:
   h:messages (Multiple messages for a component)
   h:message (Only a single message for a component)
 They have many attributes, such as
 errorClass, errorStyle, fatalClass, tooltip, etc


                     JavaServer Faces (JSF) |
                           Atul Kahate                        65
index-messageExample.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.indexWindowTitle}" />
         </title>
      </head>
      <body>
         <h1><h:outputText value="#{msgs.indexPageTitle}" /></h1>

          <h:form>
            <h:outputText value="#{msgs.greeting}" styleClass="emphasis" />
            <br />
            <h:messages errorClass="errors" layout="table" />
            <br />

             <table>
                <tr>
                   <td>
                      <h:outputText value = "#{msgs.namePrompt}" />
                   </td>
                   <td>
                      <h:inputText value = "#{ageCheck.name}"
                        required="true" label="#{msgs.namePrompt}" />
                   </td>
                   <td>
                      <h:message for="name" errorClass="errors" />
                   </td>
                </tr>

               <tr>
                  <td>
                     <h:outputText value = "#{msgs.agePrompt}" />
                  </td>
                  <td>
                     <h:inputText value = "#{ageCheck.age}"
                       required="true" size="3"
                       label="#{msgs.agePrompt}" />
                  </td>
                  <td>
                     <h:message for="age" errorClass="errors" />
                  </td>
               </tr>
            </table>
            <h:commandButton value="#{msgs.submitPrompt}" action="thankYou" />
         </h:form>
      </f:view>
   </body>
 </html>




                                                                                 JavaServer Faces (JSF) |
                                                                                       Atul Kahate          66
thankYou-
messageExample.jsp
 <%--
    Document : thankYou-messageExample
    Created on : May 5, 2008, 3:26:50 PM
    Author   : atulk
 --%>

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

 <html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Thank You</title>
   </head>
   <body>
      <h2>Thanks for entering the required information!</h2>
   </body>
 </html>



                                      JavaServer Faces (JSF) |
                                            Atul Kahate                     67
AgeCheckBean.java
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 /**
  *
  * @author atulk
  */
 public class AgeCheckBean {

     private String name;
     private int age;

     public String getName() {
       return name;
     }

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

     public int getAge() {
       return age;
     }

     public void setAge(int age) {
       this.age = age;
     }
 }


                                                        JavaServer Faces (JSF) |
                                                              Atul Kahate          68
messages.properties
 # To change this template, choose Tools | Templates
 # and open the template in the editor.

 greeting=Please fill out the following details

 indexWindowTitle=Using JSF UI Features
 indexPageTitle=Please enter the following information

 namePrompt=Name:
 contactMePrompt=Contact me
 bestDayPrompt=What is the best day to contact you?
 yearOfBirthPrompt=What year were you born?
 buttonPrompt=Submit information
 languagePrompt=Select the languages you speak:
 educationPrompt=Select your highest education level:
 emailAppPrompt=Select your email application:
 colorPrompt=Select your favourite colors:
 agePrompt=Age:
 submitPrompt=Submit form

 thankYouLabel=Thank you {0}, for your information
 contactMeLabel=Contact me:
 bestDayLabel=Best day to contact you:
 yearOfBirthLabel=Your year of birth:
 colorLabel=Colors:
 languageLabel=Languages:
 educationLabel=Education:



                                                         JavaServer Faces (JSF) |
                                                               Atul Kahate          69
faces-config.xml
 <?xml version='1.0' encoding='UTF-8'?>

 <!-- =========== FULL CONFIGURATION FILE ================================== -->

 <faces-config version="1.2"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

   <navigation-rule>
     <from-view-id>/index.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <navigation-rule>
     <from-view-id>/index-UIExample.jsp</from-view-id>
     <navigation-case>
        <from-outcome>showInformation</from-outcome>
        <to-view-id>/showMoreInformation-UIExample.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <navigation-rule>
     <from-view-id>/index-messageExample.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou-messageExample.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>



   <managed-bean>
     <managed-bean-name>user</managed-bean-name>
     <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <managed-bean>
     <managed-bean-name>ageCheck</managed-bean-name>
     <managed-bean-class>com.corejsf.AgeCheckBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <managed-bean>
     <managed-bean-name>form</managed-bean-name>
     <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

    <application>
      <resource-bundle>
         <base-name>com.corejsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
    </application>
 </faces-config>




                                                                                                                              JavaServer Faces (JSF) |
                                                                                                                                    Atul Kahate          70
Panels




         JavaServer Faces (JSF) |
               Atul Kahate          71
What are Panels?
 Normally we use HTML tables to align
 form prompts and messages
 It is error-prone and tedious
 Hence, JSF introduces h:panelGrid,
 which generates a table element
 <h:panelGrid columns=“3”>
    …
 </h:panelGrid>
              JavaServer Faces (JSF) |
                    Atul Kahate          72
Note about columns
 The columns attribute is optional – defaults to
 1
 If specified, UI components are placed from
 left to right and top to bottom
   Example: If we specify columns as 3 and we have
   9 components, we will get a panel grid with 3
   rows and 3 columns – instead, if we have 10
   components, we will have 4 rows and 3 columns
   (last two columns in the fourth row would be
   empty)
                 JavaServer Faces (JSF) |
                       Atul Kahate               73
index-panelGrid.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.indexWindowTitle}" />
         </title>
      </head>
      <body>
         <h1><h:outputText value="#{msgs.indexPageTitle}" /></h1>

          <h:form>
            <h:panelGrid columns="2" rowClasses="oddRows, evenRows" border="2">
               <h:outputText value = "#{msgs.namePrompt}" />
               <h:panelGroup>
                 <h:inputText id="name" value="#{ageCheck.name}"
                          required="true" label="#{msgs.namePrompt}" />
                 <h:message for="name" errorClass="errors" />
               </h:panelGroup>

                <h:outputText value = "#{msgs.agePrompt}" />
                <h:inputText id="age" value="#{ageCheck.age}"
                         size="3" label="#{msgs.agePrompt}" required= "true"/>
                         <h:message for="age" errorClass="errors" />



            </h:panelGrid>
            <h:commandButton value="#{msgs.submitPrompt}" action="thankYou" />
         </h:form>
      </f:view>
   </body>
 </html>




                                                                                  JavaServer Faces (JSF) |
                                                                                        Atul Kahate          74
faces-config.xml
 <?xml version='1.0' encoding='UTF-8'?>

 <!-- =========== FULL CONFIGURATION FILE ================================== -->

 <faces-config version="1.2"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

   <navigation-rule>
     <from-view-id>/index.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <navigation-rule>
     <from-view-id>/index-UIExample.jsp</from-view-id>
     <navigation-case>
        <from-outcome>showInformation</from-outcome>
        <to-view-id>/showMoreInformation-UIExample.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <navigation-rule>
     <from-view-id>/index-messageExample.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou-messageExample.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <navigation-rule>
     <from-view-id>/index-panelGrid.jsp</from-view-id>
     <navigation-case>
        <from-outcome>thankYou</from-outcome>
        <to-view-id>/thankYou-messageExample.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>




   <managed-bean>
     <managed-bean-name>user</managed-bean-name>
     <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <managed-bean>
     <managed-bean-name>ageCheck</managed-bean-name>
     <managed-bean-class>com.corejsf.AgeCheckBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <managed-bean>
     <managed-bean-name>form</managed-bean-name>
     <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

    <application>
      <resource-bundle>
         <base-name>com.corejsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
    </application>
 </faces-config>




                                                                                                                              JavaServer Faces (JSF) |
                                                                                                                                    Atul Kahate          75
Data Tables




          JavaServer Faces (JSF) |
                Atul Kahate          76
Data Table
 <h:dataTable> tag is used to deal with tabular data
 Iterates over data to create an HTML table
 <h:dataTable value’#{items}’ var=‘item’>
   <h:column>
     <h:output_text value=‘#{item.propertyName}’>
   </h:column>
   <h:column>
     <h:output_text value=‘#{item.propertyName}’>
   </h:column>
   …
 </h:dataTable>
   Only <h:column> is allowed inside the body of <h:dataTable>
                       JavaServer Faces (JSF) |
                             Atul Kahate                         77
Allowed sources of data
 Java object
 Array
 An instance   of   java.util.List
 An instance   of   java.sql.ResultSet
 An instance   of   javax.servlet.jsp.jstl.sql.Result
 An instance   of   javax.faces.model.DataModel



                     JavaServer Faces (JSF) |
                           Atul Kahate              78
index-dataTable-1.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <title>
            <h:outputText value = "#{msgs.indexMessageTitle}" />
         </title>
      </head>

       <body>
         <h1><h:outputText value="#{msgs.indexMessageTitle}" /></h1>

          <p />

          <h:form>

             <h:dataTable value="#{tableData.names}" var="name">

                <h:column>
                  <h:outputText value="#{name.last}" />
                </h:column>

                <h:column>
                  <h:outputText value="#{name.first}" />
                </h:column>

             </h:dataTable>

         </h:form>
      </f:view>
   </body>
 </html>




                                                                       JavaServer Faces (JSF) |
                                                                             Atul Kahate          79
TableData.java
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 /**
  *
  * @author atulk
  */
 public class TableData {

     private static final Name [] names = new Name [] {
        new Name ("Atul", "Kahate"),
        new Name ("Dinesh", "Samant"),
        new Name ("Umesh", "Aherwadikar"),
        new Name ("Parag", "Chincholkar")
     };

     public Name [] getNames () {
       return names;
     }
 }


                                                  JavaServer Faces (JSF) |
                                                        Atul Kahate          80
Name.java
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 /**
  *
  * @author atulk
  */
 public class Name {

     private String first;
     private String last;

     public Name(String first, String last) {
       this.first = first;
       this.last = last;
     }

     public void setFirst (String first) {
       this.first = first;
     }

     public String getFirst () {
       return first;
     }

     public void setLast (String last) {
       this.last = last;
     }

     public String getLast () {
       return last;
     }
 }



                                                        JavaServer Faces (JSF) |
                                                              Atul Kahate          81
dataTable with Headers and
Footers




          JavaServer Faces (JSF) |
                Atul Kahate          82
index-dataTable-2.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.windowTitle1}" />
         </title>
      </head>

       <body>
         <h:form>

             <h:dataTable value="#{tableData.names}" var="name"
                     captionStyle="font-size: 0.95em; font-style: italic"
                     style="width: 250px;">

                <f:facet name="caption">
                   <h:outputText value="An array of names: "/>
                </f:facet>

                <h:column headerClass="columnHeader"
                       footerClass="columnFooter">
                  <f:facet name="header">
                     <h:outputText value="#{msgs.lastnameColumn}" />
                  </f:facet>

                   <h:outputText value="#{name.last}" />

                   <f:facet name="footer">
                      <h:outputText value="#{msgs.alphanumeric}" />
                   </f:facet>

                </h:column>

                <h:column headerClass="columnHeader"
                       footerClass="columnFooter">
                  <f:facet name="header">
                     <h:outputText value="#{msgs.firstnameColumn}" />
                  </f:facet>

                   <h:outputText value="#{name.first}" />

                   <f:facet name="footer">
                      <h:outputText value="#{msgs.alphanumeric}" />
                   </f:facet>

                </h:column>

             </h:dataTable>

         </h:form>
      </body>
   </f:view>
 </html>




                                                                            JavaServer Faces (JSF) |
                                                                                  Atul Kahate          83
messages.properties
 # To change this template, choose Tools | Templates
 # and open the template in the editor.

 greeting=Please fill out the following details

 indexWindowTitle=Using JSF UI Features
 indexPageTitle=Please enter the following information
 indexMessageTitle=This is for your information
 windowTitle1=Headers, Footers, and Captions



 namePrompt=Name:
 contactMePrompt=Contact me
 bestDayPrompt=What is the best day to contact you?
 yearOfBirthPrompt=What year were you born?
 buttonPrompt=Submit information
 languagePrompt=Select the languages you speak:
 educationPrompt=Select your highest education level:
 emailAppPrompt=Select your email application:
 colorPrompt=Select your favourite colors:
 agePrompt=Age:
 submitPrompt=Submit form

 thankYouLabel=Thank you {0}, for your information
 contactMeLabel=Contact me:
 bestDayLabel=Best day to contact you:
 yearOfBirthLabel=Your year of birth:
 colorLabel=Colors:
 languageLabel=Languages:
 educationLabel=Education:

 lastnameColumn=Last Name
 firstnameColumn=First Name
 editColumn=edit
 alphanumeric=[alpha]




                                                         JavaServer Faces (JSF) |
                                                               Atul Kahate          84
dataTable – Allow Edits




           JavaServer Faces (JSF) |
                 Atul Kahate          85
index-dataTable-3.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.windowTitle2}" />
         </title>
      </head>

       <body>
         <h:form>

             <h:dataTable value="#{tableData.names}" var="name"
                     captionStyle="font-size: 0.95em; font-style: italic"
                     style="width: 250px;">
               <h:column>

                   <f:facet name="header">
                      <h:outputText value="#{msgs.editColumn}"
                               style="font-weight:bold" />
                   </f:facet>

                   <h:selectBooleanCheckbox value="#{name.editable}"
                                    onclick="submit()" />
                </h:column>

                <h:column>
                  <f:facet name="header">
                     <h:outputText value="#{msgs.lastnameColumn}"
                              style="font-weight: bold" />
                  </f:facet>

                   <h:inputText value="#{name.last}" rendered="#{name.editable}"
                            size="10" />

                   <h:outputText value="#{name.last}"
                            rendered="#{not name.editable}" />
                </h:column>

                <h:column>

                   <f:facet name="header">
                      <h:outputText value="#{msgs.firstnameColumn}"
                               style="font-weight:bold" />
                   </f:facet>

                   <h:inputText value="#{name.first}" rendered="#{name.editable}" size="10" />
                   <h:outputText value="#{name.first}" rendered="#{not name.editable}" />

                </h:column>

             </h:dataTable>

             <h:commandButton value="#{msgs.saveChangesButtonText}" />

         </h:form>
      </body>
   </f:view>
 </html>




                                                                                                 JavaServer Faces (JSF) |
                                                                                                       Atul Kahate          86
Name.java
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 /**
  *
  * @author atulk
  */
 public class Name {

     private String first;
     private String last;
     private boolean editable = false;

     public Name(String first, String last) {
       this.first = first;
       this.last = last;
     }

     public void setFirst (String first) {
       this.first = first;
     }

     public String getFirst () {
       return first;
     }

     public void setLast (String last) {
       this.last = last;
     }

     public String getLast () {
       return last;
     }

     public boolean getEditable () {
       return editable;
     }
 }




                                                        JavaServer Faces (JSF) |
                                                              Atul Kahate          87
Database Tables




          JavaServer Faces (JSF) |
                Atul Kahate          88
Database Tables – Usage
 The JDF data table component is a
 good fit for showing data stored in a
 database
 For this purpose, we need to write a
 managed bean, which will perform the
 JDBC operations to bring the data of
 interest

              JavaServer Faces (JSF) |
                    Atul Kahate          89
CustomerBean.java
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 import   java.sql.*;
 import   javax.servlet.jsp.jstl.sql.Result;
 import   javax.servlet.jsp.jstl.sql.ResultSupport;
 import   javax.sql.DataSource;

 /**
  *
  * @author atulk
  */
 public class CustomerBean {

     private Connection con;

     public void open () throws SQLException {
       if (con != null) {
           return;
       }
       con = DriverManager.getConnection                        ("jdbc:derby://localhost:1527/customer");
     }

     public Result getAll () throws SQLException {
       try {
           open ();
           Statement stmt = con.createStatement();
           ResultSet rs = stmt.executeQuery ("SELECT * FROM customers");
           return ResultSupport.toResult(rs);
       } finally {
           close ();
       }
     }

     public void close () throws SQLException {
       if (con != null) {
           con.close();
           con = null;
       }
     }
 }




                                                                                                            JavaServer Faces (JSF) |
                                                                                                                  Atul Kahate          90
index-dataTable-4.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.windowTitle2}" />
         </title>
      </head>

       <body>
         <h:form>
           <h:dataTable value="#{customer.all}" var="customer"
                    styleClass="customers"
                    headerClass="customersHeader"
                    rowClasses="oddRow,evenRow"
                    columnClasses="custid,name">
                       <!-- Only one of the row/column classes would work -->
              <h:column>
                <f:facet name="header">
                   <h:outputText value="#{msgs.customerIdHeader}" />
                </f:facet>
                <h:outputText value="#{customer.cust_ID}" />
              </h:column>

                <h:column>
                  <f:facet name="header">
                     <h:outputText value="#{msgs.nameHeader}" />
                  </f:facet>
                  <h:outputText value="#{customer.name}" />
                </h:column>

                <h:column>
                  <f:facet name="header">
                     <h:outputText value="#{msgs.phoneHeader}" />
                  </f:facet>
                  <h:outputText value="#{customer.phone_number}" />
                </h:column>

                <h:column>
                  <f:facet name="header">
                     <h:outputText value="#{msgs.addressHeader}" />
                  </f:facet>
                  <h:outputText value="#{customer.street_address}" />
                </h:column>

                <h:column>
                  <f:facet name="header">
                     <h:outputText value="#{msgs.cityHeader}" />
                  </f:facet>
                  <h:outputText value="#{customer.city}" />
                </h:column>

                <h:column>
                  <f:facet name="header">
                     <h:outputText value="#{msgs.stateHeader}" />
                  </f:facet>
                  <h:outputText value="#{customer.state}" />
                </h:column>

           </h:dataTable>
         </h:form>
      </body>
   </f:view>
 </html>




                                                                                JavaServer Faces (JSF) |
                                                                                      Atul Kahate          91
styles.css
 /*
      Document : styles
      Created on : May 5, 2008, 4:02:56 PM
      Author    : atulk
      Description:
         Purpose of the stylesheet follows.
 */

 /*
      TODO customize this sample style
      Syntax recommendation http://www.w3.org/TR/REC-CSS2/
 */

 body {
 background: #eee;
 }

 .emphasis {
 font-size: 1.3em;
 }

 .errors {
 font-style: italic;
 }

 .evenRows {
 background: PowderBlue;
 }

 .oddRows {
 background: MediumTurquoise;
 }

 .customers {
 border: thin solid black;
 }

 .customersHeader {
 text-align: center;
 font-style:italic;
 color: Snow;
 background: Teal;
 }

 .custid {
 height: 25px;
 text-align: center;
 background: MediumTurquoise;
 }

 .name {
 text-align: center;
 background: PowderBlue;
 }

 .evenRow {
 background: PowderBlue;
 }

 .oddRow {
 background: MediumTurquoise;
 }




                                                             JavaServer Faces (JSF) |
                                                                   Atul Kahate          92
Conversion and Validation




           JavaServer Faces (JSF) |
                 Atul Kahate          93
Overview of Conversion and
Validation
 Two-step process
   Convert into local value (i.e. from request
   object’s string to whatever data type the
   model expects) and then validate
   If ok, update model (i.e. set the bean
   properties with the request values)



                JavaServer Faces (JSF) |
                      Atul Kahate                94
Using Standard Convertors

 (JSF-Convertors-and-Validators in
           NetBeans)


             JavaServer Faces (JSF) |
                   Atul Kahate          95
Numbers and Dates
 Suppose we want to accept the
 amount, card number, and card expiry
 date for a payment
 What would happen if we code our JSP,
 bean etc as follows?
 Try running it


                  JavaServer Faces (JSF) |
                        Atul Kahate          96
convertor-example-1-
original.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.indexTitle1}" />
         </title>
      </head>

       <body>
         <h:form>

             <h1><h:outputText value="#{msgs.bodyTitle1}" /></h1>

             <h:panelGrid columns="2" border="2" cellpadding="5" rowClasses="oddRows,evenRows">

                <h:outputLabel value="#{msgs.amountPrompt}: " />
                <h:inputText id="amount" value="#{payment.amount}“ />

                <h:outputLabel value="#{msgs.cardNumberPrompt}: " />
                <h:inputText id="cardNumber" value="#{payment.cardNumber}" />



                <h:outputLabel value="#{msgs.expiryDatePrompt}: " />
                <h:inputText id="expiryDate" value="#{payment.expiryDate}“ />

             </h:panelGrid>

             <br />

             <h:commandButton value="#{msgs.submitPrompt}" action = "submit" />



         </h:form>
      </body>
   </f:view>
 </html>




                                                                                  JavaServer Faces (JSF) |
                                                                                        Atul Kahate          97
PaymentBean.java
 /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 package com.corejsf;

 import java.util.Date;

 /**
  *
  * @author atulk
  */
 public class PaymentBean {

     private float amount;
     private String cardNumber;
     private Date expiryDate;

     public float getAmount() {
       return amount;
     }

     public void setAmount(float amount) {
       this.amount = amount;
     }

     public String getCardNumber() {
       return cardNumber;
     }

     public void setCardNumber(String cardNumber) {
       this.cardNumber = cardNumber;
     }

     public Date getExpiryDate() {
       return expiryDate;
     }

     public void setExpiryDate(Date expiryDate) {
       this.expiryDate = expiryDate;
     }




 }




                                                        JavaServer Faces (JSF) |
                                                              Atul Kahate          98
faces-config.xml
 <?xml version='1.0' encoding='UTF-8'?>

 <!-- =========== FULL CONFIGURATION FILE ================================== -->

 <faces-config version="1.2"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

   <navigation-rule>
     <from-view-id>/convertor-example-1.jsp</from-view-id>
     <navigation-case>
        <from-outcome>submit</from-outcome>
        <to-view-id>/convertor-example-1-output.jsp</to-view-id>
     </navigation-case>
   </navigation-rule>

   <managed-bean>
     <managed-bean-name>payment</managed-bean-name>
     <managed-bean-class>com.corejsf.PaymentBean</managed-bean-class>
     <managed-bean-scope>session</managed-bean-scope>
   </managed-bean>

   <application>
     <resource-bundle>
        <base-name>com.corejsf.messages</base-name>
        <var>msgs</var>
     </resource-bundle>
   </application>

 </faces-config>



                                                             JavaServer Faces (JSF) |
                                                                   Atul Kahate                                                99
messages.properties
 indexTitle1=Payment Information Processing

 bodyTitle1=Enter payment information

 amountPrompt=Amount
 cardNumberPrompt=Card Number
 expiryDatePrompt=Expiry Date

 submitPrompt=Submit
                  JavaServer Faces (JSF) |
                        Atul Kahate           100
styles.css
 /*
      Document : styles
      Created on : May 12, 2008, 11:37:01 AM
      Author    : atulk
      Description:
         Purpose of the stylesheet follows.
 */

 /*
      TODO customize this sample style
      Syntax recommendation http://www.w3.org/TR/REC-CSS2/
 */

 body {
 background: #eee;
 }

 .evenRows {
    background-color: silver;
 }

 .oddRows {
 background: MediumTurquoise;
 }


                                               JavaServer Faces (JSF) |
                                                     Atul Kahate          101
convertor-example-1-
output.jsp
 <%--
    Document : convertor-example-1-output
    Created on : May 12, 2008, 11:03:02 AM
    Author   : atulk
 --%>

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

 <html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>JSP Page</title>
   </head>
   <body>
      <h2>Hello World!</h2>
   </body>
 </html>



                                      JavaServer Faces (JSF) |
                                            Atul Kahate                     102
What is the result?
 In the Glassfish output, we would
 notice conversion errors
 The screen would not move to the next
 page
 How do we fix this?
   Use convertors (see modified JSP on the
   next slide)

                JavaServer Faces (JSF) |
                      Atul Kahate            103
convertor-example-1.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.indexTitle1}" />
         </title>
      </head>

      <body>
        <h:form>

            <h1><h:outputText value="#{msgs.bodyTitle1}" /></h1>

            <h:panelGrid columns="2" border="2" cellpadding="5" rowClasses="oddRows,evenRows">

               <h:outputLabel value="#{msgs.amountPrompt}: " />
               <h:inputText id="amount" value="#{payment.amount}">
                 <f:convertNumber minFractionDigits="2" />
               </h:inputText>

               <h:outputLabel value="#{msgs.cardNumberPrompt}: " />
               <h:inputText id="cardNumber" value="#{payment.cardNumber}" />



               <h:outputLabel value="#{msgs.expiryDatePrompt}: " />
               <h:inputText id="expiryDate" value="#{payment.expiryDate}">
                 <f:convertDateTime pattern="MM/yyyy" />
               </h:inputText>

            </h:panelGrid>

            <br />

            <h:commandButton value="#{msgs.submitPrompt}" action = "submit" />



         </h:form>
      </body>
   </f:view>
 </html>




                                                                                                 JavaServer Faces (JSF) |
                                                                                                       Atul Kahate          104
Result now?
 We have added convertors as follows:
   <h:inputText value=“#{payment.amount}”>
     <f:convertNumber minFractionDigits=“2” />
   </h:inputText>
   AND
   <h:inputText value=“#{payment.date}”>
     <f:convertDateTime pattern=“MM/yyyy” />
   </h:inputText>
 They ensure correct input
                    JavaServer Faces (JSF) |
                          Atul Kahate            105
Conversion even in the
output!
 convertor-example-1-output.jsp
 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
 <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

 <%--
    This file is an entry point for JavaServer Faces application.
 --%>

 <html>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css" />
         <title>
            <h:outputText value = "#{msgs.indexTitle2}" />
         </title>
      </head>

      <body>
        <h:form>

            <h1><h:outputText value="#{msgs.bodyTitle2}" /></h1>

            <h:panelGrid columns="2" border="2" cellpadding="5" rowClasses="oddRows,evenRows">

               <h:outputLabel value="#{msgs.amountPrompt}: " />
               <h:outputText value="#{payment.amount}">
                 <f:convertNumber type="currency"/>
               </h:outputText>

               <h:outputLabel value="#{msgs.cardNumberPrompt}: " />
               <h:outputText id="cardNumber" value="#{payment.cardNumber}" />



               <h:outputLabel value="#{msgs.expiryDatePrompt}: " />
               <h:outputText id="expiryDate" value="#{payment.expiryDate}">
                 <f:convertDateTime pattern="MM/dd/yyyy"/>
               </h:outputText>

            </h:panelGrid>

            <br />

            <h:commandButton value="#{msgs.submitPrompt}" action = "submit" />



         </h:form>
      </body>
   </f:view>
 </html>




                                                                                                 JavaServer Faces (JSF) |
                                                                                                       Atul Kahate          106
Thank You!




             JavaServer Faces (JSF) |
                   Atul Kahate          107

More Related Content

What's hot

Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSFSoftServe
 
9. java server faces
9. java server faces9. java server faces
9. java server facesAnusAhmad
 
Sun JSF Presentation
Sun JSF PresentationSun JSF Presentation
Sun JSF PresentationGaurav Dighe
 
Magento mega menu extension
Magento mega menu extensionMagento mega menu extension
Magento mega menu extensionBun Danny
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2Jim Driscoll
 
Greate Introduction to Oracle Fusion Middleware and ADF
Greate Introduction to Oracle Fusion Middleware and ADFGreate Introduction to Oracle Fusion Middleware and ADF
Greate Introduction to Oracle Fusion Middleware and ADFMohamed Shahpoup
 
J2 ee architecture
J2 ee architectureJ2 ee architecture
J2 ee architectureKrishna Mer
 
Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)blahap
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Courseguest764934
 
Simple module Development in Joomla! 2.5
Simple module Development in Joomla! 2.5Simple module Development in Joomla! 2.5
Simple module Development in Joomla! 2.5Vishwash Gaur
 
Drupal features knowledge sharing
Drupal features   knowledge sharingDrupal features   knowledge sharing
Drupal features knowledge sharingBrahampal Singh
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkGuo Albert
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCIMC Institute
 
Lab 5a) create a struts application
Lab 5a) create a struts applicationLab 5a) create a struts application
Lab 5a) create a struts applicationtechbed
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applicationselliando dias
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsIMC Institute
 

What's hot (20)

Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
 
Jsf2.0 -4
Jsf2.0 -4Jsf2.0 -4
Jsf2.0 -4
 
Sun JSF Presentation
Sun JSF PresentationSun JSF Presentation
Sun JSF Presentation
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Magento mega menu extension
Magento mega menu extensionMagento mega menu extension
Magento mega menu extension
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
 
Greate Introduction to Oracle Fusion Middleware and ADF
Greate Introduction to Oracle Fusion Middleware and ADFGreate Introduction to Oracle Fusion Middleware and ADF
Greate Introduction to Oracle Fusion Middleware and ADF
 
Lec2 ecom fall16
Lec2 ecom fall16Lec2 ecom fall16
Lec2 ecom fall16
 
J2 ee architecture
J2 ee architectureJ2 ee architecture
J2 ee architecture
 
Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
 
Struts course material
Struts course materialStruts course material
Struts course material
 
Simple module Development in Joomla! 2.5
Simple module Development in Joomla! 2.5Simple module Development in Joomla! 2.5
Simple module Development in Joomla! 2.5
 
Drupal features knowledge sharing
Drupal features   knowledge sharingDrupal features   knowledge sharing
Drupal features knowledge sharing
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
 
Lab 5a) create a struts application
Lab 5a) create a struts applicationLab 5a) create a struts application
Lab 5a) create a struts application
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
 

Similar to AK 5 JSF 21 july 2008

Similar to AK 5 JSF 21 july 2008 (20)

Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSF and Seam
JSF and SeamJSF and Seam
JSF and Seam
 
Jsf
JsfJsf
Jsf
 
Jsf 2
Jsf 2Jsf 2
Jsf 2
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Jsf 2.0 in depth
Jsf 2.0 in depthJsf 2.0 in depth
Jsf 2.0 in depth
 
JSF2 and JSP
JSF2 and JSPJSF2 and JSP
JSF2 and JSP
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Jsf
JsfJsf
Jsf
 
Jsfsunum
JsfsunumJsfsunum
Jsfsunum
 
Lec5 ecom fall16_modified7_november16
Lec5 ecom fall16_modified7_november16Lec5 ecom fall16_modified7_november16
Lec5 ecom fall16_modified7_november16
 
MVC
MVCMVC
MVC
 
Jsfsunum
JsfsunumJsfsunum
Jsfsunum
 
JSF Presentation"2"
JSF Presentation"2"JSF Presentation"2"
JSF Presentation"2"
 
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
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Securing JSF Applications Against the OWASP Top Ten
Securing JSF Applications Against the OWASP Top TenSecuring JSF Applications Against the OWASP Top Ten
Securing JSF Applications Against the OWASP Top Ten
 
JSF 2.0 Preview
JSF 2.0 PreviewJSF 2.0 Preview
JSF 2.0 Preview
 

More from gauravashq

5 xsl (formatting xml documents)
5   xsl (formatting xml documents)5   xsl (formatting xml documents)
5 xsl (formatting xml documents)gauravashq
 
4 xml namespaces and xml schema
4   xml namespaces and xml schema4   xml namespaces and xml schema
4 xml namespaces and xml schemagauravashq
 
3 xml namespaces and xml schema
3   xml namespaces and xml schema3   xml namespaces and xml schema
3 xml namespaces and xml schemagauravashq
 
2 dtd - validating xml documents
2   dtd - validating xml documents2   dtd - validating xml documents
2 dtd - validating xml documentsgauravashq
 
1 introduction to xml
1   introduction to xml1   introduction to xml
1 introduction to xmlgauravashq
 
1 electronic data interchange (edi)
1   electronic data interchange (edi)1   electronic data interchange (edi)
1 electronic data interchange (edi)gauravashq
 
AK 3 web services using apache axis
AK 3   web services using apache axisAK 3   web services using apache axis
AK 3 web services using apache axisgauravashq
 

More from gauravashq (18)

Spring.pdf
Spring.pdfSpring.pdf
Spring.pdf
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Ajax
AjaxAjax
Ajax
 
6 xml parsing
6   xml parsing6   xml parsing
6 xml parsing
 
5 xsl (formatting xml documents)
5   xsl (formatting xml documents)5   xsl (formatting xml documents)
5 xsl (formatting xml documents)
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
 
4 xslt
4   xslt4   xslt
4 xslt
 
4 xml namespaces and xml schema
4   xml namespaces and xml schema4   xml namespaces and xml schema
4 xml namespaces and xml schema
 
3 xml namespaces and xml schema
3   xml namespaces and xml schema3   xml namespaces and xml schema
3 xml namespaces and xml schema
 
2 dtd - validating xml documents
2   dtd - validating xml documents2   dtd - validating xml documents
2 dtd - validating xml documents
 
1 introduction to xml
1   introduction to xml1   introduction to xml
1 introduction to xml
 
1 electronic data interchange (edi)
1   electronic data interchange (edi)1   electronic data interchange (edi)
1 electronic data interchange (edi)
 
AK 4 JSF
AK 4 JSFAK 4 JSF
AK 4 JSF
 
AK 3 web services using apache axis
AK 3   web services using apache axisAK 3   web services using apache axis
AK 3 web services using apache axis
 
AK css
AK cssAK css
AK css
 
AK html
AK  htmlAK  html
AK html
 

Recently uploaded

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

AK 5 JSF 21 july 2008

  • 1. JavaServer Faces (JSF) Atul Kahate (akahate@gmail.com) JavaServer Faces (JSF) | Atul Kahate 1
  • 2. What is JSF? JSF is a standard Java framework for building user interfaces for Web applications Created as a Java Community Process (JCP) – and hence has higher chances of being a success Attempts to make client-side development browser-independent and also includes features such as state management, etc JavaServer Faces (JSF) | Atul Kahate 2
  • 3. JSF Characteristics Server-side User-interface related Component framework Components are UI-related, Validations- related, Error handling-related, etc JavaServer Faces (JSF) | Atul Kahate 3
  • 4. JSF Application Features Similar to JSP-servlet application Has a deployment descriptor (web.xml), JSP files, tag libraries, static resources, etc See next slide JavaServer Faces (JSF) | Atul Kahate 4
  • 5. JSF Features Elaborated JSP pages: Form the UI Deployment descriptor: Indicates use of JSF Swing-like enhanced UI Managed backing beans: Used to hold data entered by the user Superior validation JavaServer Faces (JSF) | Atul Kahate 5
  • 6. JSF and MVC Similar to Swing and other GUI frameworks: Model = Properties of an application (e.g. user name in an user object) View = UI components that specify what events occurred (e.g. value changed or button clicked) Controller = External event listeners that are attached to the UI to handle events JavaServer Faces (JSF) | Atul Kahate 6
  • 7. JSF Advantages Based on MVC Well-defined programming model and tag libraries Sun Standard Helps reusability UI development is easier, faster Event handling is easier Separates behavior and presentation of information JavaServer Faces (JSF) | Atul Kahate 7
  • 8. JSF Drawbacks Complex without the use of an IDE Still growing Applications without using MVC are tough to build Confusion in file naming (pages are saved with .jsp but accessed as .jsf or .faces) Absence of regular expressions in validations Does not support GET method JavaServer Faces (JSF) | Atul Kahate 8
  • 9. JSF Parts JSF has three parts: Set of pre-fabricated User Interface components Event-driven programming model Component model with the facility for allowing third-party components JavaServer Faces (JSF) | Atul Kahate 9
  • 10. JSF Application Lifecycle There are six phases 1. Restore view 2. Apply request values 3. Process validations 4. Update model values 5. Invoke application 6. Render response There are two types of requests 1. Initial request 2. Postback requests JavaServer Faces (JSF) | Atul Kahate 10
  • 11. JSF Request Types 1. Initial request Very first request for a page First time, so no UI processing/validations Deals with Restore view and Render response phases 2. Postback request User has submitted a form All the six phases are dealt with here JavaServer Faces (JSF) | Atul Kahate 11
  • 12. JSF Configuration A JSF application is a standard Java EE application, with the need for the following configuration files Entry in the web.xml file Enables the Faces controller servlet when a URL pattern such as /faces/* is received JSF configuration file faces-config.xml Allows for the configuration of the JSF application – at par with web.xml file, and is located in the WEB-INF/ folder WEB-INF directory containing Actual JSF libraries jsf-api.jar and jsf- impl.jar Apache commons libraries, such as commons-beanutils.jar, commns- collections.jar, commons- digester.jar, commons-logging.jar JSTL jar files: jstl.jar and standard.jar JavaServer Faces (JSF) | Atul Kahate 12
  • 13. Converting a JSP to a JSF The first thing to do in order to convert a JSP page into a JSF page for better view is to add the following two taglibs: <%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f” %> <%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h” %> Then add a <f:view> tag in the body of the JSP This tag becomes the base UI component of the component tree in memory of the server when the page is requested for viewing If the page also takes user input, we also need to add a <h:form> tag as a child element of the above tag Subsequent HTML form element tags would be <h:inputText>, <h:commandButton>, etc JavaServer Faces (JSF) | Atul Kahate 13
  • 14. Example <%@ page contentType="text/html" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <html> <body> <h:form> <h2>A simple JSF Page</h2> <h:inputText value="#{modelBean.username}" /> <h:commandButton value="Click here" /> </h:form> </body> </html> </f:view> JavaServer Faces (JSF) | Atul Kahate 14
  • 15. JSF UI Component Tree – 1 A JSF page like the above causes a UI component tree on the server, exactly matching with the components specified in the page HtmlInputText HtmlCommandButton HtmlForm UIViewRoot JavaServer Faces (JSF) | Atul Kahate 15
  • 16. JSF UI Component Tree – 2 Once a tree like the above is created and loaded in the server’s memory, it is possible to interact with the server-side UI components, and manipulate them directly JavaServer Faces (JSF) | Atul Kahate 16
  • 17. JSF Request Processing Lifecycle Sequence of events when a request is sent to a JSF page is called as the JSF request processing lifecycle, or simply JSF lifecycle Example: <h:inputText value=“#{modelBean.username}” /> This specifies that when the form is submitted, the value entered by the user in the input text box should be passed on to the corresponding property in the server-side JavaBean named modelBean JavaServer Faces (JSF) | Atul Kahate 17
  • 18. JSF Navigation Model – 1 View (JSF pages) Controller Model (Faces servlet) (Managed beans) JavaServer Faces (JSF) | Atul Kahate 18
  • 19. JSF Navigation Model – 2 Like Struts, JSF design is also based on an MVC approach Model is bound to methods and properties in the managed beans as specified in the faces- config.xml file Controller is a servlet, that responds to all requests that have a certain URL pattern, such as /faces/*, as defined in web.xml file The controller prepares an object, called as JSF context, which contains all accessible application data and routes the client to the appropriate view component (page) View is the set of JSF pages JavaServer Faces (JSF) | Atul Kahate 19
  • 20. JSF Navigation Model – 3 The navigation model is based on a set of navigation rules Example If something is a success then pass control to something-1; else to something-2 Achieved by specifying appropriate rules in the faces-config.xml file (See next slide) JavaServer Faces (JSF) | Atul Kahate 20
  • 21. JSF Navigation Model – 3 <navigation-rule> <from-view-id>/page1.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/page2.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/page3.jsp</to-view-id> </navigation-case> </navigation-rule> JavaServer Faces (JSF) | Atul Kahate 21
  • 22. JSF Case Study – Login D:Atul-personalLecturesSICSRWeb TechnologiesWT-2JSFJSF- SimpleLogin (in NetBeans) JavaServer Faces (JSF) | Atul Kahate 22
  • 23. Application Logic The application should accept the user ID and password from the user and display a welcome page The actual user ID and password logic would not be built in initially JavaServer Faces (JSF) | Atul Kahate 23
  • 24. index.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <html> <f:view> <head> <title>JSF Login Page Example</title> </head> <body bgcolor="pink"> <h:form> <h1 align="center">The Login Page</h1> <table border="1" bordecolor="maroon" cellspacing="1" cellpadding="1" align="center"> <tr> <td> <h:outputLabel for="txtName"> <h:outputText value="Name" /> </h:outputLabel> </td> <td><h:inputText id="txtName" value="#{UserBean.name}" /></td> </tr> <tr> <td> <h:outputLabel for="txtPassword"> <h:outputText value="Password" /> </h:outputLabel> </td> <td><h:inputSecret id="txtPassword" value="#{UserBean.password}" /></td> </tr> <tr align="center"> <td colspan="2"> <h:commandButton id="cmdLogin" value="Login" action="login" /> </td> </tr> </table> </h:form> </body> </html> </f:view> JavaServer Faces (JSF) | Atul Kahate 24
  • 25. Understanding the JSP – 1 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> These taglib directives refer to the JSTL tags jsf/core – Core library, contains custom action elements that represent JSF objects (which are independent of the page markup language) Jsf/html – HTML library, contains custom action elements that represent JSF objects (which are to be rendered as HTML elements) JavaServer Faces (JSF) | Atul Kahate 25
  • 26. Understanding the JSP – 2 <f:view> This is an action element A view in JSF is the grouping of components that make a specific UI screen The view contains an instance of the javax.faces.component.UIViewRoot class It does not display anything, but it is a container for other view components (e.g. input fields, buttons, etc) JavaServer Faces (JSF) | Atul Kahate 26
  • 27. Understanding the JSP – 3 <h:form> Represents a form component Acts as a container for all input components that hold values that needs to be processed together Examples: <h:inputText>, <h:inputSecret>, <h:commandButton> JavaServer Faces (JSF) | Atul Kahate 27
  • 28. Understanding the JSP – 4 <h:outputLabel for="txtName"> <h:outputText value="Name" /> </h:outputLabel> Identifies a component that generates an HTML label JavaServer Faces (JSF) | Atul Kahate 28
  • 29. Understanding the JSP – 5 <h:inputText id="txtName" value="#{UserBean.name}" /> Generates a text box with id txtName The value that user enters here would populate an attribute called as name of a server-side JavaBean titled UserBean JavaServer Faces (JSF) | Atul Kahate 29
  • 30. Understanding the JSP – 6 <h:commandButton id="cmdLogin" value="Login" action="login" /> Generates a command button with type as submit or reset The action attribute here has relevance, as explained later JavaServer Faces (JSF) | Atul Kahate 30
  • 31. How is this linked to the next page (welcome.jsp)? index.jsp … <h:commandButton id … action = “login” /> … faces-config.xml 1 … <navigation-rule> <from-view-id>/index.jsp<from-view-id> <navigation-case> 2 <from-outcome>login</from-outcome> <to-view-id>/welcome.jsp</to-view-id> 3 … welcome.jsp … <h:commandButton id … action = “login” /> … JavaServer Faces (JSF) | Atul Kahate 31
  • 32. UserBean.java /* * UserBean.java * * Created on September 25, 2007, 4:34 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.jsf.login; /** * * @author AtulK */ public class UserBean { private String name; private String password; public String getName() { return name; } public void setName(String userName) { name = userName; } public String getPassword() { return password; } public void setPassword(String userPassword) { password = userPassword; } JavaServer Faces (JSF) | } Atul Kahate 32
  • 33. Role of UserBean.java index.jsp <html> … <td><h:inputText id = “txtName” value = “#{UserBean.name}” /></td> … Whatever the user enters on the screen in the text box is passed to the JavaBean’s set method UserBean.java public class UserBean { private String name; … public String get ame () { return name; } public void set ame (String userName) { name = username; } … } JavaServer Faces (JSF) | Atul Kahate 33
  • 34. welcome.jsp <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <html> <f:view> <head> <title>Welcome to JSF!</title> </head> <body> <h:form> <h1 align="center"> <h:outputText id="txtUserName" value="Welcome #{UserBean.name}!" /> </h1> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 34
  • 35. Managed Beans and Navigation JavaServer Faces (JSF) | Atul Kahate 35
  • 36. Managed Beans We know that the model in MVC is many times made up of JavaBeans A JavaBean in JSF is called as a managed bean JavaServer Faces (JSF) | Atul Kahate 36
  • 37. Temperature Conversion JavaServer Faces (JSF) | Atul Kahate 37
  • 38. Requirement Accept temperature in Celsius and convert it into Fahrenheit D:Atul-personalLecturesSICSRWeb TechnologiesWT- 2JSFTemperatureConversion (or in NetBeans 6.0 JSF-Temperature- Conversion) JavaServer Faces (JSF) | Atul Kahate 38
  • 39. index.jsp <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <head> <title>Celsius converter</title> </head> <body> <f:view> <h:form> <table width="30%" height="30%" border="2" cellspacing="0" cellpadding="5"> <tr> <td colspan="2"> <h:message for="celsiusEdit" /> </td> </tr> <tr> <td> <h:inputText id="celsiusEdit" value="#{pageBean.celsius}"/> </td> <td><b> <h:outputText value="Celsius"/> </b></td> </tr> <tr> <td colspan="2"> <h:commandButton action="#{pageBean.convertToFahrenheit}" value="Convert"/> </td> </tr> <tr> <td> <h:outputText value="#{pageBean.fahrenheit}"/> </td> <td><b> <h:outputText value="Fahrenheit"/> </b></td> </tr> </table> </h:form> </f:view> </body> </html> JavaServer Faces (JSF) | Atul Kahate 39
  • 40. Understanding index.jsp – 1 <td colspan="2"> <h:message for="celsiusEdit" /> </td> Space reserved for possible error messages JavaServer Faces (JSF) | Atul Kahate 40
  • 41. Understanding index.jsp – 2 <td> <h:inputText id="celsiusEdit“ value="#{pageBean.celsius}"/> </td> Text box called as celsiusEdit would be created, which maps to the celsius property of the pageBean JavaServer Faces (JSF) | Atul Kahate 41
  • 42. Understanding index.jsp – 3 <td><b> <h:outputText value="Celsius"/> </b></td> HTML label would get created JavaServer Faces (JSF) | Atul Kahate 42
  • 43. Understanding index.jsp – 4 <td colspan="2"> <h:commandButton action="#{pageBean.convertToFahrenheit}" value="Convert"/> </td> An HTML button would created, which would call the convertToFahrenheit method of the pageBean JavaServer Faces (JSF) | Atul Kahate 43
  • 44. Understanding index.jsp – 5 <td> <h:outputText value="#{pageBean.fahrenheit}"/> </td> Would display the value of the property fahrenheit of the pageBean JavaServer Faces (JSF) | Atul Kahate 44
  • 45. Understanding index.jsp – 6 <td><b> <h:outputText value="Fahrenheit"/> </b></td> Would create a label JavaServer Faces (JSF) | Atul Kahate 45
  • 46. faces-config.xml <?xml version="1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd"> <faces-config> <managed-bean> <description> Simple backing bean. </description> <managed-bean-name>pageBean</managed-bean-name> <managed-bean-class>com.iflex.PageBean</managed-bean- class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config> JavaServer Faces (JSF) | Atul Kahate 46
  • 47. pageBean.java /* * PageBean.java * * Created on September 20, 2007, 5:28 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.iflex; public class PageBean { private Double celsius = null; private Double fahrenheit = null; public PageBean(){ System.out.println("PageBean()"); } public void setCelsius(Double celsius){ System.out.println("setCelsius"); this.celsius = celsius; } public Double getCelsius(){ System.out.println("getCelsius"); return celsius; } public void setFahrenheit(Double fahrenheit){ System.out.println("setFahrenheit"); this.fahrenheit = fahrenheit; } public Double getFahrenheit(){ System.out.println("getFahrenheit"); return fahrenheit; } public void convertToFahrenheit(){ System.out.println("convertToFahrenheit"); setFahrenheit(new Double(getCelsius().doubleValue() * 1.8 + 32)); } } JavaServer Faces (JSF) | Atul Kahate 47
  • 48. Exercises Modify the temperature conversion example by reversing the logic (accept temperature in F, convert to C) Accept the number of dollars the user has got, and convert that into the equivalent Indian Rupees (USD 1 = INR 43.10) NetBeans USDToINR Accept two numbers from the user and tell the user which is greater among the two NetBeans USDToINR JavaServer Faces (JSF) | Atul Kahate 48
  • 49. Message Bundles D:AtulLecturesSICSRWeb TechnologiesWT-2JSFJSF-More- Examples JavaServer Faces (JSF) | Atul Kahate 49
  • 50. What are Message Bundles? When we implement a Web application, it is a good idea to collect all message strings in a central location Helps keeping messages consistent and also makes in application localization/internationalization easier Example indexWindowTitle=Hi there! thankYouWindowTitle=Thank you for submitting your information JavaServer Faces (JSF) | Atul Kahate 50
  • 51. Using Message Bundle – Step 1 Add a properties file to your application (e.g. messages.properties file in Source packages -> com.corejsf) indexWindowTitle=Using Textfields and Textareas thankYouWindowTitle=Thank you for submitting your information thankYouPageTitle=Thank You! indexPageTitle=Please enter the following personal information namePrompt=Name: submitPrompt=Submit your information JavaServer Faces (JSF) | Atul Kahate 51
  • 52. Using Message Bundle – Step 2 Make references to properties defined earlier in your JSP as needed (index.jsp) <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <title> <h:outputText value = "#{msgs.indexWindowTitle}" /> </title> </head> <body> <h1><h:outputText value="#{msgs.indexPageTitle}" /></h1> <h:form> <table> <tr> <td> <h:outputText value = "#{msgs.namePrompt}" /> </td> <td> <h:inputText value = "#{user.name}" /> </td> </tr> </table> <h:commandButton value="#{msgs.submitPrompt}" action="thankYou" /> </h:form> </f:view> </body> </html> JavaServer Faces (JSF) | Atul Kahate 52
  • 53. Using Message Bundle – Step 3 The other JSP (thankYou.jsp) <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <html> <f:view> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> <h:outputText value = "#{msgs.thankYouWindowTitle}" /> </title> </head> <body> <h1><h:outputText value="#{msgs.namePrompt}" /> <h:outputText value="#{user.name}" /></h1> </f:view> </body> </html> JavaServer Faces (JSF) | Atul Kahate 53
  • 54. Using Message Bundle – Step 4 Code the Bean (UserBean.java) /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; /** * * @author atulk */ public class UserBean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } JavaServer Faces (JSF) | Atul Kahate 54
  • 55. Using Message Bundle – Step 5 Add references to the config file (faces-config.xml) <?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>com.corejsf.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <application> <resource-bundle> <base-name>com.corejsf.messages</base-name> <var>msgs</var> </resource-bundle> </application> </faces-config> JavaServer Faces (JSF) | Atul Kahate 55
  • 56. Various JSF UI-related Tags D:AtulLecturesSICSRWeb TechnologiesWT-2JSFJSF-More- Examples JavaServer Faces (JSF) | Atul Kahate 56
  • 57. index-UIExample.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value="#{msgs.indexWindowTitle}" /> </title> </head> <body> <h:outputText value="#{msgs.indexPageTitle}" styleClass="emphasis" /> <h:form> <table> <tr> <td> <h:outputText value="#{msgs.namePrompt}" /> </td> <td> <h:inputText value="#{form.name}" /> </td> </tr> <tr> <td> <h:outputText value="#{msgs.contactMePrompt}" /> </td> <td> <h:selectBooleanCheckbox value="#{form.contactMe}" /> </td> </tr> <tr> <td> <h:outputText value="#{msgs.bestDayPrompt}" /> </td> <td> <h:selectManyMenu value="#{form.bestDaysToContact}"> <f:selectItems value="#{form.daysOfTheWeekItems}" /> </h:selectManyMenu> </td> </tr> <tr> <td> <h:outputText value="#{msgs.yearOfBirthPrompt}" /> </td> <td> <h:selectOneListbox size="5" value="#{form.yearOfBirth}"> <f:selectItems value="#{form.yearItems}" /> </h:selectOneListbox> </td> </tr> <tr> <td> <h:outputText value="#{msgs.colorPrompt}" /> </td> <td> <h:selectManyCheckbox value="#{form.colors}"> <f:selectItems value="#{form.colorItems}" /> </h:selectManyCheckbox> </td> </tr> <tr> <td> <h:outputText value="#{msgs.languagePrompt}" /> </td> <td> <h:selectManyListbox value="#{form.languages}"> <f:selectItems value="#{form.languageItems}" /> </h:selectManyListbox> </td> </tr> <tr> <td> <h:outputText value="#{msgs.educationPrompt}" /> </td> <td> <h:selectOneRadio value="#{form.education}" layout="pageDirection"> <f:selectItems value="#{form.educationItems}" /> </h:selectOneRadio> </td> </tr> </table> <h:commandButton value="#{msgs.buttonPrompt}" action="showInformation" /> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 57
  • 58. showMoreInformation- UIExample.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value="#{msgs.indexWindowTitle}" /> </title> </head> <body> <h:outputFormat value="#{msgs.thankYouLabel}"> <f:param value="#{form.name}" /> </h:outputFormat> <p> <table> <tr> <td><h:outputText value="#{msgs.contactMeLabel}" /></td> <td><h:outputText value="#{form.contactMe}" /></td> </tr> <tr> <td><h:outputText value="#{msgs.bestDayLabel}" /></td> <td><h:outputText value="#{form.bestDaysConcatenated}" /></td> </tr> <tr> <td><h:outputText value="#{msgs.yearOfBirthLabel}" /></td> <td><h:outputText value="#{form.yearOfBirth}" /></td> </tr> <tr> <td><h:outputText value="#{msgs.languageLabel}" /></td> <td><h:outputText value="#{form.languagesConcatenated}" /></td> </tr> <tr> <td><h:outputText value="#{msgs.colorLabel}" /></td> <td><h:outputText value="#{form.colorsConcatenated}" /></td> </tr> <tr> <td><h:outputText value="#{msgs.educationLabel}" /></td> <td><h:outputText value="#{form.education}" /></td> </tr> </table> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 58
  • 59. faces-config.xml <?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/index-UIExample.jsp</from-view-id> <navigation-case> <from-outcome>showInformation</from-outcome> <to-view-id>/showMoreInformation-UIExample.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>com.corejsf.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>form</managed-bean-name> <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <application> <resource-bundle> <base-name>com.corejsf.messages</base-name> <var>msgs</var> </resource-bundle> </application> </faces-config> JavaServer Faces (JSF) | Atul Kahate 59
  • 60. RegisterForm.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; import java.text.DateFormatSymbols; import java.util.*; import javax.faces.model.SelectItem; /** * * @author atulk */ public class RegisterForm { enum Education { HIGH_SCHOOL, BACHELOR, MASTER, DOCTOR }; private String name; private boolean contactMe; private Integer [] bestDaysToContact; private Integer yearOfBirth; private String [] colors; private String [] languages; private Education education; public Integer [] getBestDaysToContact () { return bestDaysToContact; } public void setBestDaysToContact(Integer[] bestDaysToContact) { this.bestDaysToContact = bestDaysToContact; } public String[] getColors() { return colors; } public void setColors(String[] colors) { this.colors = colors; } public boolean isContactMe() { return contactMe; } public void setContactMe(boolean contactMe) { this.contactMe = contactMe; } public Education getEducation() { return education; } public void setEducation(Education education) { this.education = education; } public String[] getLanguages() { return languages; } public void setLanguages(String[] languages) { this.languages = languages; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getYearOfBirth() { return yearOfBirth; } public void setYearOfBirth(Integer yearOfBirth) { this.yearOfBirth = yearOfBirth; } public Collection <SelectItem> getYearItems () { return birthYears; } public SelectItem [] getDaysOfTheWeekItems () { return daysOfTheWeek; } public Map <String, Object> getLanguageItems () { return languageItems; } public SelectItem [] getColorItems () { return colorItems; } public SelectItem [] getEducationItems () { return educationItems; } public String getBestDaysConcatenated () { return concatenate (bestDaysToContact); } public String getLanguagesConcatenated () { return concatenate (languages); } public String getColorsConcatenated () { return concatenate (colors); } private static String concatenate (Object [] values) { if (values == null) { return ""; } StringBuilder r = new StringBuilder(); for (Object value : values) { if (r.length () > 0) { r.append(','); } r.append(value.toString()); } return r.toString(); } private static SelectItem [] colorItems = { new SelectItem ("Red"), new SelectItem ("Blue"), new SelectItem ("Yellow"), new SelectItem ("Green"), new SelectItem ("Orange"), new SelectItem ("White"), new SelectItem ("Black"), new SelectItem ("Grey") }; private static SelectItem [] educationItems = { new SelectItem (Education.HIGH_SCHOOL, "High School"), new SelectItem (Education.BACHELOR, "Bachelor's"), new SelectItem (Education.MASTER, "Master's"), new SelectItem (Education.DOCTOR, "Doctorate") }; private static Map <String, Object> languageItems; static { languageItems = new LinkedHashMap <String, Object> (); languageItems.put ("English", "en"); languageItems.put ("French", "fr"); languageItems.put ("Russian", "ru"); languageItems.put ("Italian", "it"); languageItems.put ("Spanis", "es"); } private static Collection <SelectItem> birthYears; static { birthYears = new ArrayList <SelectItem> (); for (int i = 1900; i < 2000; i++) { birthYears.add (new SelectItem (i)); } } private static SelectItem [] daysOfTheWeek; static { DateFormatSymbols symbols = new DateFormatSymbols (); String [] weekdays = symbols.getWeekdays (); daysOfTheWeek = new SelectItem [7]; for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { daysOfTheWeek [i - 1] = new SelectItem (new Integer (i), weekdays [i]); } } } JavaServer Faces (JSF) | Atul Kahate 60
  • 61. messages.properties # To change this template, choose Tools | Templates # and open the template in the editor. indexWindowTitle=Using JSF UI Features indexPageTitle=Please enter the following information namePrompt=Name: contactMePrompt=Contact me bestDayPrompt=What is the best day to contact you? yearOfBirthPrompt=What year were you born? buttonPrompt=Submit information languagePrompt=Select the languages you speak: educationPrompt=Select your highest education level: emailAppPrompt=Select your email application: colorPrompt=Select your favourite colors: thankYouLabel=Thank you {0}, for your information contactMeLabel=Contact me: bestDayLabel=Best day to contact you: yearOfBirthLabel=Your year of birth: colorLabel=Colors: languageLabel=Languages: educationLabel=Education: JavaServer Faces (JSF) | Atul Kahate 61
  • 62. Messages JavaServer Faces (JSF) | Atul Kahate 62
  • 63. JSF Messages During the JSF life cycle, any object can create a message and add it to a queue of messages maintained by the faces context At the end of the life cycle (i.e. in the Render Response phase), we can display those messages in a view Usually, messages are associated with a UI component and are used to show validation errors JavaServer Faces (JSF) | Atul Kahate 63
  • 64. Message Types Information Warning Error Fatal JavaServer Faces (JSF) | Atul Kahate 64
  • 65. Message Details All messages can contain a summary and a detail Example: summary could be Invalid entry and detail could be Age > 100 is not accepted Two JSF tags are used for message handling: h:messages (Multiple messages for a component) h:message (Only a single message for a component) They have many attributes, such as errorClass, errorStyle, fatalClass, tooltip, etc JavaServer Faces (JSF) | Atul Kahate 65
  • 66. index-messageExample.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.indexWindowTitle}" /> </title> </head> <body> <h1><h:outputText value="#{msgs.indexPageTitle}" /></h1> <h:form> <h:outputText value="#{msgs.greeting}" styleClass="emphasis" /> <br /> <h:messages errorClass="errors" layout="table" /> <br /> <table> <tr> <td> <h:outputText value = "#{msgs.namePrompt}" /> </td> <td> <h:inputText value = "#{ageCheck.name}" required="true" label="#{msgs.namePrompt}" /> </td> <td> <h:message for="name" errorClass="errors" /> </td> </tr> <tr> <td> <h:outputText value = "#{msgs.agePrompt}" /> </td> <td> <h:inputText value = "#{ageCheck.age}" required="true" size="3" label="#{msgs.agePrompt}" /> </td> <td> <h:message for="age" errorClass="errors" /> </td> </tr> </table> <h:commandButton value="#{msgs.submitPrompt}" action="thankYou" /> </h:form> </f:view> </body> </html> JavaServer Faces (JSF) | Atul Kahate 66
  • 67. thankYou- messageExample.jsp <%-- Document : thankYou-messageExample Created on : May 5, 2008, 3:26:50 PM Author : atulk --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Thank You</title> </head> <body> <h2>Thanks for entering the required information!</h2> </body> </html> JavaServer Faces (JSF) | Atul Kahate 67
  • 68. AgeCheckBean.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; /** * * @author atulk */ public class AgeCheckBean { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } JavaServer Faces (JSF) | Atul Kahate 68
  • 69. messages.properties # To change this template, choose Tools | Templates # and open the template in the editor. greeting=Please fill out the following details indexWindowTitle=Using JSF UI Features indexPageTitle=Please enter the following information namePrompt=Name: contactMePrompt=Contact me bestDayPrompt=What is the best day to contact you? yearOfBirthPrompt=What year were you born? buttonPrompt=Submit information languagePrompt=Select the languages you speak: educationPrompt=Select your highest education level: emailAppPrompt=Select your email application: colorPrompt=Select your favourite colors: agePrompt=Age: submitPrompt=Submit form thankYouLabel=Thank you {0}, for your information contactMeLabel=Contact me: bestDayLabel=Best day to contact you: yearOfBirthLabel=Your year of birth: colorLabel=Colors: languageLabel=Languages: educationLabel=Education: JavaServer Faces (JSF) | Atul Kahate 69
  • 70. faces-config.xml <?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/index-UIExample.jsp</from-view-id> <navigation-case> <from-outcome>showInformation</from-outcome> <to-view-id>/showMoreInformation-UIExample.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/index-messageExample.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou-messageExample.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>com.corejsf.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>ageCheck</managed-bean-name> <managed-bean-class>com.corejsf.AgeCheckBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>form</managed-bean-name> <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <application> <resource-bundle> <base-name>com.corejsf.messages</base-name> <var>msgs</var> </resource-bundle> </application> </faces-config> JavaServer Faces (JSF) | Atul Kahate 70
  • 71. Panels JavaServer Faces (JSF) | Atul Kahate 71
  • 72. What are Panels? Normally we use HTML tables to align form prompts and messages It is error-prone and tedious Hence, JSF introduces h:panelGrid, which generates a table element <h:panelGrid columns=“3”> … </h:panelGrid> JavaServer Faces (JSF) | Atul Kahate 72
  • 73. Note about columns The columns attribute is optional – defaults to 1 If specified, UI components are placed from left to right and top to bottom Example: If we specify columns as 3 and we have 9 components, we will get a panel grid with 3 rows and 3 columns – instead, if we have 10 components, we will have 4 rows and 3 columns (last two columns in the fourth row would be empty) JavaServer Faces (JSF) | Atul Kahate 73
  • 74. index-panelGrid.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.indexWindowTitle}" /> </title> </head> <body> <h1><h:outputText value="#{msgs.indexPageTitle}" /></h1> <h:form> <h:panelGrid columns="2" rowClasses="oddRows, evenRows" border="2"> <h:outputText value = "#{msgs.namePrompt}" /> <h:panelGroup> <h:inputText id="name" value="#{ageCheck.name}" required="true" label="#{msgs.namePrompt}" /> <h:message for="name" errorClass="errors" /> </h:panelGroup> <h:outputText value = "#{msgs.agePrompt}" /> <h:inputText id="age" value="#{ageCheck.age}" size="3" label="#{msgs.agePrompt}" required= "true"/> <h:message for="age" errorClass="errors" /> </h:panelGrid> <h:commandButton value="#{msgs.submitPrompt}" action="thankYou" /> </h:form> </f:view> </body> </html> JavaServer Faces (JSF) | Atul Kahate 74
  • 75. faces-config.xml <?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/index-UIExample.jsp</from-view-id> <navigation-case> <from-outcome>showInformation</from-outcome> <to-view-id>/showMoreInformation-UIExample.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/index-messageExample.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou-messageExample.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/index-panelGrid.jsp</from-view-id> <navigation-case> <from-outcome>thankYou</from-outcome> <to-view-id>/thankYou-messageExample.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>com.corejsf.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>ageCheck</managed-bean-name> <managed-bean-class>com.corejsf.AgeCheckBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>form</managed-bean-name> <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <application> <resource-bundle> <base-name>com.corejsf.messages</base-name> <var>msgs</var> </resource-bundle> </application> </faces-config> JavaServer Faces (JSF) | Atul Kahate 75
  • 76. Data Tables JavaServer Faces (JSF) | Atul Kahate 76
  • 77. Data Table <h:dataTable> tag is used to deal with tabular data Iterates over data to create an HTML table <h:dataTable value’#{items}’ var=‘item’> <h:column> <h:output_text value=‘#{item.propertyName}’> </h:column> <h:column> <h:output_text value=‘#{item.propertyName}’> </h:column> … </h:dataTable> Only <h:column> is allowed inside the body of <h:dataTable> JavaServer Faces (JSF) | Atul Kahate 77
  • 78. Allowed sources of data Java object Array An instance of java.util.List An instance of java.sql.ResultSet An instance of javax.servlet.jsp.jstl.sql.Result An instance of javax.faces.model.DataModel JavaServer Faces (JSF) | Atul Kahate 78
  • 79. index-dataTable-1.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <title> <h:outputText value = "#{msgs.indexMessageTitle}" /> </title> </head> <body> <h1><h:outputText value="#{msgs.indexMessageTitle}" /></h1> <p /> <h:form> <h:dataTable value="#{tableData.names}" var="name"> <h:column> <h:outputText value="#{name.last}" /> </h:column> <h:column> <h:outputText value="#{name.first}" /> </h:column> </h:dataTable> </h:form> </f:view> </body> </html> JavaServer Faces (JSF) | Atul Kahate 79
  • 80. TableData.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; /** * * @author atulk */ public class TableData { private static final Name [] names = new Name [] { new Name ("Atul", "Kahate"), new Name ("Dinesh", "Samant"), new Name ("Umesh", "Aherwadikar"), new Name ("Parag", "Chincholkar") }; public Name [] getNames () { return names; } } JavaServer Faces (JSF) | Atul Kahate 80
  • 81. Name.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; /** * * @author atulk */ public class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public void setFirst (String first) { this.first = first; } public String getFirst () { return first; } public void setLast (String last) { this.last = last; } public String getLast () { return last; } } JavaServer Faces (JSF) | Atul Kahate 81
  • 82. dataTable with Headers and Footers JavaServer Faces (JSF) | Atul Kahate 82
  • 83. index-dataTable-2.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.windowTitle1}" /> </title> </head> <body> <h:form> <h:dataTable value="#{tableData.names}" var="name" captionStyle="font-size: 0.95em; font-style: italic" style="width: 250px;"> <f:facet name="caption"> <h:outputText value="An array of names: "/> </f:facet> <h:column headerClass="columnHeader" footerClass="columnFooter"> <f:facet name="header"> <h:outputText value="#{msgs.lastnameColumn}" /> </f:facet> <h:outputText value="#{name.last}" /> <f:facet name="footer"> <h:outputText value="#{msgs.alphanumeric}" /> </f:facet> </h:column> <h:column headerClass="columnHeader" footerClass="columnFooter"> <f:facet name="header"> <h:outputText value="#{msgs.firstnameColumn}" /> </f:facet> <h:outputText value="#{name.first}" /> <f:facet name="footer"> <h:outputText value="#{msgs.alphanumeric}" /> </f:facet> </h:column> </h:dataTable> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 83
  • 84. messages.properties # To change this template, choose Tools | Templates # and open the template in the editor. greeting=Please fill out the following details indexWindowTitle=Using JSF UI Features indexPageTitle=Please enter the following information indexMessageTitle=This is for your information windowTitle1=Headers, Footers, and Captions namePrompt=Name: contactMePrompt=Contact me bestDayPrompt=What is the best day to contact you? yearOfBirthPrompt=What year were you born? buttonPrompt=Submit information languagePrompt=Select the languages you speak: educationPrompt=Select your highest education level: emailAppPrompt=Select your email application: colorPrompt=Select your favourite colors: agePrompt=Age: submitPrompt=Submit form thankYouLabel=Thank you {0}, for your information contactMeLabel=Contact me: bestDayLabel=Best day to contact you: yearOfBirthLabel=Your year of birth: colorLabel=Colors: languageLabel=Languages: educationLabel=Education: lastnameColumn=Last Name firstnameColumn=First Name editColumn=edit alphanumeric=[alpha] JavaServer Faces (JSF) | Atul Kahate 84
  • 85. dataTable – Allow Edits JavaServer Faces (JSF) | Atul Kahate 85
  • 86. index-dataTable-3.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.windowTitle2}" /> </title> </head> <body> <h:form> <h:dataTable value="#{tableData.names}" var="name" captionStyle="font-size: 0.95em; font-style: italic" style="width: 250px;"> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.editColumn}" style="font-weight:bold" /> </f:facet> <h:selectBooleanCheckbox value="#{name.editable}" onclick="submit()" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.lastnameColumn}" style="font-weight: bold" /> </f:facet> <h:inputText value="#{name.last}" rendered="#{name.editable}" size="10" /> <h:outputText value="#{name.last}" rendered="#{not name.editable}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.firstnameColumn}" style="font-weight:bold" /> </f:facet> <h:inputText value="#{name.first}" rendered="#{name.editable}" size="10" /> <h:outputText value="#{name.first}" rendered="#{not name.editable}" /> </h:column> </h:dataTable> <h:commandButton value="#{msgs.saveChangesButtonText}" /> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 86
  • 87. Name.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; /** * * @author atulk */ public class Name { private String first; private String last; private boolean editable = false; public Name(String first, String last) { this.first = first; this.last = last; } public void setFirst (String first) { this.first = first; } public String getFirst () { return first; } public void setLast (String last) { this.last = last; } public String getLast () { return last; } public boolean getEditable () { return editable; } } JavaServer Faces (JSF) | Atul Kahate 87
  • 88. Database Tables JavaServer Faces (JSF) | Atul Kahate 88
  • 89. Database Tables – Usage The JDF data table component is a good fit for showing data stored in a database For this purpose, we need to write a managed bean, which will perform the JDBC operations to bring the data of interest JavaServer Faces (JSF) | Atul Kahate 89
  • 90. CustomerBean.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; import java.sql.*; import javax.servlet.jsp.jstl.sql.Result; import javax.servlet.jsp.jstl.sql.ResultSupport; import javax.sql.DataSource; /** * * @author atulk */ public class CustomerBean { private Connection con; public void open () throws SQLException { if (con != null) { return; } con = DriverManager.getConnection ("jdbc:derby://localhost:1527/customer"); } public Result getAll () throws SQLException { try { open (); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("SELECT * FROM customers"); return ResultSupport.toResult(rs); } finally { close (); } } public void close () throws SQLException { if (con != null) { con.close(); con = null; } } } JavaServer Faces (JSF) | Atul Kahate 90
  • 91. index-dataTable-4.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.windowTitle2}" /> </title> </head> <body> <h:form> <h:dataTable value="#{customer.all}" var="customer" styleClass="customers" headerClass="customersHeader" rowClasses="oddRow,evenRow" columnClasses="custid,name"> <!-- Only one of the row/column classes would work --> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.customerIdHeader}" /> </f:facet> <h:outputText value="#{customer.cust_ID}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.nameHeader}" /> </f:facet> <h:outputText value="#{customer.name}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.phoneHeader}" /> </f:facet> <h:outputText value="#{customer.phone_number}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.addressHeader}" /> </f:facet> <h:outputText value="#{customer.street_address}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.cityHeader}" /> </f:facet> <h:outputText value="#{customer.city}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="#{msgs.stateHeader}" /> </f:facet> <h:outputText value="#{customer.state}" /> </h:column> </h:dataTable> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 91
  • 92. styles.css /* Document : styles Created on : May 5, 2008, 4:02:56 PM Author : atulk Description: Purpose of the stylesheet follows. */ /* TODO customize this sample style Syntax recommendation http://www.w3.org/TR/REC-CSS2/ */ body { background: #eee; } .emphasis { font-size: 1.3em; } .errors { font-style: italic; } .evenRows { background: PowderBlue; } .oddRows { background: MediumTurquoise; } .customers { border: thin solid black; } .customersHeader { text-align: center; font-style:italic; color: Snow; background: Teal; } .custid { height: 25px; text-align: center; background: MediumTurquoise; } .name { text-align: center; background: PowderBlue; } .evenRow { background: PowderBlue; } .oddRow { background: MediumTurquoise; } JavaServer Faces (JSF) | Atul Kahate 92
  • 93. Conversion and Validation JavaServer Faces (JSF) | Atul Kahate 93
  • 94. Overview of Conversion and Validation Two-step process Convert into local value (i.e. from request object’s string to whatever data type the model expects) and then validate If ok, update model (i.e. set the bean properties with the request values) JavaServer Faces (JSF) | Atul Kahate 94
  • 95. Using Standard Convertors (JSF-Convertors-and-Validators in NetBeans) JavaServer Faces (JSF) | Atul Kahate 95
  • 96. Numbers and Dates Suppose we want to accept the amount, card number, and card expiry date for a payment What would happen if we code our JSP, bean etc as follows? Try running it JavaServer Faces (JSF) | Atul Kahate 96
  • 97. convertor-example-1- original.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.indexTitle1}" /> </title> </head> <body> <h:form> <h1><h:outputText value="#{msgs.bodyTitle1}" /></h1> <h:panelGrid columns="2" border="2" cellpadding="5" rowClasses="oddRows,evenRows"> <h:outputLabel value="#{msgs.amountPrompt}: " /> <h:inputText id="amount" value="#{payment.amount}“ /> <h:outputLabel value="#{msgs.cardNumberPrompt}: " /> <h:inputText id="cardNumber" value="#{payment.cardNumber}" /> <h:outputLabel value="#{msgs.expiryDatePrompt}: " /> <h:inputText id="expiryDate" value="#{payment.expiryDate}“ /> </h:panelGrid> <br /> <h:commandButton value="#{msgs.submitPrompt}" action = "submit" /> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 97
  • 98. PaymentBean.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejsf; import java.util.Date; /** * * @author atulk */ public class PaymentBean { private float amount; private String cardNumber; private Date expiryDate; public float getAmount() { return amount; } public void setAmount(float amount) { this.amount = amount; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public Date getExpiryDate() { return expiryDate; } public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } } JavaServer Faces (JSF) | Atul Kahate 98
  • 99. faces-config.xml <?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <navigation-rule> <from-view-id>/convertor-example-1.jsp</from-view-id> <navigation-case> <from-outcome>submit</from-outcome> <to-view-id>/convertor-example-1-output.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>payment</managed-bean-name> <managed-bean-class>com.corejsf.PaymentBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <application> <resource-bundle> <base-name>com.corejsf.messages</base-name> <var>msgs</var> </resource-bundle> </application> </faces-config> JavaServer Faces (JSF) | Atul Kahate 99
  • 100. messages.properties indexTitle1=Payment Information Processing bodyTitle1=Enter payment information amountPrompt=Amount cardNumberPrompt=Card Number expiryDatePrompt=Expiry Date submitPrompt=Submit JavaServer Faces (JSF) | Atul Kahate 100
  • 101. styles.css /* Document : styles Created on : May 12, 2008, 11:37:01 AM Author : atulk Description: Purpose of the stylesheet follows. */ /* TODO customize this sample style Syntax recommendation http://www.w3.org/TR/REC-CSS2/ */ body { background: #eee; } .evenRows { background-color: silver; } .oddRows { background: MediumTurquoise; } JavaServer Faces (JSF) | Atul Kahate 101
  • 102. convertor-example-1- output.jsp <%-- Document : convertor-example-1-output Created on : May 12, 2008, 11:03:02 AM Author : atulk --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h2>Hello World!</h2> </body> </html> JavaServer Faces (JSF) | Atul Kahate 102
  • 103. What is the result? In the Glassfish output, we would notice conversion errors The screen would not move to the next page How do we fix this? Use convertors (see modified JSP on the next slide) JavaServer Faces (JSF) | Atul Kahate 103
  • 104. convertor-example-1.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.indexTitle1}" /> </title> </head> <body> <h:form> <h1><h:outputText value="#{msgs.bodyTitle1}" /></h1> <h:panelGrid columns="2" border="2" cellpadding="5" rowClasses="oddRows,evenRows"> <h:outputLabel value="#{msgs.amountPrompt}: " /> <h:inputText id="amount" value="#{payment.amount}"> <f:convertNumber minFractionDigits="2" /> </h:inputText> <h:outputLabel value="#{msgs.cardNumberPrompt}: " /> <h:inputText id="cardNumber" value="#{payment.cardNumber}" /> <h:outputLabel value="#{msgs.expiryDatePrompt}: " /> <h:inputText id="expiryDate" value="#{payment.expiryDate}"> <f:convertDateTime pattern="MM/yyyy" /> </h:inputText> </h:panelGrid> <br /> <h:commandButton value="#{msgs.submitPrompt}" action = "submit" /> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 104
  • 105. Result now? We have added convertors as follows: <h:inputText value=“#{payment.amount}”> <f:convertNumber minFractionDigits=“2” /> </h:inputText> AND <h:inputText value=“#{payment.date}”> <f:convertDateTime pattern=“MM/yyyy” /> </h:inputText> They ensure correct input JavaServer Faces (JSF) | Atul Kahate 105
  • 106. Conversion even in the output! convertor-example-1-output.jsp <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <f:view> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title> <h:outputText value = "#{msgs.indexTitle2}" /> </title> </head> <body> <h:form> <h1><h:outputText value="#{msgs.bodyTitle2}" /></h1> <h:panelGrid columns="2" border="2" cellpadding="5" rowClasses="oddRows,evenRows"> <h:outputLabel value="#{msgs.amountPrompt}: " /> <h:outputText value="#{payment.amount}"> <f:convertNumber type="currency"/> </h:outputText> <h:outputLabel value="#{msgs.cardNumberPrompt}: " /> <h:outputText id="cardNumber" value="#{payment.cardNumber}" /> <h:outputLabel value="#{msgs.expiryDatePrompt}: " /> <h:outputText id="expiryDate" value="#{payment.expiryDate}"> <f:convertDateTime pattern="MM/dd/yyyy"/> </h:outputText> </h:panelGrid> <br /> <h:commandButton value="#{msgs.submitPrompt}" action = "submit" /> </h:form> </body> </f:view> </html> JavaServer Faces (JSF) | Atul Kahate 106
  • 107. Thank You! JavaServer Faces (JSF) | Atul Kahate 107