Java Web Programming [8/9] : JSF and AJAX

1,263 views

Published on

Presentation for Java Web Programming Course; 2011

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,263
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
60
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Java Web Programming [8/9] : JSF and AJAX

  1. 1. Module 8:JSF and AJAX BasicsThanisa Kruawaisayawan Thanachart Numnonda www.imcinstitute.com
  2. 2. Objectives What is JSF? Real-Life Examples of AJAX Apps What is AJAX and Why AJAX? Technologies Used In AJAX XMLHttpRequest 2
  3. 3. JavaServer™ Faces (JSF) Framework Is… A server side user interface (UI) component framework for Java™ technology-based web applications. (Validators) Drag-and-drop UI components to build a web Application.
  4. 4. Application Configuration File XML file for configuring resources required at application startup time  navigation rules, converters, validators, render kits Usually named as faces-config.xml A <faces-config> tag must enclose all of the other declarations <faces-config> .... </faces-config>
  5. 5. Two Tag Libraries jsf_core  Definesother JSF related tags  Independent of any rendering technology html_basic  Defines tags for representing common HTML user interface components JSP page need to declare them <%@ taglib uri="http://java.sun.com/jsf/core/" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html/" prefix="h" %>
  6. 6. <f:view> element Represents UIViewRoot component All component tags on the page must be enclosed in the view tag <f:view> ... other faces tags, possibly mixed with other content ... </f:view> Optional locale attribute  Overrides the Locale stored in the UIViewRoot
  7. 7. HTML Tags Used to control display data or accept data from the user Common attributes  id:uniquely identifies the component  value: identifies an external data source mapped to the components value  binding: identifies a bean property mapped to the component instance
  8. 8. Built-in UI Component Classes UIForm:  Encapsulates a group of controls that submit data to the application. This component is analogous to the form tag in HTML. UIInput:  Takes data input from a user  is a subclass of UIOutput UIOutput:  Displays data output on a page
  9. 9. UIForm & <h:form> tag UIForm UI component  An input form with child components representing data that is either presented to the user or submitted with the form Encloses all of the controls that display or collect data from the user Include HTML markup to layout the controls on the page  <h:form> tag itself does not perform any layout
  10. 10. UIInput & UIOutput Components UIInput component displays a value to a user and allows the user to modify this data  The most common example is a text field UIOutput component displays data that cannot be modified  The most common example is a label Conversions can occur Both UIInput and UIOutput components can be rendered in several different ways
  11. 11. UICommand & <h:commandButton> UICommand component performs an action when it is activated  Most common renderers are Button and Link
  12. 12. UICommand & <h:commandButton> Additional attributes  action:  is either a logical outcome String or a JSF EL expression that points to a bean method that returns a logical outcome String  In either case, the logical outcome String is used by the navigation system to determine what page to access when the UICommand component is activated
  13. 13. Example1: <h:commandButton> from carDetail.jsp<h:commandButton action="#{carstore.buyCurrentCar}" value="#{bundle.buy}" /> action attribute  references a method on the CarStore backing bean that performs some processing and returns an outcome  outcome is passed to the default NavigationHandler, which matches the outcome against a set of navigation rules defined in the application configuration file. value attribute  references the localized message for the buttons label  bundle part of the expression refers to the ResourceBundle that contains a set of localized messages
  14. 14. greeting.jsp <f:view> <h:form id="helloForm" > <h2>Hi. My name is Duke. Im 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}“ /> <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>
  15. 15. Validation Model jsf-core tag library also defines a set of tags that correspond to the standard Validator implementations Most of the tags have a set of attributes for configuring the validators properties  minimum and maximum
  16. 16. Validator Tags <f:validator>  Registers a custom Validator on a component <f:validateLength>  Registers a LengthValidator on a component <f:validateLongRange>  Registers a LongRangeValidator on a component <f:validateDoubleRange>  Registers a DoubleRangeValidator on a component
  17. 17. Real-Life Examples of AJAX Apps Google maps  http://maps.google.com/ Google Suggest  http://www.google.com/webhp?complete=1&hl=en Gmail  http://gmail.com/ Yahoo Maps (new)  http://maps.yahoo.com/ Many more are popping everywhere 17
  18. 18. What is AJAX? Asynchronous JavaScript And XML DHTML plus Asynchronous communication capability through XMLHttpRequest Pros  Most viable RIA technology so far  Tremendous industry momentum  Several toolkits and frameworks are emerging  No need to download code & no plug-in required Cons  Still browser incompatibility  JavaScript is hard to maintain and debug 18
  19. 19. Why AJAX? Intuitive and natural user interaction  Noclicking required  Mouse movement is a sufficient event trigger "Partial screen update" replaces the "click, wait, and refresh" user interaction model  Only user interface elements that contain new information are updated (fast response)  The rest of the user interface remains displayed without interruption (no loss of operational context) Asynchronous communication replaces "synchronous request/response model." 19
  20. 20. Interrupted useroperation whilethe data is beingfetchedUninterrupteduser operationwhile data isbeing fetched 20
  21. 21. 21
  22. 22. Server-Side AJAX Request Processing Server programming model remains the same  It receives standard HTTP GETs/POSTs  Can use Servlet, JSP, JSF, ... With minor constraints  More frequent and finer-grained requests from client  Response content type can be  text/xml  text/plain  text/json  text/javascript 22
  23. 23. Demo Scenario Runsample 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 23
  24. 24. Data Validation Example 24
  25. 25. Steps of AJAX Operation1. A clientevent occurs2. An XMLHttpRequest object is created3. The XMLHttpRequest object is configured4. The XMLHttpRequest object makes an async. request5. The ValidateServlet returns an XML document containing the result6. The XMLHttpRequest object calls the callback() function and processes the result7. The HTML DOM is updated 25
  26. 26. 1. A Client event occurs A JavaScript function is called as the result of an event Example: validateUserId() JavaScript function is mapped as a event handler to a onkeyup event on input form field whose id is set to “userid” <input type="text" size="20" id="userid" name="id" onkeyup="validateUserId();"> 26
  27. 27. 2. An XMLHttpRequest object is createdvar req;function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); }}function validateUserId() { initRequest(); req.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); req.open("GET", url, true); req.send(null);} 27
  28. 28. 3. An XMLHttpRequest object is configured with a callback functionvar req;function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); }}function validateUserId() { initRequest(); req.onreadystatechange = processRequest; // callback function if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); req.open("GET", url, true); req.send(null); 28}
  29. 29. 4. XMLHttpRequest object makes an async. requestfunction initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); }}function validateUserId() { initRequest(); req.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); req.open("GET", url, true); req.send(null);} URL is set to validate?id=greg 29
  30. 30. 5. The ValidateServlet returns an XML document containing the results (Server)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>"); } } 30
  31. 31. 6. XMLHttpRequest object calls callback() function and processes the result The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = ...; 31
  32. 32. 7. The HTML DOM is updated JavaScript technology gets a reference to any element in a page using DOM API 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 elements attributes; modify the elements style properties; or add, remove, or modify child elements 32
  33. 33. 1. <script type="text/javascript">2. function setMessageUsingDOM(message) {3. var userMessageElement = document.getElementById("userIdMessage");4. var messageText;5. if (message == "false") {6. userMessageElement.style.color = "red";7. messageText = "Invalid User Id";8. } else {9. userMessageElement.style.color = "green";10. messageText = "Valid User Id";11. }12. var messageBody = document.createTextNode(messageText);13. // if the messageBody element has been created simple replace it otherwise14. // append the new element15. if (userMessageElement.childNodes[0]) {16. userMessageElement.replaceChild(messageBody,17. userMessageElement.childNodes[0]);18. } else {19. userMessageElement.appendChild(messageBody);20. }21. }22. </script>23. <body>24. <div id="userIdMessage"></div>25. </body> 33
  34. 34. Acknowledgement Most contents are borrowed from thepresentation slides of Sang Shin, Java™Technology Evangelist, Sun Microsystems,Inc. 34
  35. 35. Thank you thananum@gmail.comwww.facebook.com/imcinstitute www.imcinstitute.com 35

×