Web-Tier Codecamp JavaServer Faces, AJAX, Java Studio Creator by fso56144

VIEWS: 36 PAGES: 129

									Web-Tier Codecamp:
JavaServer Faces,
AJAX,
Java Studio Creator
Sang Shin
sang.shin@sun.com
Technology Evangelist
Sun Microsystems, Inc.
Agenda
• JavaServer Faces (JSF)
  > Quick introduction
  > Development steps
  > Key concepts: UI component model, Request processing life-
      cycle, Event handling, Rendering
• AJAX
  > What is and Why AJAX?
  > Technologies used in AJAX
  > Anatomy of AJAX interaction
  > Best practice guidelines
  > Issues and Futures
• AJAX and JSF: Perfect Marriage
                                                                 2
JavaServer Faces(JSF):
Quick Introduction
JavaServer™ Faces (JSF)
Framework Is…


  A server side user interface (UI)
  component framework for Java™
  technology-based web
  applications.

  Drag-and-drop UI components to
  build a web Application.

                                      4
What is JavaServer Faces?
• Next generation Web application framework
  based on component model
  >   UI Components
  >   Events-based interaction model
  >   Back-end-data integration
  >   Rendering model
  >   Validation, Internationalization, Navigation (similar to
      Struts)
• Designed to be leveraged by tools (as opposed to
  be used by developers directly)
  > Sun Java Studio Creator
                                                                 5
JavaServer Faces(JSF):
Development Steps
Sample JSP Application we are
going to build
• guessNumber application that comes with JSF
  1.0 as part of J2EE 1.4 SDK
• Guess a number between 0 and 10, inclusive
  > The response page tells you if you guessed correctly
• Input validation




                                                           7
Starting Page




                8
Failure Outcome Navigation




                             9
Success Outcome Navigation




                             10
Input Validation Error




                         11
Steps for Developing JSF Application
1. Develop Model objects (Managed Beans)
  > Model objects hold the data
  > Validator, convertor, event handler
2. Add managed bean declarations
  > To the application configuration file
3.Create the JSP Pages
  > Using the UI component and JSF tags
4. Define Page Navigation
  > In the application configuration file (faces-config.xml)
5.Create message resource file
                                                               12
Step 1: Develop Model Objects
• Model object holds data from UI
  > It is a JavaBean
  > JSF runtime keeps the bean’s data in sync with the UI
• May contain
  > action methods
  > event handlers
  > custom validator
• Responsibility of application developer
  > Page author and the application developer need to work
    in tandem to make sure that the UI component tags refer
    to the proper properties of the model objects
                                                              13
Model object: UserNumberBean
public class UserNumberBean {
  Integer userNumber = null;
  Integer randomInt = null;
  String response = null;
  public UserNumberBean () {
      Random randomGR = new Random();
      randomInt = new Integer(randomGR.nextInt(10));
      System.out.println("Duke's number: "+randomInt);
  }
  public void setUserNumber(Integer user_number) {
    userNumber = user_number;
    System.out.println("Set userNumber " + userNumber);
  }
  public Integer getUserNumber() {
    System.out.println("get userNumber " + userNumber);
    return userNumber;
  }
                                                          14
Properties of Model Object
• JSF implementation automatically convert the
  data to the type specified by the model object
  property
  > You can also apply a customer converter to a
    component to convert the components value to a type
    not supported by the component
• Properties of a Model object is directly
  addressible in a JSP page
  > #{BeanName.PropertyName}



                                                          15
 Step 2: Add Managed Bean
 Declarations to App. Conf. File
• JSF implementation processes Application
  Configuration File on application startup time
  and initializes the UserNumberBean and stores
  it in a scope object if no instance exists
  > Bean is then available for all pages in the application
  > Similar to Bean Factory in the Spring Framework
• Creation and lifetime is managed by JSF
  runtime
  > No need for <jsp:useBean> tag

                                                              16
UserNumberBean in faces-config.xml
<managed-bean>
 <description>
  The "Model file" bean that backs up the guessNumber webapp
 </description>
 <managed-bean-name>UserNumberBean</managed-bean-name>
 <managed-bean-class>guessNumber.UserNumberBean</managed-bean-class>
 <managed-bean-scope>session</managed-bean-scope>
 <managed-property>
  <property-name>minimum</property-name>
  <property-class>java.lang.Long</property-class>
  <value>0</value>
 </managed-property>
 <managed-property>
  <property-name>maximum</property-name>
  <property-class>java.lang.Long</property-class>
  <value>10</value>
 </managed-property>
</managed-bean>
                                                                       17
Step 3: Create Pages
• Page author's responsibility
• Involves
  > Laying out JSF UI components on the pages
     > <h:outputText>, <h:inputText>, <h:commandButton>
     > <h:inputText> not <input type=”text”>
     > <h:commandButton> not <input type=”submit”>
  > Mapping the components to model object data
     > #{UserNumberBean.minimum}
  > Add validators and event listeners on any form
    components
     > validator="#{UserNumberBean.validate}"

