Interactive Web Frameworks - PowerPoint by HD4u6mus

VIEWS: 0 PAGES: 32

									Interactive Web Frameworks



        Anthony Berglas
         RSA Security
          March 2007
                    Introduction
• AJAX Technologies
  – Basic Introduction
  – Client side tools eg. Yahoo YUI, Google GWT
  – Server side tools eg. Echo2, ZK, WingS, ASP.NET
• Non AJAX interactive technologies eg. Flex/Flash
• Locus of control – Client vs Server vs Hybrid
  – The critical question
• Why Interactive Web Pages?
  – Do they really add value that justifies the pain?
               The AJAX Basics
• Normally web pages can only be refreshed as a whole
• JavaScript can update pages dynamically
  – JavaScript can send intra page messages to server
• Traditionally done with IFrames
• Now can be done with XMLHttpRequest objects
• Popularized by Google
  – Eg. mail aliases looked up on demand
                  Basic Example
httpRequest = new XMLHttpRequest(); // non-IE
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");// IE

httpRequest.onreadystatechange
  = function() { alertContents(httpRequest); };

url = “http://foo.com/my.xml”;
url = “http://foo.com/myApp?p=urlencoded”;
url = “http://foo.com/myWebService?p=urlencoded”;

httpRequest.open('GET', url, true);
httpRequest.send(null);

// Response calls alertContents Asynchronously
                 Basic Example ctd