                                                          18
 greeting.jsp (1)
<HTML>
  <HEAD> <title>Hello</title> </HEAD>
  <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
  <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
  <body bgcolor="white">




                                                                19
greeting.jsp (2)

 <f:view>
  <h:form id="helloForm" >
    <h2>Hi. My name is Duke. I'm thinking of a number from
     <h:outputText value="#{UserNumberBean.minimum}"/> to
     <h:outputText value="#{UserNumberBean.maximum}"/>.
     Can you guess it?
    </h2>
   <h:graphicImage id="waveImg" url="/wave.med.gif" />
   <h:inputText id="userNo" value="#{UserNumberBean.userNumber}"
              validator="#{UserNumberBean.validate}"/>
   <h:commandButton id="submit" action="success" value="Submit" />
   <p>
   <h:messages style="color: red; font-family: 'New Century Schoolbook', serif;
      font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>
  </h:form>
 </f:view>
</HTML>

                                                                                    20
greeting.jsp (2) in
(Input Validation Error)
 <f:view>
  <h:form id="helloForm" >
    <h2>Hi. My name is Duke. I'm thinking of a number from
     <h:outputText value="#{UserNumberBean.minimum}"/> to
     <h:outputText value="#{UserNumberBean.maximum}"/>.
     Can you guess it?
    </h2>
   <h:graphic_image id="waveImg" url="/wave.med.gif" />
   <h:inputText id="userNo" value="#{UserNumberBean.userNumber}"
              validator="#{UserNumberBean.validate}"/>
   <h:commandButton id="submit" action="success" value="Submit" />
   <p>
   <h:messages style="color: red; font-family: 'New Century Schoolbook', serif;
      font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>
  </h:form>
 </f:view>
</HTML>

                                                                                    21
response.jsp with wrong guess
<HTML>
 <HEAD> <title>Guess The Number</title> </HEAD>
 <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
 <body bgcolor="white">
 <f:view>
 <h:form id="responseForm" >
    <h:graphicImage id="waveImg" url="/wave.med.gif" />
 <h2><h:outputText id="result"
                  value="#{UserNumberBean.response}"/></h2>
 <h:commandButton id="back" value="Back" action="success"/><p>
  </h:form>
  </f:view>
</HTML>




                                                                 22
response.jsp with correct guess
<HTML>
 <HEAD> <title>Guess The Number</title> </HEAD>
 <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
 <body bgcolor="white">
 <f:view>
 <h:form id="responseForm" >
    <h:graphicImage id="waveImg" url="/wave.med.gif" />
 <h2><h:outputText id="result"
                  value="#{UserNumberBean.response}"/></h2>
 <h:commandButton id="back" value="Back" action="success"/><p>
  </h:form>
  </f:view>
</HTML>




                                                                 23
Step 4: Define Page Navigation

• Application developer responsibility
  > Navigation rules are defined in the application
    configuration file (faces-config.xml)
• Navigation rules
  > Determine which page to go to after the user clicks a
    button or a hyperlink
  > Based on a logical “outcome”
  > Works pretty much the same way in Struts




                                                            24
Navigation Rule 1 for
guessNumber Example
<navigation-rule>
 <description>
    The decision rule used by the NavigationHandler to
    determine which view must be displayed after the
    current view, greeting.jsp is processed.
 </description>
 <from-view-id>/greeting.jsp</from-view-id>
 <navigation-case>
    <description>
      Indicates to the NavigationHandler that the response.jsp
      view must be displayed if the Action referenced by a
      UICommand component on the greeting.jsp view returns
      the outcome "success".
    </description>
  <from-outcome>success</from-outcome>
  <to-view-id>/response.jsp</to-view-id>
 </navigation-case>
</navigation-rule>


                                                                 25
Navigation Rule 2 for
guessNumber Example
<navigation-rule>
 <description>
    The decision rules used by the NavigationHandler to
    determine which view must be displayed after the
    current view, response.jsp is processed.
 </description>
 <from-view-id>/response.jsp</from-view-id>
 <navigation-case>
    <description>
       Indicates to the NavigationHandler that the greeting.jsp
       view must be displayed if the Action referenced by a
       UICommand component on the response.jsp view returns
       the outcome "success".
    </description>
    <from-outcome>success</from-outcome>
    <to-view-id>/greeting.jsp</to-view-id>
 </navigation-case>
</navigation-rule>


                                                                  26
JavaServer Faces(JSF):
Demo
Demo Scenario
• Building JSF application fresh using NetBeans
  > Using JSF template
  > Code completion of JSF tags in a JSP page




                                                  28
JavaServer Faces(JSF):
Key Concepts
Key Concepts of JavaServer Faces
• UI Component model
• Request processing life-cycle
  >   Conversion
  >   Validation
  >   Binding to model objects
  >   Navigation
• Event handling
• Rendering


                                  30
JSF Architecture
                        Server
                        JSF Page
Desktop   HTML
                            HTML
Browser                     RenderKit



                Front                   App
                ctrl      JSF Page      Backend


                            WML
                            RenderKit
Phone
          WML



                                                  31
JavaServer Faces(JSF):
Key Concepts:
UI Component
What is a UI Component?
• A well defined, familiar idiom for UI design
• Are configurable, reusable elements that compose
  the user interfaces of JSF applications
• Can be simple, like a button, or compound, like a
  table, which can be composed of multiple
  components
• Extensible through composition, adding new
  components
• Accessible via JSF custom tags in JSP page

                                                      33
JSF UI Component Model
• A set of UIComponent classes for specifying the
  state and behavior of UI components
• An event and listener model that defines how to
  handle component events
• A conversion model that defines how to plug in data
  converters onto a component
• A validation model that defines how to register
  validators onto a component



                                                        34
   UI Components




            +
 Form, Text, CheckBox,
Radio Button, Option List,
   Button,Label, Grid,
        Tree, etc.
                             35
How UI Component classes are
used by Page authors?
• Most page authors and application developers
  will not have to use these classes directly
  > They will instead include the components on a page by
    using the component's corresponding tags
• Most of these component tags can be rendered in
  different ways
  > For example, a UICommand component can be rendered
    as a button or a hyperlink using different tags
  > <h:commandButton id="submit" action="success"
    value="Submit" />
  > <h:commandLink ... >
                                                            36
JavaServer Faces(JSF):
Key Concepts:
Request Processing
Life-Cycle
Request Processing Life-Cycle




                                38
Request Processing Lifecycle Phases
1. Reconstitute component tree phase
2. Apply request values phase
3. Process validations phase
4. Update model values phase
5. Invoke application phase
6. Render response phase

Component writer's concern: Step 1, 2
JSF application developer's concern: Step 2, 3, 4, 5
                                                       39
Phase 1: Reconstitute
Component Tree (View) Phase
• When a request for a JavaServer Faces page is
  made, such as when clicking on a link or a button,
  the JSF implementation begins the Restore view
  phase
  > if it is the first time, an empty view is created
• JSF runtime performs
  > builds a view of a JavaServer Faces page
     > a view is a component tree of the page
  > wires up event handlers and validators
  > saves the view in the FacesContext

                                                        40
Phase 2: Apply Request Values
Phase
• Each component in the tree extracts its new value
  from the request parameters with its built-in
  decode method
• Within the decode method, the String type of a
  parameter is then converted to a specified type
  then stored locally on the component
  > Conversion errors are queued on the FaceContext




                                                      41
Converters
• Standard converters
  > Boolean, byte, character, date time, double, float, integer,
    long, number, short
  > BigInteger, BigDecimal (Creator and JSF RI)
  > <f:convertNumber integerOnly=”true”/>
• Custom converter
  > converterId registered in faces-config.xml
  > <f:converter convertId=”myOwnConverter”/>
• Method Binding
  > Expression to use a method in a bean

                                                                   42
Faces-config.xml : Custom Converter

1:<h:inputText id="ccno" size="16"
2: converter="creditCardConverter" required="true">
3:   <cs:format_validator
4:     formatPatterns="9999999999999999|9999 9999 9999
9999|9999-9999-9999-9999"/>
5:</h:inputText>


1:
2: <!-- Converter -->
3: <converter>
4:   <description>CreditCard Converter</description>
5:    <converter-id>creditCardConverter</converter-id>
6:    <converter-class>carstore.CreditCardConverter
7:    </converter-class>
8: </converter>