function alertContents(httpRequest) {
  if (httpRequest.readyState == 4) // asynchronous
    if (httpRequest.status == 200) {// else exception

         // eg. “Hello”
         alert(httpRequest.responseText); // or

        // eg. “<myElement>Hello</myElement>”
        var xmldoc = httpRequest.responseXML;
        var root_node =
    xmldoc.getElementsByTagName(‘myElement').item(0);
        alert(root_node.firstChild.data); // or

        // eg. “myInput.value=‘foo’;...”
        eval(httpRequest.responseText); // Very thin client !
    }
}
                       Problems
• Programming over multiple tiers clumsy/messy
  – “Asynchronous” makes it even more error prone
• Difficult to Debug
• Difficult to Test
• Security issues
  – Your code might not be running on the client
• Many browser idiosyncrasies
  – Eg. JavaScript issues, DOM issues, CSS issues, ...
  – Even just getting the httpRequest object inconsistent
  – Also browser version dependent
• IE 5, Safari 1.2, Mozilla 1.0, Opera 8, Netscape 7
• Client operating system dependent
• Need to use higher level framework
  – eg. http://www.ajaxmatters.com/blog/ajax-frameworks/
    lists 104, but incomplete (eg. not WingS)
                    Yahoo’s YUI
• Conventional JavaScript/css library
• General Utilities
    – Connection Manager, Events, Animation, Drag & Drop
    – History Manager, Dom collection, ...
• Rich UI Controls
    – Data Table (resizable columns etc.)
    – Tree View, Tab View, Calendar
    – AutoComplete, Advanced Buttons, Fancy Menus, Slider...
•   Very browser independent
•   Open source (BSD), well supported by Yahoo
•   Lots of cool examples, but weak docs
•   http://developer.yahoo.com/yui/ has good docs
•   (Thomas Czarniecki recommends it)
   Yahoo Code Sample and Egs.
• Client side JavaScript?
                 Google’s GWT
• Java to JavaScript translator(!!!)
   – Hosted development mode runs on server – “Awesome”
   – Web deployment mode converts to JavaScript
     (Java byte code magically converted to JavaScript)
• UI components – trees, tab bars, modal dialogs
   – Normal widgets, events etc. (analogous to YUI)
• RPC based serialization (for hybrid control? DTO)
• Semi open source (Java to JavaScript binary only)
   – Good support from Google
• http://code.google.com/webtoolkit/overview.html
• Debugging Hosted easy, (impossible for Web bugs?)
   – There are JavaScript debuggers too!
• Good tools eg. screen painter
• Michael Neale recommends – “works as advertised”
          GWT Client Example
private Button fPopupButton
  = new Button("Show Popup", this);

public Popups() {
    VerticalPanel panel = new VerticalPanel();
    panel.setSpacing(8);
    panel.add(fPopupButton);
    panel.add(fDialogButton);...
    initWidget(panel);
}

public void onClick(Widget sender) {
    if (sender == fPopupButton) {
      MyPopup p = new MyPopup();
      int left = sender.getAbsoluteLeft() + 10; ...
      p.setPopupPosition(left, top);
      p.show();
}...}
           GWT Client Fetch Example
calService = () GWT.create(CalendarService.class);

public void updateRowData(...) {
 String url = GWT.getModuleBaseURL() + "calendar";
 callService.setServiceEntryPoint(url);

    // Actually fetch the data remotely.
    calService.getPeople(
      startRow, maxRows, new AsyncCallback() {
          public void onFailure(Throwable caught) {
            acceptor.failed(caught);
          }

            public void onSuccess(Object result) {
              Person[] people = (Person[]) result;
              pushResults(acceptor, startRow, people);
            }
     });
}
          Google GWT Summary
• Java to JavaScript is very clever
   – Too Clever?
   – Unintelligible Client code
   – It had better be bug free, but supported by Google
• Most powerful widgets?
   – eg. supports Google Maps, Mail, Spreadsheet?
• Good docs, examples
• But still multi tier low level programming
                  Locus of Control
• Traditional Server only – no JavaScript at all
   – Clean, simple, sufficient?
• Hybrid – Server serves HTML with JavaScript
   – Very messy, programming in two tiers
• Client Side – Entire application runs on client
   – Server side just implements clean web services, no UI
     getCustomerList(NamePattern, offset, max)
     updateCutomer(custId, custRecord, userId)
     Exposing these might be bad. (& not necessarily SOAP!)
   – As much how to use the tools as the tools themselves
• Server Side yet highly interactive
   – Browser behaves like smart X-Terminal, driven from server
   – Fixed JavaScript libraries, no user written code on client
   – Can be very chatty with the server, almost field by field
      • Substantial server load, very stateful
   – Several Tools: Echo2, ZK, WingS, (Developer 2000 ++)
      Echo2 (also ZK, WingS etc.)

• Events optimized, but crude, eg. Button click
    – Not auto-complete etc. need custom components
• Need JavaScript components for fine grained events
• Very stateful, server affinity, some load on server
• Open Source (Mozilla or LGPL)
• http://www.theserverside.com/news/thread.tss?threa
  d_id=40804 (Tom Liebeck) Echo2 vs GWT
• Excellent docs and examples
• Very cool demos (some latency over the web)
            Echo2 Basic Example
public class HelloWorldApp
    extends ApplicationInstance {

  public Window init() { // @Overides inherited
    Window window = new Window();
    ContentPane contentPane = new ContentPane();
    window.setContent(contentPane);
    Label label = new Label("Hello, world!");
    contentPane.add(label); ...

      return window;
} }

public class HelloWorldServlet
      extends WebContainerServlet {
  public ApplicationInstance newInstance() {
      return new HelloWorldApp(); } }
  // (One instance of HelloWorldApp per user session)
      Echo2 Layout Example
Column buttonColumn = new Column();

ColumnLayoutData layoutData
  = new ColumnLayoutData();
layoutData.setAlignment(new Alignment(
   Alignment.RIGHT,Alignment.DEFAULT));
button1.setLayoutData(layoutData);

Button button1
 = new Button("First Button");
buttonColumn.add(button1);
button1.setBackground(Color.GREEN);
Button button2 = new Button(
  "Second Button"); ...
      Echo2 Example Events
// Events on SERVER in responce to client
final Button button =
    new Button("Please click me.");
 button.addActionListener(
    new ActionListener() {
     public void
       actionPerformed(ActionEvent e){
          button.setText("Thanks!"); }
 }); // (Anon. inner class)
             Echo2 XML Messages
// On button click having entered 75 into a field
<client-message>
  <message-part processor="EchoPropertyUpdate"> <property
  component-id="c_7" name="text"> 75 </property>
  </message-part> ....

// Response from server (full response much bigger)
<server-message xmlns=“http://www.nextapp.com/...” ...
  <message-part-group id="remove"> ...
   <message-part
       processor="EchoDomUpdate.MessageProcessor">
    <dom-remove target-id="c_4"/> ...
  <message-part-group id="update">
   <message-part
     processor="EchoDomUpdate.MessageProcessor">
       <dom-add parent-id="c_2_cell_c_4">
     <content>
       <span xmlns="http://www.w3.org/1999/xhtml“
          id="c_4">
      Your guess, 75 was too high. Try again: </span> ...
                            Flex
• “Significantly richer UI, not just a little better, WAY
  better. Orders of magnitude better”
   – Is this really true?
• No browser compatibility issues. None. It just works.
   – Flash plug in give similar client side virtual machine
     advantages we get with the java virtual machine on server
     side.
• Security better in flex, no source code ever exposed.
  Background / asynch requests are not exposed like
  they are in AJAX.
• Very proprietary, but opening up
• (Tony Obermeit)
• Why go to the trouble of AJAX if not for the WOW!
                              Flex Ctd
• Talks to apps via web services or Java “Flex Data
  Services”
  –   “FDS allows direct access to Java objects”. Secure?
  –   Hibernate interface?
  –   Syncs client data cache with server (eg. sort on client)
  –   Async/Push Messaging option (as well as RPC)
       • Direct client to client, eg. for data sync.
  – Proxying – security
• MXML (template)
• ActionScript (JavaScriptish).
  – JIT compiled. Strong Typing etc. Can call/be called AJAX
• Can create custom components
• Animations (“behaviors”) etc.
• http://www.adobe.com/products/flex/whitepapers/pdf
  s/flex2wp_technicaloverview.pdf
                 Flex – MXML
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
    creationComplete=”ws.getList()”>
 <mx:Style source=”main.css”/>
 <mx:WebService id=”ws”
  wsdl=”http://mysite.com/services/CatalogWS?wsdl” >
    <mx:operation name=”getList”/>
 </mx:WebService>
 <mx:Panel title=”Product Catalog”>
 <mx:DataGrid width=”100%” height=”100%”
     dataProvider=”{ws.getList.lastResult}”>
   <mx:columns>
     <mx:DataGridColumn dataField=”name”
         headerText=”Name”/>
     <mx:DataGridColumn dataField=”price” .../>
   </mx:columns>
 </mx:DataGrid>
 </mx:Panel>
</mx:Application>
                     Client Java
• Much maligned, but like Flex avoids browser issues
• Webstart much improved
  – Are there still issues?
  – Applets are also still an option – issues?
• Core Java not as pretty as Flex
  – But many Swing libraries available
  – Full power of Java system plus development environment
• Normal mode Swing on client, Brower ignored
  – (Can also have client Java update the DOM, a really bad
    idea (Did this for Developer 200++))
                     ASP.NET
• ASP.NET has object tree,
  – Inherently server side AJAXable
  – (unlike JSP/JSTL)
• ASP.NET AJAX is a JavaScript library
• http://www.daniel-
  zeiss.de/AJAXComparison/Results.htm
  good comparison of 8 tools’ architectures
• Also Script# – C# to JavaScript
• Worth looking at for Ideas at least
                   Plain HTML
• Interactive great for unusual applications
  – Spreadsheet
  – Node/Arc graph editor (Difficult with AJAX?)
  – Full featured mail/word processor
• But plain HTML a reasonable option for
  Forms, Lists and Trees
  – Ie. the common case for business applications
• Can/should be Stateless, scalable on server
• Add minimal JavaScript only where it really adds
  value
              Template Driven
• Most UIs are essentially Forms, Lists, Tree (CRUD)
• Need multiple branding,
  – (More than CSS)
• Do not want to have to program each UI by hand
• Want meta data driven templates
• (Leads to AgileUI presentation...)
                      Conclusion
• Raw AJAX hard to use, need tools
• Key issue is locus of control
    – Hybrid – multi tier programming hard
    – All Client side – Server just web services
    – All Server side – Can be slow, inflexible
•   For client side Yahoo YUI is simple and respected
•   Google GWT is very clever, hybrid style
•   Echo2, ZK, WingS support server side
•   There are alternatives to AJAX, eg. Flex/Flash
•   But no need for AJAX for effective applications
•   Key is to model Lists/Forms/Trees at a high level
•   KISS – Keep It Simple, Stupid
End
                          ZK
• Server centric like echo2
  – Mark up generates page graph, code can modify
• Has own XML markup language and Beanshell
  – Can also use plain Java
• ZK has some nice components, but echo2 cleaner?
• http://www.zkoss.org/doc/ZK-wp-prodovw.pdf
  overview
• http://www.zkoss.org/zkdemo/userguide/index.zul
  has examples
• http://forum.nextapp.com/forum/index.php?showtopic
  =2278&st=15 compares them
• Licensing issues – GPL + Commercial?
• Aimed at non-Java programmers, “easy to use”
               ZK Sample 1
<zk>
  <window id="win" border="normal" width="200px"
  sizable="true">
     <caption image="/img/inet.png" label="Hi
  there!"/>
     <checkbox label="Hello, Wolrd!"/>
  </window>

  <button label="Overlap"
  onClick="win.doOverlapped();"/>
  <button label="Popup"
  onClick="win.doPopup();"/>
  <button label="Embed"
  onClick="win.doEmbedded();"/>
</zk>
                           XK Sample 2
<window title="textbox with constraints" border="normal">
    <grid width="90%">
    <rows>
           <row>textbox: <textbox value="text..."/></row>
           <row>int box:<intbox/></row>
           <row>decimal box:<decimalbox format="#,##0.##"/></row>
           <row>date box:
                     <hbox>
                     <datebox id="db"/>
                     <listbox onSelect="db.setFormat(self.selectedItem.value)" mold="select"
    rows="1">
                               <listitem label="Default" value=""/>
                               <listitem label="yyyy/MM/dd" value="yyyy/MM/dd"/>
                               <listitem label="MM-dd-yy" value="MM-dd-yy"/>
                     </listbox>
                     </hbox>
           </row>
           <row>positive box:<intbox constraint="no negative,no zero"/></row>
           <row>e-mail:<textbox constraint="/.+@.+\.[a-z]+/: Please enter an e-mail
    address"/></row>
           <row>
                     multiple lines:
                     <textbox rows="5" cols="40">
                               <attribute name="value">
text line1...
text line2...
                               </attribute>
                     </textbox>
           </row>
    </rows>
    </grid>
</window>
        ZK Sample Pure Java
import org.zkoss.zul.*;
public class TestRichlet extends
  org.zkoss.zk.ui.GenericRichlet {
public void service(Page page) {
page.setTitle("Richlet Test");
final Window w = new Window("Richlet
  Test", "normal", false);
new Label("Hello World!").setParent(w);
final Label l = new Label();
l.setParent(w);
//...
w.setPage(page);
}
}
                                 Misc
• Bindows – Client locus, XML + JS, Very Windows LAF,
  proprietary
• Lazlo/openLazlo: XML/JavaScript  Flash
    – Well known, looks neat
•   (XUL – client side XML markup, firefox & IE).
•   http://dojotoolkit.org/ Wondrous js widgets! O/S
•   JSON – alt to XML {“x”, 123, [1, 2, 3]}
•   JSMX – client only lightweight AJAX (no widgets)
•   JavaScript Lint – traps undeclared variables!
    – But not object props, need to run.
• DOJO – pure JS, “more features than YUI”, “difficult to
  customize”
• ProtoType – another pure JS. Similar to YUI?
• “Of YUI, DOJO, Prototype YUI easier to understand better
  documented”

								
To top