                                                         43
Phase 3: Process Validation Phase

• JSF implementation processes all input validations
  registered on the components in the tree
  > This is input validation (not business logic validation)
• In case of validation errors
  > Error messages are queued in FacesContext
  > Lifecycle advances directly to the Render Response phase
• Example
  > A input value has be be between 1 and 10 in guessNumber
    example

                                                               44
Validators
• Built-in validator
  > Length, longrange, doublerange
  > <f:validateLength minimum=”6”/>
• Custom validator
  > <f:validator validatorId= “myValidator”/>
  > validatorId registered in faces-config.xml
• Method Binding
  > Use a method binding expression to use
    a method in a bean


                                                 45
Phase 4: Update Model Values Phase

• JSF implementation walks the component tree
  and set the corresponding model object
  properties to the components' local values
  > Update the bean properties pointed at by an input
    component's value attribute
  > Type conversion from local value to model property type
• Example in greeting.jsp
  > userNumber property of the UserNumberBean is set to the
    local value of the userNo component
  > <h:inputText id="userNo" value="#{UserNumberBean.userNumber}"
           validator="#{UserNumberBean.validate}"/>
                                                                    46
Phase 5: Invoke Application Phase

• JSF implementation handles any application-level
  events, such as submitting a form or linking to
  another page




                                                 47
Invoke Application Phase
• Execute the action specified in the action and
  retrieve the outcome
  > CommandEvent – UI Command (such as a menu item)
    selected
  > FormEvent – Input form (with associated fields) to be
    processed
<h:commandButton action="#{carstore.buyCurrentCar" ... />



1: public class CarStore extends Object { ...
2: public String buyCurrentCar() {
3:     getCurrentModel().getCurrentPrice();
4:     return "success";
5: }
                                                            48
Phase 6: Render Response Phase

• JSF implementation invokes the components'
  built-in encode method and renders the
  components from the component tree saved in
  the FacesContext
  > Create appropriate markup from component tree
  > If errors in previous phases, original page is rendered with
    any queued error messages
• State of the response is saved so that
  subsequent requests can access it and it is
  available to the Restore View phase

                                                                   49
JavaServer Faces(JSF):
Key Concepts:
Event Handling
Lifecycle




            51
Two Types of Events
• Value change events
  > ValueChangedEvent—UIInput component whose value
    was just changed, called during the Process Validations
    phase
  > ValueChangeListener: Refers to a Model bean method
    that handles ValueChangeEvents
• Action events
  > ActionEvent—UICommand component activated by the
    user, processed during the Apply Request Values phase
    or the Invoke Application phase
  > ActionListener: Refers to a Model bean method that
    handles ActionEvents
                                                              52
JavaServer Faces(JSF):
Key Concepts:
Rendering
Component Rendering

• Rendering is handled by Render kit not by
  component classes
  > Component writers can define the behavior of a
    component once, but create multiple renderers
• Page authors and application developers can
  change the appearance of a component on the
  page by selecting the tag that represents the
  appropriate component/renderer combination
  > <h:commandButton>
  > <h:commandLink>

                                                     54
RenderKit
• Defines how component classes map to
  component tags appropriate for a particular client
  type
  > HTML renderkit
  > WML renderkit
  > SVG renderkit
• JSF implementation includes a built-in RenderKit
  for rendering to an HTML client
• For every UI component that a RenderKit
  supports, the RenderKit defines a set of Renderer
  objects
                                                       55
Renderer Object
• Defines a different way to render the particular
  component to the output defined by the RenderKit
• Example
  > UICommand component has two different renderers in the
    HTML renderkit
     > <h:commandButton>
     > <h:commandLink>




                                                             56
JavaServer Faces(JSF):
Struts-Faces Integration
Library & Shale
Struts-Faces Integration Design Goal

• Take an existing Struts-based application
• Convert JSP page one at a time
  > Use JavaServer Faces components instead of Struts
    HTML tags
• Tweak the mapping information in struts-
  config.xml
• Make no changes in the form beans or actions



                                                        58
Struts-Faces Integration Current
Status
• Struts-Faces integration library available at
  Apache site
  > http://cvs.apache.org/builds/jakarta-struts/nightly/struts-
    faces/
• Currently works with JSF v1.1
• Work with Tiles




                                                                  59
Next Generation Framework: Shale
• For building new webapps, consider Shale as the
  base web application framework:
  > Subproject of the Apache Struts project
  > http://struts.apache.org/shale/
• Extensions on top of JSF lifecycle:
  > No redundant implementation of JSF standard features
• Functional equivalence with Struts 1.x:
  > Including Tiles, Commons Validator support
• Innovative additional features:
  > Dialogs, ViewController, Clay, Remoting

                                                           60
Java Studio Creator
Sun Java Studio Creator Benefits
• Rapid, visual web application & portlet development
  using JavaServer Faces components
• Your choice:
  > Windows, Solaris, Linux, Mac OSX
• Standards-based applications
  > No vendor lock-in
• Alternative to Visual Basic and ASP.NET
  > Enables consolidation of presentation and middle tier on
    Java platform


                                                               62
Features (1 of 4)
• Complete development environment
  > Sun Java System Application Server PE
  > Sample DB
  > Sample applications (new)
• “Green Arrow” deployment
  > Enables iterative cycle: write code, build/deploy, make
    changes, repeat
• Support for coding at level you're comfortable with
  > Visually in Designer
  > Directly in JavaServer Pages (JSP)
  > In Java
                                                              63
Features (2 of 4)
• Rich library of JavaServer Faces components (new)
  > e.g. table, calendar, tree, tab set, file upload, and many more
  > Validators and converters
• Query Editor
  > Visually create SQL queries including joins, where clauses,
    criteria, etc.
• DataProviders (new)
  > Bind components to a variety of data
  > Enables drag-and-drop Web Service and EJB method
    binding


                                                                      64
Features (3 of 4)
• Built on NetBeans 4.1
  > VCS integration (new)
  > Refactoring (new)
  > Debugger
• Stylesheet Editor
  > Visual CSS development (new)
• Page Navigator
  > Point and click to define user flow
• Virtual Forms
  > dealing with multiple input scenarios in a single page

                                                             65
Features (4 of 4)
• Export WAR
  > i.e. WAR can be deployed to a number of containers
    including Sun Application Server, WebLogic, WebSphere,
    Tomcat, etc.
• Portlet Development
  > JSR-168
• Third-party components
  > Enables excellent design-time experience with third-party
    JavaServer Faces components (e.g. Otrix, Software FX,
    ILOG, JSCAPE, among others)


                                                                66
Java Studio Creator: Demo
Building an Employee
Travel Center Web Application
Demo Scenario
• Drag and drop UI components
• Data-binding between UI components & database
  tables
• SQL query
• JSF event-handler
• Table display layout
• Page navigation
• Data-binding between UI components and Web
  services and EJB
                                                  68
Demo Scenario
• Look into how JavaServer Faces functionality is
  used within Java Studio Creator




                                                    69
AJAX:
What is and Why AJAX?
Agenda
•   What is and Why AJAX?
•   Technologies used in AJAX
•   AJAX usage cases
•   Anatomy of AJAX interaction
•   AJAX and JSF
•   Best practice guidelines
•   Current issues and future

                                  71
Characteristics of Conventional
Web Application
• Click, wait, and refresh user interaction
  > Page refreshes from the server needed for all events, data
    submissions, and navigation
• Synchronous “request/response” communication
  model
  > Browser always initiates the requet
  > The user has to wait for the response




                                                                 72
Issues of Conventional
Web Application
•   Slow response
•   Lost of operation context during refresh
•   Excessive server load and bandwidth consumption
•   Lack of two-way, real-time communication capability
    for server initiated updates



                                                          73
Welcome To AJAX
• "Partial screen update" replaces the "click, wait, and
  refresh" user interaction model
  > Only user interface elements that contain new information are
    updated; the rest of the user interface remains displayed
    without interruption
• Asynchronous communication replaces
  "synchronous request/response model."
  > A user can continue to use the application while the client
    program requests information from the server in the
    background

                                                                  74
75
76
AJAX:
Technologies Used
in AJAX
Technologies Used in AJAX
• Javascript
  > Loosely typed object based scripting language
  > JavaScript in a page is called when an event in a page occurs
• DOM
  > API for accessing and manipulating structured documents
  > represents the structure of XML and HTML documents
• CSS
  > CSS allow for a clear separation of the presentation from the
    content and may be changed programatically by JavaScrip
• HTTP
  > XMLHttpRequest
                                                                    78
XMLHttpRequest
•   JavaScript object
•   Adopted by Mozilla™, Firefox, Safari, and Opera
•   Communication may be GET/POST
•   Documents must be text/xml
•   Page continues to process events, the
    XMLHttpRequest object works in the background




                                                      79
Server-Side AJAX Request
Processing
• Requests are HTTP Gets/POSTs
• Programming model remains the same
  > Servlet, JSP, JSF, ...
  > More frequent granular requets
  > Response content type needs to be text/xml




                                                 80
AJAX: Usage Cases
Usage cases for AJAX
• Real-time form data validation
  > user IDs, serial numbers, postal codes, or even special
    coupon codes that require server-side validation can be
    validated in a form before the user submits a form
• Auto-Completion
  > email address, name, or city name may be autocompleted as
    the user types
• Master detail operation
  > Based on a client event, an HTML page can fetch more
    detailed information on data such as a product listing
                                                              82
Usage cases for AJAX
• Advanced GUI widgets and controls
  > Controls such as tree controls, menus, and progress bars
    may be provided that do not require page refreshes
• Refreshing data
  > HTML pages may poll data from a server for up-to-date data
    such as scores, stock quotes, weather, or application-specific
    data
• Server side notification
  > An HTML page may simulate a server-side push by polling
    the server for event notifications
                                                                 83
Real-Life Examples of AJAX apps
• Google maps
  > http://maps.google.com/
• Gmail
  > http://gmail.com/
• Goolgle Suggest
  > http://www.google.com/webhp?complete=1&hl=en
• ZUGGEST- an XMLHttp Experiment using Amazon
  > http://www.francisshanahan.com/zuggest.aspx




                                                   84
AJAX: Demo
Demo Scenario

• Run sample AJAX applications within NetBeans IDE
  > Auto completion
  > Data validation
  > Progress bar
• You can try this demo yourself
  > These applications are provided as built-in sample
    applications in NetBeans




                                                         86
AJAX: Anatomy Of
AJAX Interaction
Anatomy of an AJAX Interaction




                                 88
Steps Of Interaction
1.A client event occurs
2.An XMLHttpRequest object is created and configured
3.The XMLHttpRequest object makes a call
4.The request is processed by the ValidateServlet.
5.The ValidateServlet returns an XML document
  containing the result
6.The XMLHttpRequest object calls the callback() function
  and processes the result
7.The HTML DOM is updated
                                                       89
1. A Client event occurs
• JavaScript technology functions are called as the
  result of an event
• The validateUserId() function is mapped to a
  onkeyup event on a link or form component

  <input type="text"
          size="20"
           id="userid"
          name="id"
       onkeyup="validateUserId();">
                                                      90
2. An XMLHttpRequest object is
created and configured
var req;
function initRequest(url) {
   if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       isIE = true;
       req = new ActiveXObject("Microsoft.XMLHTTP");
   }
}
function validateUserId() {
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   initRequest(url);
   req.onreadystatechange = processRequest;
   req.open("GET", url, true);
   req.send(null);
}                                                             91
3. XMLHttpRequest object makes a call
function initRequest(url) {
   if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       isIE = true;
       req = new ActiveXObject("Microsoft.XMLHTTP");
   }
}
function validateUserId() {
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   initRequest(url);
   req.onreadystatechange = processRequest;
   req.open("GET", url, true);
   req.send(null);
}
• URL is set to validate?id=gr
                                                              92
XMLHttpRequest Methods
• open(“method”, “URL”, syn/asyn)
  > Assigns destination URL, method, mode
• send(content)
  > Sends request including string or DOM object data
• abort()
  > Terminates current request
• getAllResponseHeaders()
  > Returns headers (labels + values) as a string
• getResponseHeader(“header”)
  > Returns value of a given header
• setRequestHeader(“label”,”value”)
  > Sets Request Headers before sending
                                                        93
XMLHttpRequest Properties
• onreadystatechange
  > Event handler that fires at each state change
  > You implement your own function that handles this
• readyState – current status of request
  > 0 = uninitialized
  > 1 = loading
  > 2 = loaded
  > 3 = interactive (some data has been returned)
  > 4 = complete
• status
  > HTTP Status returned from server: 200 = OK
                                                        94
XMLHttpRequest Properties
• responseText
  > String version of data returned from server
• responseXML
  > XML DOM document of data returned
• statusText
  > Status text returned from server




                                                  95
4. The request is processed by the
ValidateServlet (page 1)
public class ValidationServlet extends HttpServlet {
  private ServletContext context;
  private HashMap accounts = new HashMap();
  public void init(ServletConfig config) throws ServletException {
    this.context = config.getServletContext();
    accounts.put("greg","account data");
    accounts.put("duke","account data");
  }




                                                                     96
4. The request is processed by the
ValidateServlet (page 2)
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException {
   String targetId = request.getParameter("id");
 if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write("<valid>true</valid>");
     } else {
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write("<valid>false</valid>");
     }
 }



                                                                               97
5. The ValidateServlet returns an XML
document containing the results

    public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
        String targetId = request.getParameter("id");
        if ((targetId != null) && !users.containsKey(targetId.trim())) {
            response.setContentType("text/xml");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().write("valid");
        } else {
            response.setContentType("text/xml");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().write("invalid");
        }
    }
}
                                                                                  98
6. XMLHttpRequest object calls callback()
function and processes the result
• The XMLHttpRequest object was configured to call
  the processRequest() function when there are
  changes to the readyState of the XMLHttpRequest
  object

  function processRequest() {
      if (req.readyState == 4) {
          if (req.status == 200) {
              var message =
      req.responseXML.getElementsByTagName("valid")[0].
      childNodes[0].nodeValue;
              setMessageUsingDOM(message);
  ...                                                     99
Browser and DOM
• Browsers maintain an object representation of the
  documents being displayed
  > In the form of Document Object Model (DOM)
• JavaScript technology in an HTML page has access
  to the DOM, and APIs are available that allow
  JavaScript technology to modify the DOM after the
  page has loaded




                                                      100
Object Representation of the XML
Document Retrieved
• Following a successful request, JavaScript
  technology code may modify the DOM of the HTML
  page
• The object representation of the XML document that
  was retrieved from the ValidateServlet is available to
  JavaScript technology code using the
  req.responseXML, where req is an XMLHttpRequest
  object

                                                       101
DOM APIs for Navigation
• DOM APIs provide a means for JavaScript
  technology to navigate the content from that
  document and use that content to modify the DOM
  of the HTML page
    <message>
     valid
    </message>
  function parseMessage() {
    var message = req.responseXML.getElementsByTagName
    ("message")[0];
    setMessage(message.childNodes[0].nodeValue);
  }
                                                         102
7. The HTML DOM is updated
• JavaScript technology can gain a reference to any
  element in the HTML DOM using a number of APIs
• The recommended way to gain a reference to an
  element is to call
  > document.getElementById("userIdMessage"), where
    "userIdMessage" is the ID attribute of an element appearing in
    the HTML document
• JavaScript technology may now be used to modify
  the element's attributes; modify the element's style
  properties; or add, remove, or modify child elements
                                                                103
Change the Body content of an
Element
<script type="text/javascript">
function setMessage(message) {
  mdiv = document.getElementById("userIdMessage");
  if (message == "invalid") {
     mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id</
  div>";
  } else {
     mdiv.innerHTML = "<div style=\"color:green\">Valid User Id</
  div>";
  }
}
</script>
<body>
<div id="userIdMessage"></div>
</body>                                                           104
AJAX: Demo
Analyze AutoComplete AJAX
Interaction
• Capture the HTTP traffic via HTTP Monitor
• Make a breakpoint in the doGet() method of
  AutocompleteServlet
• Display some messages from client' JavaScript's
  functions through alert(“some message”)




                                                    106
AJAX:
Current Issues & Futures
Current Issues of AJAX
• Comlexity
  > Server side developers will need to understand that
    presentation logic will be required in the HTML client pages as
    well as in the server-side logic
  > HTML page developers must have JavaScript technology
    skills
• AJAX-based applications can be difficult
  to debug and test
  > JavaScript is hard to debug
• No standardization of the XMLHttpRequest yet
• JavaScript technology dependency
  > Must be enabled for applications to function
                                                                  108
Browsers support
•   Need XmlHttpRequest browser support
•   Mozilla Firefox 1.0 and above
•   Netscape version 7.1 and above
•   Apple Safari 1.2 and above.
•   Microsoft Internet Exporer 5 and above
•   Konqueror
•   Opera 7.6 and above


                                             109
AJAX Futures
•   AJAX-enabled JSF Component libraries
•   Standardization of XMLHttpRequest
•   More best practices in the programming model
•   Better browser support
•   Framework support and new frameworks




                                                   110
AJAX:
Best Practice Guidelines
AJAX Efficiency
•   Keep requests as concise as possible
•   Only request/respond with the data required
•   Preload data on the server where possible
•   Put some thought into what event will trigger
•   Some events happen faster than is practical to
    make server requests
    > i.e. Although Google Suggest appears to make a request on
      each keystroke, closer examination reveals it is actually
      makes requests at regular time intervals


                                                                  112
Things to Consider
• AJAX requires a different way of thinking about how
  you build your application
• Requires thinking about interface and interaction
  > Usability is the key—and is what you should strive for
     > Do not break what the user is focusing on
     > Make sure to give the user feedback
  > Do not over-use it




                                                             113
Things to Consider
• How do you handle state + sessions?
  > Decision on where to put state information gets trickier
     > Can all be on the client so you can have truly stateless servers
     > Requires a lot more client code for state – server already has
       mechanism for clustered
  > state synchronization
  > What happens if the server or network dies?




                                                                          114
Things to Consider
• Navigation Issues
  > Back button is meaningless unless you code ‘undo’
    functionality to it
     > Invisible IFRAME and puts results back to visible web page
     > Google Maps, Dojo toolkit (http://dojotoolkit.org)
  > Bookmarking doesn’t work unless you manually change the
    URL
     > Use anchor, URL#xyz
  > Refresh button can kill your app
     > Save state in <body onload> method

                                                                    115
Things to Consider
• Don’t assume the server is going to respond instantly
  > Network latency – consider interval between user request
    and server response
     > Need visual feedback for background activity
     > Preload data on the server where possible




                                                               116
AJAX & JavaServer Faces
(JSF) - Perfect Marriage
AJAX and JSF: Perfect Marriage

• Low-level JavaScript technology and CSS rendering
  can be handled by JSF component
  > JSF component hides AJAX complexities from page
    developers - it is now component developer's job
  > The rendering framework in JSF is leveraged




                                                       118
   JSF Platform Page Developer’s
   View of AJAX
<ajaxTags:completionField size="40" id="cityField"
  completionMethod="#{ApplicationBean.completeCity}"
  value="#{SessionBean.city}" required="true"
 />




                                                       119
AJAX Processing With
a JSF Component




                       120
Demo
AJAX-Enabled JSF
Component
Demo Scenario

• Use AJAX-enabled text field component within
  Java Studio Creator
  > As you type in the text field, auto-completion is attempted
    based on a list of possible expansions provided by a
    180,000-word dictionary
  > The dictionary is provided through a web service.
• You can try this demo yourself
  > http://developers.sun.com/prodtech/javatools/jscreator/ea/
    jsc2/learning/tutorials/textcompletion.html


                                                                  122
Summary,
Call For Action,
Resources,
Sun Developer Network
Summary

• JavaServer Faces is the standard for web
  application framework
• Struts can work well with
  JavaServer™ Faces
• You can use Java Studio Creator to ease the
  development of JavaServer Faces Application
• AJAX-enabled JSF components will be provided
  by Java Studio Creator

                                                 124
Call For Actions

• Try Sun Java Studio Creator – It is free!
• Try AJAX-enabled applications with NetBeans
• Join Sun Network Development (SDN)




                                                125
Resources
• JavaServer Faces homesite
  > http://java.sun.com/J2EE/javaserverfaces/
• JSF Central
  > http://www.jsfcentral.com/
• Java Studio Creator homesite
  > http://www.sun.com/jscreator/
• Sun Java Studio Creator 2 Early Access
  > http://developers.sun.com/prodtech/javatools/jscreator/ea/jsc2/down
• Struts integration library
  > http://jakarta.apache.org/builds/jakarta-struts/nightly/struts-
    faces/
                                                                      126
Sun Developer Network
Empowering the Developer

Increasing developer
productivity with:
   Technical articles
   Tutorials and sample codes
   Monitored forum
   support
   Community involvement
   through user groups, events,
   and conferences
   And more...                    http://developer.sun.com

                                                             127
SDN Expert Developer Help
 ● Project Lifeguard

   > Sun Developer Network Beta Program providing expert
     developer help
   > Pilot limited in scope starting November 15, Beta program
     can end without notice
   > Products supported during beta:
      > Java Studio Creator
      > Java Studio Enterprise (December 2005)
      > J2SE 1.4/2.5 Core
      > Sun Studio 10 and 11 for Solaris (December 2005)
   > Per incident, online help
   > 24 hour acknowledgment, M-F, 9-5 Bangalore TMZ
   > Provides help with programming “how to”
 • http://developer.sun.com/developer_help
                                                                 128
Web-Tier Codecamp:
JavaServer Faces,
AJAX,
Java Studio Creator
Sang Shin
sang.shin@sun.com
Technology Evangelist
Sun Microsystems, Inc.

								
To top