SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
© 2009 Marty Hall




 The Google Web Toolkit (
        g               (GWT):
                            )
            Basics
                                       (
                                       (GWT 1.7 Version)
                                                       )
            Originals of Slides and Source Code for Examples:
        http://courses.coreservlets.com/Course-Materials/gwt.html
           p                                             g
                  Customized Java EE Training: http://courses.coreservlets.com/
  Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
   Developed and taught by well-known author and developer. At public venues or onsite at your location.




                                                                                                                © 2009 Marty Hall




 For live Ajax & GWT training, see training
courses at http://courses.coreservlets.com/.
          t htt //                l t       /
      Taught by the author of Core Servlets and JSP, More
     Servlets and JSP and this tutorial. Available at public
                  JSP,          tutorial
     venues, or customized versions can be held on-site at
                       your organization.
    •C
     Courses d
             developed and t
                 l   d d taught b M t H ll
                             ht by Marty Hall
           – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics
           – Ajax courses can concentrate on EElibrary (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several
                  Customized Java one Training: http://courses.coreservlets.com/
    • Courses developed and taught by coreservlets.com experts (edited by Marty)
  Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
            JSP, JSF 1.x & JSF EJB3, Ruby/Rails
   Developed and taught by well-known author and developer. At public venues or onsite at your location.
                                           Contact hall@coreservlets.com for details
Topics in This Section
    • Pros and cons of GWT
    • Installing GWT
    • Development process
      – Making a project
      – Editing auto-generated HTML file
      – Editing auto-generated Java class
                auto generated
    • Testing process
      – Hosted mode
      – Local Web mode
      – Deployed mode
    • Quick preview: client-side event handlers
5
    • Quick preview: custom Java classes


                                                                                                 © 2009 Marty Hall




                                   Motivation

                      Customized Java EE Training: http://courses.coreservlets.com/
        Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
         Developed and taught by well-known author and developer. At public venues or onsite at your location.
Why Ajax?
    • HTML and HTTP are weak
       –N i
         Non-interactive
                     i
       – Coarse-grained updates
    • Everyone wants to use a browser
       – Not an application that requires SW installation
    • “Real” browser-based active content
       – Failed: Java Applets
              • Not universally supported; can’t interact with the HTML
       – Serious alternative: Flash (and Flex)
                                    (        )
              • Not yet universally supported; limited power
       – New and unproven
              • Microsoft Silverlight
              • JavaFX
              • Adobe AIR (formerly “Apollo”)
7




    Traditional Web Apps vs.
    Ajax Apps

         Infrequent large updates                                         Frequent small updates




8    Diagrams from Ajax in Action by Dave Crane et al, Manning Press. See recommended books in next lecture.
Google Home Page
     (formerly Google Suggest)




9




     Ajax Jobs (as of Sept. 2009)
         Indeed.com compiles data from many jobs sites




10
Ajax Problems
     that GWT Tries to Address
     • At least two languages are required
       – JavaScript on the client
       – Java or another language on the server
     • Invoking server is cumbersome
       – Even with JSON-RPC or jQuery support
       – Want more powerful RPC mechanism
     • JavaScript scales poorly to large projects
       –   No strong typing
                   g yp g
       –   Weak object hierarchies
       –   Many run-time errors instead of compile-time errors
       –   Incompatibility across platforms
       –   Can’t use preexisting Java libraries or utilities
11




     GWT Jobs
     (Absolute and Relative)




12
© 2009 Marty Hall




                             Overview and
                              Installation

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Overview of the
     Google Web Toolkit (GWT)
     • Big Idea
       – You write both client-side and server-side code in Java
       – Client-side code
          • Uses an API similar to Swing
          • Most basic JDK 1.6 constructs and classes supported
          • Gets compiled into JavaScript that runs in your browser
       –S
        Server-side code
                id    d
          • Client uses a callback API and specifies data source URL
                 – Once you define callback, you are mostly using regular Java
                   method calls with complex arguments and return values
          • Server extends special class and defines regular methods
                 – These are not servlet-style doBlah methods linked to HTTP
                 – Arguments and return values can be
                       » Primitives, Strings, arrays, a few java.util collections, Serializable custom classes

14
Sites that Use GWT
     • Google Sites
          – Google Base, Google Wave,
            Google Checkout,
            Google Web Content
            Manager
     •   kaching.com
     •   gogrid.com
     •   contactoffice.com
     •   riflethru.com
     •   scenechronize.com
     •   whirled.com
15




         Advantages of GWT
     • No JavaScript syntax errors
          – Use a reliable, strongly-typed language (Java) for development and
                  reliable strongly typed
            debugging
          – No JavaScript programming at all!
     • Can use complex Java on the client
          – Turned into JavaScript, but you still use String, array, Math class,
            ArrayList, HashMap, custom classes, etc.
          – Full IDE-based Java support for development and debugging
                 IDE based
     • Can send complex Java types to/from the server
          – Data gets serialized across network.
          – More powerful and convenient approach than JSON RPC or DWR
                                                       JSON-RPC DWR.
     • Standalone test environment
          – Can test within Eclipse without installing a server
     • Support by major company
          – Supported by the company that popularized Ajax in the first place
          – Support won’t go away like perhaps with AjaxTags
16
Disadvantages of GWT
     • Less incremental; big learning curve
       – Java developers can deploy with AjaxTags in just a few minutes,
                                                                 minutes
         whereas it takes much longer to get anything running with GWT.
       – JavaScript developers can adapt to new library (e.g., move from
         jQuery to Dojo) easily, whereas GWT seems foreign to them
     • N
       Nonstandard approach to HTML and JavaScript
           t d d          ht          dJ    S i t
       – Programmatic creation of HTML can make use of standard HTML
         and CSS tools more difficult.
       – You never put direct JavaScript in your HTML
                                                 HTML.
           • Very powerful in the long run, but hard to get used to at first.
       – Not search engine friendly
           • Google and others won’t index the dynamic content
                g                               y
     • Only for Java developers
       – Most Ajax environments do JavaScript on the client and have a
         choice for the server. GWT is based entirely around Java.
     • Unusual approach
       – Fundamentally different strategy than all other Ajax environments
17
         makes evaluation and management buyoff harder




     Alternatives to GWT
     • Client-Side Tools
       – jQuery
           • http://www.jquery.org/
       – Dojo (built on Prototype)
           • http://www.dojotoolkit.org/
                p         j           g
       – script.aculo.us (built on Prototype)
           • http://script.aculo.us/
       – ExtJS
           • htt // tj
             http://extjs.com/ (they also have native library f GWT)
                             / (th    l h        ti lib       for
       – Yahoo User Interface Library (YUI)
           • http://developer.yahoo.com/yui/
       – Google Closure Library
           • http://code.google.com/closure/library/
     • These are not mutually exclusive wrt GWT
       – You can wrap them in JSNI in GWT
       – But more common approach is to use the JS tools directly, refer to a
         URL, and use arbitrary technology on the server
18
Alternatives to GWT (Continued)

     • Server-Side Tools
       – Direct Web Remoting
           • Lets you call Java methods semi-directly from JavaScript
               – But not as cleanly or with as powerful return types as with GWT
           • http://getahead.ltd.uk/dwr/
       – JSON/JSON-RPC
           • For sending data to/from JavaScript with less parsing
           • http://www.json.org/
           • http://json-rpc.org/
       – JSP custom tag libraries
           • Create tags that generate into HTML and JavaScript
               – Use approaches from previous page, but hide details and simplify code
                 for page developers
           • http://courses.coreservlets.com/Course-Materials/msajsp.html

19




     Alternatives to GWT (Continued)
     • Hybrid Client/Server Tools
       – Aj T
         AjaxTags (built on top of script.aculo.us)
                  (b il          f i         l    )
           • JSP custom tags that generate Ajax functionality
               – Supports many powerful Ajax capabilities with very simple syntax
               – htt // j t
                 http://ajaxtags.sourceforge.net
                                       f       t
       – JavaServer Faces (JSF) component libraries
           • Trinidad (formerly Oracle ADF)
               – htt //
                 http://www.oracle.com/technology/products/jdev/htdocs/
                                l     /t h l       / d t /jd /htd     /
                 partners/addins/exchange/jsf/ (also myfaces.apache.org)
           • Tomahawk
               – http://myfaces.apache.org/tomahawk/
                    p    y       p       g
           • Ajax4JSF
               – http://labs.jboss.com/jbossajax4jsf/
           • IceFaces
               – http://www.icefaces.org/
           • Build your own
               – http://courses.coreservlets.com/Course-Materials/jsf.html
20
Installation: Overview
     • Download and install Google Eclipse Plugin
          • http://code.google.com/appengine/docs/java/tools/
            eclipse.html
       – Includes core GWT libraries
       – Includes utilities for building, running, testing, and
         benchmarking GWT apps from within Eclipse
       – I l d utilities for the Google App Engine
         Includes tiliti f th G          l A E i
          • Won’t be discussed here, but they do not interfere with
            using plugin for GWT for deployment on any Java server
     • GWT can also be used without Eclipse
          • http://code.google.com/webtoolkit/download.html
       – Some limited support for other IDEs
       – Comes with prebuilt ant scripts
21     – Not discussed in this tutorial




     Installation: Details
     (Eclipse 3 5 – Galileo)
               3.5
     • Go to Eclipse “Install New Software” page
       – Start Eclipse (3.5)
       – Help  Install New Software  Work With
     • Load plugin
       – Enter
         http://dl.google.com/
            p      g g
         eclipse/plugin/3.5
       – Press “Add”, then “OK”
         (leave name blank)
       – Select all Plugin
         and SDK options
                     p
       – Press “Next” (and finish)
22
       – Restart Eclipse
Installation: Details
      (Eclipse 3.4 – Ganymede)
                34
     • Go to Eclipse “Add Site” page
       – Start Eclipse (3.4)
       – Help  Software Updates  Available Software
          Add Site
     • Load plugin
       – Enter
         http://dl.google.com/
         eclipse/plugin/3.4
       – Press “OK”
       – Select all Plugin
         and SDK options
                     p
       – Press “Install”
23
       – Restart Eclipse




     Documentation
     • GWT overview page
       – Good starting point with links to tutorials and docs.
          • http://code.google.com/webtoolkit/overview.html
     • Developer’s guide
       Developer s
       – Includes Quick Start guide and general approaches
          • http://code.google.com/webtoolkit/doc/1.6/DevGuide.html
                        g g
     • Reference guide              Note that they didn’t update URLs when GWT moved from 1.6 to 1.7.




       – Includes JavaDoc API, guide to which Java features are
         supported on client side, and widget library reference
                 d     li     id     d id lib           f
          • http://code.google.com/webtoolkit/doc/1.6/RefGuide.html
     • Developer Forum
       – Pretty active with experts to answer questions
24
          • http://groups.google.com/group/Google-Web-Toolkit
Other GWT Plugins for Eclipse
     • Cypal Studio
       – Simplifies many of the tedious RPC steps covered later
          • Especially keeping normal and Async versions in synch
          • But this support expected in official Google Eclipse Plugin
            eventually
       – Simple to use, free, open source, relatively weak
          • http://www cypal in/studio
            http://www.cypal.in/studio
     • GWT Designer
       – Simplifies project and RPC creation
       – Drag-and-drop GUI builder
       – Powerful, complex, commercial product
          • http://www.instantiations.com/gwtdesigner/

25




                                                                                                  © 2009 Marty Hall




                      Creating Eclipse
                             j
                         Projects

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.
General Application
     Development Approach
     • Create a new project
       – Cli k “g” (New Web Application Project) button at top
         Click “ ” (N W b A li ti P j t) b tt            tt
       – Enter project name and base package name
       – Delete extraneous files
     • Edit auto-generated HTML file
       – war/MyApp.html
     • Edit auto generated Java file
            auto-generated
       – src/package.client/MyApp.java
     • Test in hosted mode
       – Cli k Run arrow at top
         Click R          tt
     • Test in local Web mode
       – Click “Compile/Browse” from hosted mode browser
                   p
     • Deploy to Web server
       – Copy and rename “war” folder, deploy to any Java server
27




     Making and Testing Sample
     Project
     • Create a new project
       – Click g (New Web Application Project) button at top
       – Enter project name and base package name
     • Test in hosted mode
       – Click Run arrow at top
          • “Hosted mode” means that client side code runs in Java,
             Hosted mode             client-side
            so Java debugger can be used, print statements go to
            Java console, and changes are deployed automatically
     • Test in local Web mode
       – Click “Compile/Browse” from hosted mode browser
          • “Web mode” means that client-side Java code is compiled
            to JavaScript and then executed in normal browser
                   S

28
Creating a New Project
     • Click “g” at top
       – Or File  New 
         Web Application Project
     • Enter info
       – Choose project name
         and base package
                  p    g
         name
       – Use default SDK
         settings
       – Press Finish



29




     Resulting Eclipse Project
                                             Client-side code must be in “client” package. Server-side code can
                                             also import and use classes in this package (other than main app).
                                             All code in this package will eventually get translated into JavaScript.


                                            Samples. You can use these files as examples upon which to model
                                            your code, but in real projects you will delete them.


                                       Starting point client-side code. You will edit this extensively.




                                         If you have done “Compile/Browse” (see later slides on Web Mode), you
                                         can find this folder on the file system, copy it, rename it to “MyGwtApp”
                                         (or
                                         ( any other name), and deploy it to a Java-based server.
                                                  th         ) dd l           t J      b d



                        Created the first time you run the app. When you do
                        “Compile/Browse” (see later slides on Web Mode), this folder g
                             p               (                           ),          gets
                        populated with JavaScript files.

                                   Starting point HTML file. You will edit this extensively.

30
Testing the Project in Hosted Mode

     • Idea
         – New projects have
           sample behavior
           built in
     • Steps
         – Click on app name
                      pp
           in left window
         – Press Green Run
           arrow at top
         – Or, R-click project
           and Run As 
           Web Application
     Note: “hosted mode” means running entirely within IDE in Java. IDE has embedded version of the Jetty server bundled.
            • Code almost always runs identically once deployed in a regular browser, but hosted mode lets you use the Java
31            console (System.out.println) and Eclipse debugger (breakpoints, etc.)




     Testing the Project in Local Web
     Mode
                                                                                            Press this in hosted mode browser.

                                                                                            Page will pop up in normal Web
                                                                                            browser, running with only HTML
                                                                                            and JavaScript.




32
Deploying the Project to Normal
     Java App Server
     • Idea
       – O
         Once you hhave ddone C
                              Compile/Browse, the “war” folder
                                    il /B      h “    ” f ld
         contains a portable exploded Web app
     • Deploying as exploded app (folder)
         p y g        p       pp (      )
       –   Press Compile/Browse to build JavaScript files
       –   Copy “war” folder to another location
       –   Rename “war” folder (e.g., MyDeployedGwtApp)
                    war         (e g
       –   Copy new folder to server’s deployment directory
     • Deploying as zipped app (WAR file)
       –   Press Compile/Browse to build JavaScript files
       –   Create empty ZIP file (e.g., MyDeployedGwtApp.zip)
       –   Copy contents of “war” folder into ZIP file
                             war
       –   Change extension to .war (e.g., MyDeployedGwtApp.war)
       –   Copy WAR file to server’s deployment directory
33




     Deploying the Project to Normal
     Java App Server: Results




34
© 2009 Marty Hall




                      Developing GWT
                       Applications
                         pp

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     General Application
     Development Approach
     • Create a new project
       – Cli k “g” (New Web Application Project) button at top
         Click “ ” (N W b A li ti P j t) b tt            tt
       – Enter project name and base package name
       – Delete extraneous files
     • Edit auto-generated HTML file
       – war/MyApp.html
     • Edit auto generated Java file
            auto-generated
       – src/package.client/MyApp.java
     • Test in hosted mode
       – Cli k Run arrow at top
         Click R          tt
     • Test in local Web mode
       – Click “Compile/Browse” from hosted mode browser
                   p
     • Deploy to Web server
       – Copy and rename “war” folder, deploy to any Java server
36
Editing Auto-Generated HTML
     File
     • File location
       – war/AppName.html
     • Required script
       – GWT b ild <script…> tag in head section. Leave this
               builds      i        i h d       i   L       hi
         unchanged.
       – Entire rest of sample HTML file can be deleted and
                           p
         replaced with custom content.
     • Usual body content
       – Give ids to sections where buttons, textfields, and output
         will go. Usually div, span, td, or th elements.
          • <span id sectionForButton1
             span id="sectionForButton1"></span>
                                          /span


37




     Editing Auto-Generated Java
     Class
     • File location
       – src/package.client/AppName.java
     • Required structure
       – Cl must implement E
         Class      i l         EntryPoint and contain
                                     P i     d      i
         onModuleLoad method. Entire rest of sample Java class
         can be deleted and replaced with custom content.
                              p
     • Usual code
       – Create a control
          • Button button1 = new Button("Press Here");
       – Give it an event handler
          • button1.addClickHandler(new Button1Handler());
       – Insert the control into the page
          • RootPanel.get("sectionForButton1").add(button1);
38
Auto-Generated Java Class:
     Minimal Structure
     package packageName.client;

     import com.google.gwt.core.client.*;
     import com.google.gwt.user.client.ui.*;
     import com google gwt event dom client *;;
            com.google.gwt.event.dom.client.*;;

     public class AppName implements EntryPoint {
       public void onModuleLoad() { // M i entry point
         bli    id   M d l L d()        Main   t   i t

         }
     }




39




     Example: Button that Generates
     Random Number (On Client)
     • Created GwtApp1 project
         – Clicked on blue “g” (New Web Application Project)
             • Could also do File  New  Web Application Project
         – Project Name: GwtApp1, Package: coreservlets
                         GwtApp1
     • HTML
         – war/GwtApp1.html
                   pp
             • Need regions whose ids (not names!) are
               randomNumberButton and randomNumberResult
     • Java
         – src/coreservlets.client/GwtApp1.java
             • Button named randomNumberButton
             • HTML (label) named randomNumberResult
             • Button’s event handler should insert value into HTML
40
Deleting Extraneous Files
     • Motivation
          – N apps contain sample files that are good examples to learn
            New              i      l fil h           d        l  l
            from, but that should be deleted from new projects
     • Files to delete
          – Under src/package.client
               • GreetingService.java
               • GreetingServiceAsync.java
                        g          y j
          – Under src/package.server
               • GreetingServiceImpl.java
          – Under war
               • AppName.css (replace with own style sheet in subfolder)
     • Files to edit
          – war/WEB INF/web xml
            war/WEB-INF/web.xml
               • Remove servlet-mapping for GreetingServiceImpl
               • Forgetting this step will result in errors at server startup
41




      Auto-Generated HTML File


                                    Created and edited by hand. See slides at end of section on overriding standard styles.



                                          Created automatically, but needs extensive editing.
                                          Top shown below.


     <!DOCTYPE ...>
      !
     <html xmlns="http://www.w3.org/1999/xhtml">
     <head><title>First GWT App</title>
     <link rel="stylesheet"
                  y                                                 This code edited by hand
                                                                                         hand.
           href="./css/styles.css"                                  Use normal HTML (usually xhtml).
           type="text/css"/>
     <script type="text/javascript" language="javascript"
             src= gwtapp1/gwtapp1.nocache.js ></script>
             src="gwtapp1/gwtapp1 nocache js"></script>
     </head>
                                     Inserted automatically by GWT. Leave it in unchanged.
     <body>                          Entire rest of file can be modified in any way. There is
42
                                                                an iframe in the body that is sometimes useful to have.
Auto-Generated HTML File:
      Continued
     ...
     <fieldset>
     <legend>Client-Side Data</legend>
     <table border="1">
       <tr><th>User Control</th>
           <th>Result</th></tr>
       <tr><td id="randomNumberButton"></td>
           <td id="randomNumberResult"></td></tr>
       ...
     </table><br/>
     </fieldset>                       These names will be referred to in Java code.
     ...                               In these simple examples we create one HTML
                                       section for each low-level GWT widget. But in
     </body>                           more advanced applications, it is common to
     </html>                           put GWT panels into HTML sections, and then
                                       put multiple GWT widgets in the panels. It is
                                                                      even possible to build a GUI completely with
                                                                      GWT, where the HTML just has one blank div
                                                                      section that will contain the main GWT panel.


43




      Auto-Generated Java Class

                                  Created automatically, but need extensive editing. Shown below.
                                                      y,                          g




                                     Created by hand. Will be used later in this tutorial.
                                                hand                             tutorial




     package coreservlets.client;
        k            l     li
     import com.google.gwt.core.client.*;
     import com.google.gwt.user.client.ui.*;                                                  Created automatically.
                                                                                              Your code should be
     import com.google.gwt.event.dom.client.*;
     i    t         l    t     t d    li t *                                                  called by onModuleLoad.
                                                                                                ll d b    M d l L d



     public class GwtApp1 implements EntryPoint {
       public void onModuleLoad() {
         …
       }
44
     }
Auto-Generated Java Class:
         Continued
     public class GwtApp1 implements EntryPoint {
       public void onModuleLoad() { // Main entry point
         buttonSetup();
                                       Button is builtin GWT class. All standard HTML controls have corresponding
         listSetup();                  GWT Swing-like classes. GWT also defines many extended components that are
                                       combinations of HTML elements.
       }

         private void buttonSetup() {
           Button randomNumberButton = new Button("Show Random Number");
           HTML randomNumberResult = new HTML("<i>Num will go here</i>");
           randomNumberButton.addClickHandler
             (new RanNumHandler(randomNumberResult));
                     g
           RootPanel.get("randomNumberButton").add(randomNumberButton);
           RootPanel.get("randomNumberResult").add(randomNumberResult);
         }
         ...
                                                                                  Matches ids in the HTML
     }


45




         Auto-Generated Java Class :
         Continued
                                                                    Using an inner class for event handling. Alternative
                                                                    approaches discussed in upcoming section on GWT events.




         private class RanNumHandler implements ClickHandler {
            private HTML resultRegion;

              public RanNumHandler(HTML resultRegion) {
                this.resultRegion = resultRegion;
                thi      ltR i          ltR i
              }

              public void onClick(ClickEvent event) {
                bli    id   Cli k(Cli kE   t     t)
                resultRegion.setText("Number: " + Math.random()*10);
              }
          }

                Whenever user clicks button, insert this string into the GWT HTML object
                (which is really a div).
46
Testing in Hosted Mode
       – Click project name in Eclipse. Press Run button at top
       – Or, R-click project name and Run As  Web Application
                                                         When first brought up.

                                                         After pressing button.




47




     Testing in Local Web Mode
     • Idea
       –RRunning in Web mode means running in a regular
              i i W b         d              i i        l
         browser with all client-side Java code converted to
         JavaScript
       – Uses embedded version of Jetty server on local machine
     • Steps
       – Run the application in hosted mode
       – Click the “Compile/Browse” button at top of hosted-
         mode browser.
       – Result:
          • Creates JavaScript files in war/appname folder
          • Loads the main HTML file in your default browser
              – You can copy this URL to other browsers to test cross-browser
                compatibility
48
Testing in Local Web Mode
                                                            Press this in hosted mode
                                                            browser.

                                                            Page will pop up in default
                                                            system browser, running with
                                                            only HTML and JavaScript.




49




     Testing in Deployed Mode
     • Idea
       – D l d mode is similar to Local Web mode
         Deployed d i i il        L lW b      d
          • Running in a regular browser with all client-side Java code
            converted to JavaScript
          • However uses normal Web App structure running on a
            However,
            Java server of your choice on any machine
     • Steps
       – Run the application in hosted mode
       – Click the “Compile/Browse” button
          • Do this immediately before deploying so you have
            JavaScript files corresponding to most recent Java code
       – Find the “war” folder on filesystem
          • Copy/rename and deploy as exploded WAR
          • Or, copy contents (not “war” folder itself) into file.zip, then
            rename file.zip to file.war and deploy as WAR file
50
Testing in Deployed Mode
     • Copied workspace/project/war folder
       – Renamed to GwtApp1 to keep similar-looking URL
          • GwtApp1.html is welcome-file, so name can be omitted
       – Deployed to Apache Tomcat on localhost
          • Could have used any Java-capable server




51




                                                                                                  © 2009 Marty Hall




                         Using Auxiliary
                          Java Classes

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.
Big Idea
     • Use regular Java for client-side code
        – Normal Java 1.6 syntax
             • Classes, methods, constructors, loops, control statements, etc.
         – Supporting classes
             • Static methods in the Math class and many common data structures
                 – St i
                   String, array, Li t (A
                                    List (ArrayList, Li k dLi t) M (H hM and others), D t etc.
                                               Li t LinkedList), Map (HashMap d th ) Date, t
                 – For full list, see http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html
         – Custom GWT classes
             • Class defined for each type of standard HTML control
                 – Button, Checkbox, Image, Hyperlink, RadioButton, etc.
             • GWT also provides classes for groups of HTML controls
                 – SuggestBox, SimplePanel, TabPanel, ScrollPanel, Tree, FlexTable, PopupPanel, etc.
     • Java gets translated into JavaScript
            g
        – Click Compile/Browser to generate JavaScript
        – But you develop and test using Java only
     • Restrictions
        – N t all collections or classes supported
          Not ll ll ti            l            t d
        – Custom classes must be placed in “...client” package.
53




      Example: Linked Comboboxes
      (Choosing State Results in List of Associated Cities)
     • Eclipse Project: GwtApp1
         –S
          Same project as i previous example
                  j       in    i         l
     • HTML: GwtApp1.html
         – Need regions with ids stateList and cityList
     • Java:
         – GwtApp1.java: main application class
             • D fi
               Defines two li b
                           listboxes
             • Attaches event handler to listbox that stores state names
         – StateInfo.java (must be in ...client package)
             • Associates state name with array of cities
             • Defines static method with list of common states
     • Note
         – In AjaxTags section, we matched cities to states using
           server-side code. Using custom Java classes greatly
54
           simplifies client-side code.
Editing Auto-Generated Files
     •    Edit AppName.html and give ids to sections
          – Gi ids to sections where buttons, textfields, and output will go
            Give id       i     h b               fi ld     d         ill
                   <tr><td>State: <span id="stateList"></span></td>
                       <td>City: <span id="cityList"></span></td></tr>
     •    Edit AppName.java
             •   Code called by auto-generated onModuleLoad method
          1. Create controls
                 stateList = new ListBox();
                 cityList = new ListBox();
          2. Define event handlers
                 stateList.addChangeHandler(new StateHandler());
          3. Insert in HTML page
                 RootPanel.get( stateList ).add(stateList);
                 RootPanel.get("stateList").add(stateList);
                 RootPanel.get("cityList").add(cityList);

55




         Auto-Generated HTML File
     • Same file as in earlier example
          – war/GwtAppl.html
          – Needs auto-generated script tag in the head section
     • Body
          <fieldset>
          <legend>Client-Side Data</legend>
          <table b d
           t bl border="1">
                        "1"
            <tr><th>User Control</th>
                <th>Result</th></tr>
            <tr><td id= randomNumberButton ></td>
                    id="randomNumberButton"></td>
                <td id="randomNumberResult"></td></tr>
            <tr><td>State: <span id="stateList"></span></td>
                <td>City: <span id="cityList"></span></td></tr>
                                 id cityList ></span></td></tr>
          </table><br/>
          </fieldset>
56
Auto-Generated Java Class
     • Same file as in earlier example
          – C ll d src/coreservlets.client.GwtApp1.java
            Called /            l    li G A 1 j
          – Has three sets of import statements
          – Has auto-generated features
                      g
                • implements EntryPoint
                • onModuleLoad method

     package coreservlets.client;

     import com.google.gwt.core.client.*;
     import com.google.gwt.user.client.ui.*;
     import com.google.gwt.event.dom.client.*;

     public class GwtApp1 implements EntryPoint {
       public void onModuleLoad() { // Main entry point
57




      Auto-Generated Java Class:
      Continued
     public class GwtApp1 implements EntryPoint {
       p
       public void onModuleLoad() { // Main entry p               y point
         buttonSetup();
         listSetup();                 ListBox is builtin GWT class. All standard HTML controls have corresponding
       }                              GWT Swing-like classes. GWT also defines many extended components that are
                                      combinations of HTML elements.
       // buttonSetup shown earlier

        private void listSetup() {
          ListBox stateList = new ListBox();
          populateStateList(stateList);
          stateList.setVisibleItemCount(1);            Matches ids in the HTML
          ListBox cityList = new ListBox();
          cityList.addItem("Select City");
          cityList.setVisibleItemCount(1);
           it Li t   tVi ibl It C     t(1)
          cityList.setEnabled(false);
          stateList.addChangeHandler(new StateHandler(stateList,
                                                      cityList));
          RootPanel.get("stateList").add(stateList);
          RootPanel.get("cityList").add(cityList);
        }
58
Auto-Generated Java Class:
     Continued


     p
     private void populateStateList(ListBox stateList) {
                   p p              (                )
         stateList.addItem("Select State");
         StateInfo[] nearbyStates =
           StateInfo.getNearbyStates();
         for(StateInfo state: nearbyStates) {
           stateList.addItem(state.getStateName());
         }
       }


                            Unlike l
                            U lik early GWT versions, you can use J
                                                  i                  Java 5 and 6 f t
                                                                              d features ((e.g., new-style for/each l
                                                                                                      t l f / h loop) f client-side
                                                                                                                       ) for li t id
                            code. However, you are limited in what classes are supported for client-side code. For a complete list, see
                            http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html. For server-side code (see later tutorial
                            section), you can use any features of the Java version your server is using.

59




     Auto-Generated Java Class:
     Continued
     private class StateHandler implements ChangeHandler {
        private ListBox stateList, cityList;

          public StateHandler(ListBox stateList, ListBox cityList) {
            this.stateList = stateList;
            this.cityList = cityList;
          }

          public void onChange(ChangeEvent event) {
            int index = stateList.getSelectedIndex();
            String state = stateList.getItemText(index);
               i                 i              (i d )
            StateInfo[] nearbyStates =
              StateInfo.getNearbyStates();
            String[] cities =
              StateInfo.findCities(nearbyStates, state);
              St t I f fi dCiti (      b St t     t t )
            cityList.clear();
            for(String city: cities) {
              cityList.addItem(city);
            }
            cityList.setEnabled(true);
          }
60
      }
Helper Class (StateInfo)
     package coreservlets.client;
                                                                  Must be in same package as AppName.java.
                                                                  (...client). Only classes in this package
                                                                  are translated into JavaScript.
     public class StateInfo {
       private String stateName;
       private String[] cities;

       public StateInfo(String stateName, String[] cities) {
         this.stateName = stateName;
         this.cities
         this cities = cities;
       }

       p
       public String getStateName() {
                   g g           ()
         return(stateName);
       }

       public String[] getCities() {
         bli St i []     tCiti ()
         return(cities);
       }
61




      Helper Class
      (StateInfo,
      (StateInfo Continued)
       private static String[] mdCities =
         { Baltimore , Frederick , Gaithersburg , Rockville };
         {"Baltimore", "Frederick","Gaithersburg","Rockville"};
       private static String[] vaCities =
         {"Virginia Beach","Norfolk","Chesapeake","Arlington"};
       private static String[] paCities =
         {"Philadelphia","Pittsburgh","Allentown","Erie"};
       private static String[] njCities =
         {"Newark", "Jersey City","Paterson","Elizabeth"};
       private static String[] nyCities =
         {"New York", "Buffalo","Rochester","Yonkers"};
       private static StateInfo[] nearbyStates =
         { new StateInfo("Maryland", mdCities),
                        (    y     ,         ),
           new StateInfo("Virginia", vaCities),
           new StateInfo("Pennsylvania", paCities),
           new StateInfo("New Jersey", njCities),
           new St t I f ("N
               StateInfo("New York", nyCities)
                              Y k"     Citi )
         };
                               Can use arrays, ArrayList, HashMap, String, Date, custom classes, etc. GWT does not
                               support every standard Java class on client, but a large set of them. For full list, see
62                             http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html
Helper Class
      (StateInfo,
      (StateInfo Continued)
       public static StateInfo[] getNearbyStates() {
         return(nearbyStates);
       }

      public static String[] findCities(StateInfo[] states,
                                         String stateName) {
         for(StateInfo state: states) {
           if(state.getStateName().equals(stateName)) {
             return(state.getCities());
             return(state getCities());
           }
         }
         String[] unknown = {
              g[]           {"Unknown state"};
                                            }
         return(unknown);
       }
     }



63




      Testing in Hosted Mode
        – Click project name in Eclipse. Press Run button at top
        – Or, R-click project name and Run As  Web Application
                                             When first brought up.

                                             After selecting state
                                                             state.
                                             (Cities selected to illustrate contents)




64
Testing in Local Web Mode
                                                      Press this in hosted mode
                                                      browser.

                                                      Page will pop up in default
                                                      system browser, running with
                                                      only HTML and JavaScript on
                                                      client side.




65




     Testing in Deployed Mode
     • workspace/project/war
       – Renamed to GwtApp1 to keep similar-looking URL
       – Deployed to Apache Tomcat on localhost
          • Could have used any Java-capable server
                                Java capable




66
© 2009 Marty Hall




              Overriding Standard
                  CSS Styles
                         y

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Auto-Loaded Style Sheet in
     Auto-Generated HTML File
     • Idea
       – Th JavaScript file automatically inserts
         The J S i fil               i ll i
         <link rel="stylesheet" href="…/standard.css">
         at end of head section.
     • Good news
       – There are styles such as gwt-Button and gwt-HTML that
         let you customize the look of all GWT widgets
       – There are three predefined themes (standard, dark,
         chrome) that you can switch among
     • Bad news
       – The automatic stylesheet is loaded after yours. So, it
         overrides your entries, not vice versa.
       – It gives styles for body, td, select, pre, and a.
       – Cannot edit it: gets rebuilt when you do Compile/Browse
68
Simple Usage: Overriding
     Standard Styles
     • Mark your styles with !important
       – End your entries with !important so that they won’t be
         overridden by standard.css.
       – Only needed for body, td select pre, and a.
                          body td, select, pre     a
          • body { background-color: red !important; … }
            td { font-size: 103px !important; … }
     • O use explict CSS class names
       Or,      li t      l
       – Don’t give styles to those five HTML element names, but
         instead use CSS class names
          • CSS:
            .mybodystyle { background-color: red; … }
            .bigcell { font size: 103px; …
                       font-size:
          • HTML:
            <body class="mybodystyle">
69          <td class="bigcell">




     Advanced Usage: Loading
     Stylesheets Manually
     • Edit src/packageName/AppName.gwt.xml
       – Change <inherits name='… .Standard'/> to
         <inherits name='… .StandardResources'/>
          • This causes stylesheet to be output under war folder but
                                                          folder,
            not loaded
     • Load the GWT stylesheet first
       – <link rel="stylesheet"
               href="./appname/gwt/standard/standard.css">
     • Load your stylesheet second
       – <link rel="stylesheet" href="./css/mystyles.css">



70
styles.css from GwtApp1
     body { background-color: #fdf5e6 !important }
     td { font-size: 18px !important;
          font size:
          font-family: Arial, Helvetica, sans-serif !important;
     }                                              Entries for body and td marked as !important
                                                    because body and td defined in standard.css.
     …                                              This approach is recommended for GWT
                                                    beginners.
     th { background-color: #ef8429;
          font-size: 18px;
          font family:
          font-family: Arial, Helvetica, sans serif;
                                         sans-serif;
     }
     legend {
       font-weight: bold;
               g        ;
                                         Entries for other elements not marked with !important
       color: black;                     because they are not defined in standard.css
       background-color: #eeeeee;
       border: 1px solid #999999;
                p
       padding: 3px 2px;
     }
71




      Advanced Usage: Loading
      Stylesheets Manually
     • src/packageName/GwtApp1.gwt.xml
         – Change
              • <inherits
                name com.google.gwt.user.theme.standard.Standard /
                name='com.google.gwt.user.theme.standard.Standard'/>
         – to
              • <inherits
                name= com.google.gwt.user.theme.standard.StandardResources />
                name='com google gwt user theme standard StandardResources'/>
     • Auto-generated HTML file
         – Load standard.css and custom stylesheet. If you load your
           custom stylesheet second, its entries override earlier ones.
              • <link rel="stylesheet"
                      href= /gwtapp1/gwt/standard/standard css">
                      href="./gwtapp1/gwt/standard/standard.css >
                <link rel="stylesheet"
                      href="./css/mystyles.css">
72
© 2009 Marty Hall




                                        Wrap-Up

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Summary
     • Create an Eclipse application
       – Press “g” button at top, or File  New  Web Application Project
                g            top
     • Edit auto-generated HTML (AppName.html)
       – Give ids to regions where controls will be placed
           • But see later section on panels You might have few (one?) region
                                      panels.                          region.
     • Edit auto-generated Java (AppName.java)
       – Edit onModuleLoad
           • Create controls
                     controls.               Button b = new Button( );
                                                            Button(...);
           • Give them event handlers.       b.addClickHandler(…);
           • Insert controls into HTML page. RootPanel.get("id").add(b);
     • Test in hosted mode (always)
       – Click Run button at top or R-click  Run As  Web App
     • Test in local Web mode (occasionally)
       – Press C
               Compile/Browse in hosted mode b
                   il /       i h     d   d browser
     • Deploy to normal Java server (at end)
74     – Copy/rename “war” folder or put contents into .war file
© 2009 Marty Hall




                         Questions?

              Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Contenu connexe

Tendances

Tendances (19)

Alpes Jug (29th March, 2010) - Apache Maven
Alpes Jug (29th March, 2010) - Apache MavenAlpes Jug (29th March, 2010) - Apache Maven
Alpes Jug (29th March, 2010) - Apache Maven
 
Performance tuning the Spring Pet Clinic sample application
Performance tuning the Spring Pet Clinic sample applicationPerformance tuning the Spring Pet Clinic sample application
Performance tuning the Spring Pet Clinic sample application
 
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
JavaCro'21 - Java is Here To Stay - HUJAK KeynoteJavaCro'21 - Java is Here To Stay - HUJAK Keynote
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
 
Lausanne Jug (08th April, 2010) - Maven
Lausanne Jug (08th April, 2010) - MavenLausanne Jug (08th April, 2010) - Maven
Lausanne Jug (08th April, 2010) - Maven
 
Riviera JUG (20th April, 2010) - Maven
Riviera JUG (20th April, 2010) - MavenRiviera JUG (20th April, 2010) - Maven
Riviera JUG (20th April, 2010) - Maven
 
Introduction in Apache Maven2
Introduction in Apache Maven2Introduction in Apache Maven2
Introduction in Apache Maven2
 
QEWD.js: Have your Node.js Cake and Eat It Too
QEWD.js: Have your Node.js Cake and Eat It TooQEWD.js: Have your Node.js Cake and Eat It Too
QEWD.js: Have your Node.js Cake and Eat It Too
 
Apache Maven - eXo TN presentation
Apache Maven - eXo TN presentationApache Maven - eXo TN presentation
Apache Maven - eXo TN presentation
 
Java 9 Module System Introduction
Java 9 Module System IntroductionJava 9 Module System Introduction
Java 9 Module System Introduction
 
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
 
Geneva Jug (30th March, 2010) - Maven
Geneva Jug (30th March, 2010) - MavenGeneva Jug (30th March, 2010) - Maven
Geneva Jug (30th March, 2010) - Maven
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
 
The Modern Java Web Developer - JavaOne 2013
The Modern Java Web Developer - JavaOne 2013The Modern Java Web Developer - JavaOne 2013
The Modern Java Web Developer - JavaOne 2013
 
Javantura Zagreb 2014 - Vaadin - Peter Lehto
Javantura Zagreb 2014 - Vaadin - Peter LehtoJavantura Zagreb 2014 - Vaadin - Peter Lehto
Javantura Zagreb 2014 - Vaadin - Peter Lehto
 
Groovy Testing Sep2009
Groovy Testing Sep2009Groovy Testing Sep2009
Groovy Testing Sep2009
 
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
 
Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)
 
4 maven junit
4 maven junit4 maven junit
4 maven junit
 
Lorraine JUG (1st June, 2010) - Maven
Lorraine JUG (1st June, 2010) - MavenLorraine JUG (1st June, 2010) - Maven
Lorraine JUG (1st June, 2010) - Maven
 

En vedette

lecture2-PerlProgramming
lecture2-PerlProgramminglecture2-PerlProgramming
lecture2-PerlProgramming
tutorialsruby
 
Historia de la salchipapa herrera avalos
Historia de la salchipapa     herrera   avalosHistoria de la salchipapa     herrera   avalos
Historia de la salchipapa herrera avalos
Gregory Herrera
 
Internation Journal Conference
Internation Journal ConferenceInternation Journal Conference
Internation Journal Conference
Hemanth Kumar
 

En vedette (14)

Historia de la Filosofía Tomo I
Historia de la Filosofía Tomo IHistoria de la Filosofía Tomo I
Historia de la Filosofía Tomo I
 
Clipping cnc 23022016 versão de impressão
Clipping cnc 23022016   versão de impressãoClipping cnc 23022016   versão de impressão
Clipping cnc 23022016 versão de impressão
 
Docker para desarrolladores .NET
Docker para desarrolladores .NETDocker para desarrolladores .NET
Docker para desarrolladores .NET
 
Trabajo 6 andrade alexis vision
Trabajo 6 andrade alexis visionTrabajo 6 andrade alexis vision
Trabajo 6 andrade alexis vision
 
lecture2-PerlProgramming
lecture2-PerlProgramminglecture2-PerlProgramming
lecture2-PerlProgramming
 
Planeación grillito y cocuyo
Planeación grillito y cocuyoPlaneación grillito y cocuyo
Planeación grillito y cocuyo
 
Sports Association
Sports Association Sports Association
Sports Association
 
Historia de la salchipapa herrera avalos
Historia de la salchipapa     herrera   avalosHistoria de la salchipapa     herrera   avalos
Historia de la salchipapa herrera avalos
 
Internation Journal Conference
Internation Journal ConferenceInternation Journal Conference
Internation Journal Conference
 
Que sont ils-devenus ?
Que sont ils-devenus ?Que sont ils-devenus ?
Que sont ils-devenus ?
 
C8 - Jihad
C8 - JihadC8 - Jihad
C8 - Jihad
 
Admin
AdminAdmin
Admin
 
Apps como estrategia de servicio al cliente
Apps como estrategia de servicio al clienteApps como estrategia de servicio al cliente
Apps como estrategia de servicio al cliente
 
hailpern-interact09
hailpern-interact09hailpern-interact09
hailpern-interact09
 

Similaire à GWT-Basics

Gwt overview & getting started
Gwt overview & getting startedGwt overview & getting started
Gwt overview & getting started
Binh Bui
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
snopteck
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
snopteck
 
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
Fred Sauer
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
Ramamohan Chokkam
 

Similaire à GWT-Basics (20)

Gwt overview & getting started
Gwt overview & getting startedGwt overview & getting started
Gwt overview & getting started
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
The Java alternative to Javascript
The Java alternative to JavascriptThe Java alternative to Javascript
The Java alternative to Javascript
 
Java script core
Java script coreJava script core
Java script core
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
MWLUG - Universal Java
MWLUG  -  Universal JavaMWLUG  -  Universal Java
MWLUG - Universal Java
 
GWT HJUG Presentation
GWT HJUG PresentationGWT HJUG Presentation
GWT HJUG Presentation
 
Gwt Presentation1
Gwt Presentation1Gwt Presentation1
Gwt Presentation1
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
Polygot Java EE on the GraalVM
Polygot Java EE on the GraalVMPolygot Java EE on the GraalVM
Polygot Java EE on the GraalVM
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and Gaelyk
 
01 java intro
01 java intro01 java intro
01 java intro
 
The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011
 
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
 
GWT Reloaded
GWT ReloadedGWT Reloaded
GWT Reloaded
 
Polyglot Applications with GraalVM
Polyglot Applications with GraalVMPolyglot Applications with GraalVM
Polyglot Applications with GraalVM
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 

Plus de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 

Plus de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

GWT-Basics

  • 1. © 2009 Marty Hall The Google Web Toolkit ( g (GWT): ) Basics ( (GWT 1.7 Version) ) Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/gwt.html p g Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2009 Marty Hall For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. t htt // l t / Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your organization. •C Courses d developed and t l d d taught b M t H ll ht by Marty Hall – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics – Ajax courses can concentrate on EElibrary (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several Customized Java one Training: http://courses.coreservlets.com/ • Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. JSP, JSF 1.x & JSF EJB3, Ruby/Rails Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets.com for details
  • 2. Topics in This Section • Pros and cons of GWT • Installing GWT • Development process – Making a project – Editing auto-generated HTML file – Editing auto-generated Java class auto generated • Testing process – Hosted mode – Local Web mode – Deployed mode • Quick preview: client-side event handlers 5 • Quick preview: custom Java classes © 2009 Marty Hall Motivation Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. Why Ajax? • HTML and HTTP are weak –N i Non-interactive i – Coarse-grained updates • Everyone wants to use a browser – Not an application that requires SW installation • “Real” browser-based active content – Failed: Java Applets • Not universally supported; can’t interact with the HTML – Serious alternative: Flash (and Flex) ( ) • Not yet universally supported; limited power – New and unproven • Microsoft Silverlight • JavaFX • Adobe AIR (formerly “Apollo”) 7 Traditional Web Apps vs. Ajax Apps Infrequent large updates Frequent small updates 8 Diagrams from Ajax in Action by Dave Crane et al, Manning Press. See recommended books in next lecture.
  • 4. Google Home Page (formerly Google Suggest) 9 Ajax Jobs (as of Sept. 2009) Indeed.com compiles data from many jobs sites 10
  • 5. Ajax Problems that GWT Tries to Address • At least two languages are required – JavaScript on the client – Java or another language on the server • Invoking server is cumbersome – Even with JSON-RPC or jQuery support – Want more powerful RPC mechanism • JavaScript scales poorly to large projects – No strong typing g yp g – Weak object hierarchies – Many run-time errors instead of compile-time errors – Incompatibility across platforms – Can’t use preexisting Java libraries or utilities 11 GWT Jobs (Absolute and Relative) 12
  • 6. © 2009 Marty Hall Overview and Installation Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Overview of the Google Web Toolkit (GWT) • Big Idea – You write both client-side and server-side code in Java – Client-side code • Uses an API similar to Swing • Most basic JDK 1.6 constructs and classes supported • Gets compiled into JavaScript that runs in your browser –S Server-side code id d • Client uses a callback API and specifies data source URL – Once you define callback, you are mostly using regular Java method calls with complex arguments and return values • Server extends special class and defines regular methods – These are not servlet-style doBlah methods linked to HTTP – Arguments and return values can be » Primitives, Strings, arrays, a few java.util collections, Serializable custom classes 14
  • 7. Sites that Use GWT • Google Sites – Google Base, Google Wave, Google Checkout, Google Web Content Manager • kaching.com • gogrid.com • contactoffice.com • riflethru.com • scenechronize.com • whirled.com 15 Advantages of GWT • No JavaScript syntax errors – Use a reliable, strongly-typed language (Java) for development and reliable strongly typed debugging – No JavaScript programming at all! • Can use complex Java on the client – Turned into JavaScript, but you still use String, array, Math class, ArrayList, HashMap, custom classes, etc. – Full IDE-based Java support for development and debugging IDE based • Can send complex Java types to/from the server – Data gets serialized across network. – More powerful and convenient approach than JSON RPC or DWR JSON-RPC DWR. • Standalone test environment – Can test within Eclipse without installing a server • Support by major company – Supported by the company that popularized Ajax in the first place – Support won’t go away like perhaps with AjaxTags 16
  • 8. Disadvantages of GWT • Less incremental; big learning curve – Java developers can deploy with AjaxTags in just a few minutes, minutes whereas it takes much longer to get anything running with GWT. – JavaScript developers can adapt to new library (e.g., move from jQuery to Dojo) easily, whereas GWT seems foreign to them • N Nonstandard approach to HTML and JavaScript t d d ht dJ S i t – Programmatic creation of HTML can make use of standard HTML and CSS tools more difficult. – You never put direct JavaScript in your HTML HTML. • Very powerful in the long run, but hard to get used to at first. – Not search engine friendly • Google and others won’t index the dynamic content g y • Only for Java developers – Most Ajax environments do JavaScript on the client and have a choice for the server. GWT is based entirely around Java. • Unusual approach – Fundamentally different strategy than all other Ajax environments 17 makes evaluation and management buyoff harder Alternatives to GWT • Client-Side Tools – jQuery • http://www.jquery.org/ – Dojo (built on Prototype) • http://www.dojotoolkit.org/ p j g – script.aculo.us (built on Prototype) • http://script.aculo.us/ – ExtJS • htt // tj http://extjs.com/ (they also have native library f GWT) / (th l h ti lib for – Yahoo User Interface Library (YUI) • http://developer.yahoo.com/yui/ – Google Closure Library • http://code.google.com/closure/library/ • These are not mutually exclusive wrt GWT – You can wrap them in JSNI in GWT – But more common approach is to use the JS tools directly, refer to a URL, and use arbitrary technology on the server 18
  • 9. Alternatives to GWT (Continued) • Server-Side Tools – Direct Web Remoting • Lets you call Java methods semi-directly from JavaScript – But not as cleanly or with as powerful return types as with GWT • http://getahead.ltd.uk/dwr/ – JSON/JSON-RPC • For sending data to/from JavaScript with less parsing • http://www.json.org/ • http://json-rpc.org/ – JSP custom tag libraries • Create tags that generate into HTML and JavaScript – Use approaches from previous page, but hide details and simplify code for page developers • http://courses.coreservlets.com/Course-Materials/msajsp.html 19 Alternatives to GWT (Continued) • Hybrid Client/Server Tools – Aj T AjaxTags (built on top of script.aculo.us) (b il f i l ) • JSP custom tags that generate Ajax functionality – Supports many powerful Ajax capabilities with very simple syntax – htt // j t http://ajaxtags.sourceforge.net f t – JavaServer Faces (JSF) component libraries • Trinidad (formerly Oracle ADF) – htt // http://www.oracle.com/technology/products/jdev/htdocs/ l /t h l / d t /jd /htd / partners/addins/exchange/jsf/ (also myfaces.apache.org) • Tomahawk – http://myfaces.apache.org/tomahawk/ p y p g • Ajax4JSF – http://labs.jboss.com/jbossajax4jsf/ • IceFaces – http://www.icefaces.org/ • Build your own – http://courses.coreservlets.com/Course-Materials/jsf.html 20
  • 10. Installation: Overview • Download and install Google Eclipse Plugin • http://code.google.com/appengine/docs/java/tools/ eclipse.html – Includes core GWT libraries – Includes utilities for building, running, testing, and benchmarking GWT apps from within Eclipse – I l d utilities for the Google App Engine Includes tiliti f th G l A E i • Won’t be discussed here, but they do not interfere with using plugin for GWT for deployment on any Java server • GWT can also be used without Eclipse • http://code.google.com/webtoolkit/download.html – Some limited support for other IDEs – Comes with prebuilt ant scripts 21 – Not discussed in this tutorial Installation: Details (Eclipse 3 5 – Galileo) 3.5 • Go to Eclipse “Install New Software” page – Start Eclipse (3.5) – Help  Install New Software  Work With • Load plugin – Enter http://dl.google.com/ p g g eclipse/plugin/3.5 – Press “Add”, then “OK” (leave name blank) – Select all Plugin and SDK options p – Press “Next” (and finish) 22 – Restart Eclipse
  • 11. Installation: Details (Eclipse 3.4 – Ganymede) 34 • Go to Eclipse “Add Site” page – Start Eclipse (3.4) – Help  Software Updates  Available Software  Add Site • Load plugin – Enter http://dl.google.com/ eclipse/plugin/3.4 – Press “OK” – Select all Plugin and SDK options p – Press “Install” 23 – Restart Eclipse Documentation • GWT overview page – Good starting point with links to tutorials and docs. • http://code.google.com/webtoolkit/overview.html • Developer’s guide Developer s – Includes Quick Start guide and general approaches • http://code.google.com/webtoolkit/doc/1.6/DevGuide.html g g • Reference guide Note that they didn’t update URLs when GWT moved from 1.6 to 1.7. – Includes JavaDoc API, guide to which Java features are supported on client side, and widget library reference d li id d id lib f • http://code.google.com/webtoolkit/doc/1.6/RefGuide.html • Developer Forum – Pretty active with experts to answer questions 24 • http://groups.google.com/group/Google-Web-Toolkit
  • 12. Other GWT Plugins for Eclipse • Cypal Studio – Simplifies many of the tedious RPC steps covered later • Especially keeping normal and Async versions in synch • But this support expected in official Google Eclipse Plugin eventually – Simple to use, free, open source, relatively weak • http://www cypal in/studio http://www.cypal.in/studio • GWT Designer – Simplifies project and RPC creation – Drag-and-drop GUI builder – Powerful, complex, commercial product • http://www.instantiations.com/gwtdesigner/ 25 © 2009 Marty Hall Creating Eclipse j Projects Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 13. General Application Development Approach • Create a new project – Cli k “g” (New Web Application Project) button at top Click “ ” (N W b A li ti P j t) b tt tt – Enter project name and base package name – Delete extraneous files • Edit auto-generated HTML file – war/MyApp.html • Edit auto generated Java file auto-generated – src/package.client/MyApp.java • Test in hosted mode – Cli k Run arrow at top Click R tt • Test in local Web mode – Click “Compile/Browse” from hosted mode browser p • Deploy to Web server – Copy and rename “war” folder, deploy to any Java server 27 Making and Testing Sample Project • Create a new project – Click g (New Web Application Project) button at top – Enter project name and base package name • Test in hosted mode – Click Run arrow at top • “Hosted mode” means that client side code runs in Java, Hosted mode client-side so Java debugger can be used, print statements go to Java console, and changes are deployed automatically • Test in local Web mode – Click “Compile/Browse” from hosted mode browser • “Web mode” means that client-side Java code is compiled to JavaScript and then executed in normal browser S 28
  • 14. Creating a New Project • Click “g” at top – Or File  New  Web Application Project • Enter info – Choose project name and base package p g name – Use default SDK settings – Press Finish 29 Resulting Eclipse Project Client-side code must be in “client” package. Server-side code can also import and use classes in this package (other than main app). All code in this package will eventually get translated into JavaScript. Samples. You can use these files as examples upon which to model your code, but in real projects you will delete them. Starting point client-side code. You will edit this extensively. If you have done “Compile/Browse” (see later slides on Web Mode), you can find this folder on the file system, copy it, rename it to “MyGwtApp” (or ( any other name), and deploy it to a Java-based server. th ) dd l t J b d Created the first time you run the app. When you do “Compile/Browse” (see later slides on Web Mode), this folder g p ( ), gets populated with JavaScript files. Starting point HTML file. You will edit this extensively. 30
  • 15. Testing the Project in Hosted Mode • Idea – New projects have sample behavior built in • Steps – Click on app name pp in left window – Press Green Run arrow at top – Or, R-click project and Run As  Web Application Note: “hosted mode” means running entirely within IDE in Java. IDE has embedded version of the Jetty server bundled. • Code almost always runs identically once deployed in a regular browser, but hosted mode lets you use the Java 31 console (System.out.println) and Eclipse debugger (breakpoints, etc.) Testing the Project in Local Web Mode Press this in hosted mode browser. Page will pop up in normal Web browser, running with only HTML and JavaScript. 32
  • 16. Deploying the Project to Normal Java App Server • Idea – O Once you hhave ddone C Compile/Browse, the “war” folder il /B h “ ” f ld contains a portable exploded Web app • Deploying as exploded app (folder) p y g p pp ( ) – Press Compile/Browse to build JavaScript files – Copy “war” folder to another location – Rename “war” folder (e.g., MyDeployedGwtApp) war (e g – Copy new folder to server’s deployment directory • Deploying as zipped app (WAR file) – Press Compile/Browse to build JavaScript files – Create empty ZIP file (e.g., MyDeployedGwtApp.zip) – Copy contents of “war” folder into ZIP file war – Change extension to .war (e.g., MyDeployedGwtApp.war) – Copy WAR file to server’s deployment directory 33 Deploying the Project to Normal Java App Server: Results 34
  • 17. © 2009 Marty Hall Developing GWT Applications pp Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. General Application Development Approach • Create a new project – Cli k “g” (New Web Application Project) button at top Click “ ” (N W b A li ti P j t) b tt tt – Enter project name and base package name – Delete extraneous files • Edit auto-generated HTML file – war/MyApp.html • Edit auto generated Java file auto-generated – src/package.client/MyApp.java • Test in hosted mode – Cli k Run arrow at top Click R tt • Test in local Web mode – Click “Compile/Browse” from hosted mode browser p • Deploy to Web server – Copy and rename “war” folder, deploy to any Java server 36
  • 18. Editing Auto-Generated HTML File • File location – war/AppName.html • Required script – GWT b ild <script…> tag in head section. Leave this builds i i h d i L hi unchanged. – Entire rest of sample HTML file can be deleted and p replaced with custom content. • Usual body content – Give ids to sections where buttons, textfields, and output will go. Usually div, span, td, or th elements. • <span id sectionForButton1 span id="sectionForButton1"></span> /span 37 Editing Auto-Generated Java Class • File location – src/package.client/AppName.java • Required structure – Cl must implement E Class i l EntryPoint and contain P i d i onModuleLoad method. Entire rest of sample Java class can be deleted and replaced with custom content. p • Usual code – Create a control • Button button1 = new Button("Press Here"); – Give it an event handler • button1.addClickHandler(new Button1Handler()); – Insert the control into the page • RootPanel.get("sectionForButton1").add(button1); 38
  • 19. Auto-Generated Java Class: Minimal Structure package packageName.client; import com.google.gwt.core.client.*; import com.google.gwt.user.client.ui.*; import com google gwt event dom client *;; com.google.gwt.event.dom.client.*;; public class AppName implements EntryPoint { public void onModuleLoad() { // M i entry point bli id M d l L d() Main t i t } } 39 Example: Button that Generates Random Number (On Client) • Created GwtApp1 project – Clicked on blue “g” (New Web Application Project) • Could also do File  New  Web Application Project – Project Name: GwtApp1, Package: coreservlets GwtApp1 • HTML – war/GwtApp1.html pp • Need regions whose ids (not names!) are randomNumberButton and randomNumberResult • Java – src/coreservlets.client/GwtApp1.java • Button named randomNumberButton • HTML (label) named randomNumberResult • Button’s event handler should insert value into HTML 40
  • 20. Deleting Extraneous Files • Motivation – N apps contain sample files that are good examples to learn New i l fil h d l l from, but that should be deleted from new projects • Files to delete – Under src/package.client • GreetingService.java • GreetingServiceAsync.java g y j – Under src/package.server • GreetingServiceImpl.java – Under war • AppName.css (replace with own style sheet in subfolder) • Files to edit – war/WEB INF/web xml war/WEB-INF/web.xml • Remove servlet-mapping for GreetingServiceImpl • Forgetting this step will result in errors at server startup 41 Auto-Generated HTML File Created and edited by hand. See slides at end of section on overriding standard styles. Created automatically, but needs extensive editing. Top shown below. <!DOCTYPE ...> ! <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>First GWT App</title> <link rel="stylesheet" y This code edited by hand hand. href="./css/styles.css" Use normal HTML (usually xhtml). type="text/css"/> <script type="text/javascript" language="javascript" src= gwtapp1/gwtapp1.nocache.js ></script> src="gwtapp1/gwtapp1 nocache js"></script> </head> Inserted automatically by GWT. Leave it in unchanged. <body> Entire rest of file can be modified in any way. There is 42 an iframe in the body that is sometimes useful to have.
  • 21. Auto-Generated HTML File: Continued ... <fieldset> <legend>Client-Side Data</legend> <table border="1"> <tr><th>User Control</th> <th>Result</th></tr> <tr><td id="randomNumberButton"></td> <td id="randomNumberResult"></td></tr> ... </table><br/> </fieldset> These names will be referred to in Java code. ... In these simple examples we create one HTML section for each low-level GWT widget. But in </body> more advanced applications, it is common to </html> put GWT panels into HTML sections, and then put multiple GWT widgets in the panels. It is even possible to build a GUI completely with GWT, where the HTML just has one blank div section that will contain the main GWT panel. 43 Auto-Generated Java Class Created automatically, but need extensive editing. Shown below. y, g Created by hand. Will be used later in this tutorial. hand tutorial package coreservlets.client; k l li import com.google.gwt.core.client.*; import com.google.gwt.user.client.ui.*; Created automatically. Your code should be import com.google.gwt.event.dom.client.*; i t l t t d li t * called by onModuleLoad. ll d b M d l L d public class GwtApp1 implements EntryPoint { public void onModuleLoad() { … } 44 }
  • 22. Auto-Generated Java Class: Continued public class GwtApp1 implements EntryPoint { public void onModuleLoad() { // Main entry point buttonSetup(); Button is builtin GWT class. All standard HTML controls have corresponding listSetup(); GWT Swing-like classes. GWT also defines many extended components that are combinations of HTML elements. } private void buttonSetup() { Button randomNumberButton = new Button("Show Random Number"); HTML randomNumberResult = new HTML("<i>Num will go here</i>"); randomNumberButton.addClickHandler (new RanNumHandler(randomNumberResult)); g RootPanel.get("randomNumberButton").add(randomNumberButton); RootPanel.get("randomNumberResult").add(randomNumberResult); } ... Matches ids in the HTML } 45 Auto-Generated Java Class : Continued Using an inner class for event handling. Alternative approaches discussed in upcoming section on GWT events. private class RanNumHandler implements ClickHandler { private HTML resultRegion; public RanNumHandler(HTML resultRegion) { this.resultRegion = resultRegion; thi ltR i ltR i } public void onClick(ClickEvent event) { bli id Cli k(Cli kE t t) resultRegion.setText("Number: " + Math.random()*10); } } Whenever user clicks button, insert this string into the GWT HTML object (which is really a div). 46
  • 23. Testing in Hosted Mode – Click project name in Eclipse. Press Run button at top – Or, R-click project name and Run As  Web Application When first brought up. After pressing button. 47 Testing in Local Web Mode • Idea –RRunning in Web mode means running in a regular i i W b d i i l browser with all client-side Java code converted to JavaScript – Uses embedded version of Jetty server on local machine • Steps – Run the application in hosted mode – Click the “Compile/Browse” button at top of hosted- mode browser. – Result: • Creates JavaScript files in war/appname folder • Loads the main HTML file in your default browser – You can copy this URL to other browsers to test cross-browser compatibility 48
  • 24. Testing in Local Web Mode Press this in hosted mode browser. Page will pop up in default system browser, running with only HTML and JavaScript. 49 Testing in Deployed Mode • Idea – D l d mode is similar to Local Web mode Deployed d i i il L lW b d • Running in a regular browser with all client-side Java code converted to JavaScript • However uses normal Web App structure running on a However, Java server of your choice on any machine • Steps – Run the application in hosted mode – Click the “Compile/Browse” button • Do this immediately before deploying so you have JavaScript files corresponding to most recent Java code – Find the “war” folder on filesystem • Copy/rename and deploy as exploded WAR • Or, copy contents (not “war” folder itself) into file.zip, then rename file.zip to file.war and deploy as WAR file 50
  • 25. Testing in Deployed Mode • Copied workspace/project/war folder – Renamed to GwtApp1 to keep similar-looking URL • GwtApp1.html is welcome-file, so name can be omitted – Deployed to Apache Tomcat on localhost • Could have used any Java-capable server 51 © 2009 Marty Hall Using Auxiliary Java Classes Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 26. Big Idea • Use regular Java for client-side code – Normal Java 1.6 syntax • Classes, methods, constructors, loops, control statements, etc. – Supporting classes • Static methods in the Math class and many common data structures – St i String, array, Li t (A List (ArrayList, Li k dLi t) M (H hM and others), D t etc. Li t LinkedList), Map (HashMap d th ) Date, t – For full list, see http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html – Custom GWT classes • Class defined for each type of standard HTML control – Button, Checkbox, Image, Hyperlink, RadioButton, etc. • GWT also provides classes for groups of HTML controls – SuggestBox, SimplePanel, TabPanel, ScrollPanel, Tree, FlexTable, PopupPanel, etc. • Java gets translated into JavaScript g – Click Compile/Browser to generate JavaScript – But you develop and test using Java only • Restrictions – N t all collections or classes supported Not ll ll ti l t d – Custom classes must be placed in “...client” package. 53 Example: Linked Comboboxes (Choosing State Results in List of Associated Cities) • Eclipse Project: GwtApp1 –S Same project as i previous example j in i l • HTML: GwtApp1.html – Need regions with ids stateList and cityList • Java: – GwtApp1.java: main application class • D fi Defines two li b listboxes • Attaches event handler to listbox that stores state names – StateInfo.java (must be in ...client package) • Associates state name with array of cities • Defines static method with list of common states • Note – In AjaxTags section, we matched cities to states using server-side code. Using custom Java classes greatly 54 simplifies client-side code.
  • 27. Editing Auto-Generated Files • Edit AppName.html and give ids to sections – Gi ids to sections where buttons, textfields, and output will go Give id i h b fi ld d ill <tr><td>State: <span id="stateList"></span></td> <td>City: <span id="cityList"></span></td></tr> • Edit AppName.java • Code called by auto-generated onModuleLoad method 1. Create controls stateList = new ListBox(); cityList = new ListBox(); 2. Define event handlers stateList.addChangeHandler(new StateHandler()); 3. Insert in HTML page RootPanel.get( stateList ).add(stateList); RootPanel.get("stateList").add(stateList); RootPanel.get("cityList").add(cityList); 55 Auto-Generated HTML File • Same file as in earlier example – war/GwtAppl.html – Needs auto-generated script tag in the head section • Body <fieldset> <legend>Client-Side Data</legend> <table b d t bl border="1"> "1" <tr><th>User Control</th> <th>Result</th></tr> <tr><td id= randomNumberButton ></td> id="randomNumberButton"></td> <td id="randomNumberResult"></td></tr> <tr><td>State: <span id="stateList"></span></td> <td>City: <span id="cityList"></span></td></tr> id cityList ></span></td></tr> </table><br/> </fieldset> 56
  • 28. Auto-Generated Java Class • Same file as in earlier example – C ll d src/coreservlets.client.GwtApp1.java Called / l li G A 1 j – Has three sets of import statements – Has auto-generated features g • implements EntryPoint • onModuleLoad method package coreservlets.client; import com.google.gwt.core.client.*; import com.google.gwt.user.client.ui.*; import com.google.gwt.event.dom.client.*; public class GwtApp1 implements EntryPoint { public void onModuleLoad() { // Main entry point 57 Auto-Generated Java Class: Continued public class GwtApp1 implements EntryPoint { p public void onModuleLoad() { // Main entry p y point buttonSetup(); listSetup(); ListBox is builtin GWT class. All standard HTML controls have corresponding } GWT Swing-like classes. GWT also defines many extended components that are combinations of HTML elements. // buttonSetup shown earlier private void listSetup() { ListBox stateList = new ListBox(); populateStateList(stateList); stateList.setVisibleItemCount(1); Matches ids in the HTML ListBox cityList = new ListBox(); cityList.addItem("Select City"); cityList.setVisibleItemCount(1); it Li t tVi ibl It C t(1) cityList.setEnabled(false); stateList.addChangeHandler(new StateHandler(stateList, cityList)); RootPanel.get("stateList").add(stateList); RootPanel.get("cityList").add(cityList); } 58
  • 29. Auto-Generated Java Class: Continued p private void populateStateList(ListBox stateList) { p p ( ) stateList.addItem("Select State"); StateInfo[] nearbyStates = StateInfo.getNearbyStates(); for(StateInfo state: nearbyStates) { stateList.addItem(state.getStateName()); } } Unlike l U lik early GWT versions, you can use J i Java 5 and 6 f t d features ((e.g., new-style for/each l t l f / h loop) f client-side ) for li t id code. However, you are limited in what classes are supported for client-side code. For a complete list, see http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html. For server-side code (see later tutorial section), you can use any features of the Java version your server is using. 59 Auto-Generated Java Class: Continued private class StateHandler implements ChangeHandler { private ListBox stateList, cityList; public StateHandler(ListBox stateList, ListBox cityList) { this.stateList = stateList; this.cityList = cityList; } public void onChange(ChangeEvent event) { int index = stateList.getSelectedIndex(); String state = stateList.getItemText(index); i i (i d ) StateInfo[] nearbyStates = StateInfo.getNearbyStates(); String[] cities = StateInfo.findCities(nearbyStates, state); St t I f fi dCiti ( b St t t t ) cityList.clear(); for(String city: cities) { cityList.addItem(city); } cityList.setEnabled(true); } 60 }
  • 30. Helper Class (StateInfo) package coreservlets.client; Must be in same package as AppName.java. (...client). Only classes in this package are translated into JavaScript. public class StateInfo { private String stateName; private String[] cities; public StateInfo(String stateName, String[] cities) { this.stateName = stateName; this.cities this cities = cities; } p public String getStateName() { g g () return(stateName); } public String[] getCities() { bli St i [] tCiti () return(cities); } 61 Helper Class (StateInfo, (StateInfo Continued) private static String[] mdCities = { Baltimore , Frederick , Gaithersburg , Rockville }; {"Baltimore", "Frederick","Gaithersburg","Rockville"}; private static String[] vaCities = {"Virginia Beach","Norfolk","Chesapeake","Arlington"}; private static String[] paCities = {"Philadelphia","Pittsburgh","Allentown","Erie"}; private static String[] njCities = {"Newark", "Jersey City","Paterson","Elizabeth"}; private static String[] nyCities = {"New York", "Buffalo","Rochester","Yonkers"}; private static StateInfo[] nearbyStates = { new StateInfo("Maryland", mdCities), ( y , ), new StateInfo("Virginia", vaCities), new StateInfo("Pennsylvania", paCities), new StateInfo("New Jersey", njCities), new St t I f ("N StateInfo("New York", nyCities) Y k" Citi ) }; Can use arrays, ArrayList, HashMap, String, Date, custom classes, etc. GWT does not support every standard Java class on client, but a large set of them. For full list, see 62 http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html
  • 31. Helper Class (StateInfo, (StateInfo Continued) public static StateInfo[] getNearbyStates() { return(nearbyStates); } public static String[] findCities(StateInfo[] states, String stateName) { for(StateInfo state: states) { if(state.getStateName().equals(stateName)) { return(state.getCities()); return(state getCities()); } } String[] unknown = { g[] {"Unknown state"}; } return(unknown); } } 63 Testing in Hosted Mode – Click project name in Eclipse. Press Run button at top – Or, R-click project name and Run As  Web Application When first brought up. After selecting state state. (Cities selected to illustrate contents) 64
  • 32. Testing in Local Web Mode Press this in hosted mode browser. Page will pop up in default system browser, running with only HTML and JavaScript on client side. 65 Testing in Deployed Mode • workspace/project/war – Renamed to GwtApp1 to keep similar-looking URL – Deployed to Apache Tomcat on localhost • Could have used any Java-capable server Java capable 66
  • 33. © 2009 Marty Hall Overriding Standard CSS Styles y Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Auto-Loaded Style Sheet in Auto-Generated HTML File • Idea – Th JavaScript file automatically inserts The J S i fil i ll i <link rel="stylesheet" href="…/standard.css"> at end of head section. • Good news – There are styles such as gwt-Button and gwt-HTML that let you customize the look of all GWT widgets – There are three predefined themes (standard, dark, chrome) that you can switch among • Bad news – The automatic stylesheet is loaded after yours. So, it overrides your entries, not vice versa. – It gives styles for body, td, select, pre, and a. – Cannot edit it: gets rebuilt when you do Compile/Browse 68
  • 34. Simple Usage: Overriding Standard Styles • Mark your styles with !important – End your entries with !important so that they won’t be overridden by standard.css. – Only needed for body, td select pre, and a. body td, select, pre a • body { background-color: red !important; … } td { font-size: 103px !important; … } • O use explict CSS class names Or, li t l – Don’t give styles to those five HTML element names, but instead use CSS class names • CSS: .mybodystyle { background-color: red; … } .bigcell { font size: 103px; … font-size: • HTML: <body class="mybodystyle"> 69 <td class="bigcell"> Advanced Usage: Loading Stylesheets Manually • Edit src/packageName/AppName.gwt.xml – Change <inherits name='… .Standard'/> to <inherits name='… .StandardResources'/> • This causes stylesheet to be output under war folder but folder, not loaded • Load the GWT stylesheet first – <link rel="stylesheet" href="./appname/gwt/standard/standard.css"> • Load your stylesheet second – <link rel="stylesheet" href="./css/mystyles.css"> 70
  • 35. styles.css from GwtApp1 body { background-color: #fdf5e6 !important } td { font-size: 18px !important; font size: font-family: Arial, Helvetica, sans-serif !important; } Entries for body and td marked as !important because body and td defined in standard.css. … This approach is recommended for GWT beginners. th { background-color: #ef8429; font-size: 18px; font family: font-family: Arial, Helvetica, sans serif; sans-serif; } legend { font-weight: bold; g ; Entries for other elements not marked with !important color: black; because they are not defined in standard.css background-color: #eeeeee; border: 1px solid #999999; p padding: 3px 2px; } 71 Advanced Usage: Loading Stylesheets Manually • src/packageName/GwtApp1.gwt.xml – Change • <inherits name com.google.gwt.user.theme.standard.Standard / name='com.google.gwt.user.theme.standard.Standard'/> – to • <inherits name= com.google.gwt.user.theme.standard.StandardResources /> name='com google gwt user theme standard StandardResources'/> • Auto-generated HTML file – Load standard.css and custom stylesheet. If you load your custom stylesheet second, its entries override earlier ones. • <link rel="stylesheet" href= /gwtapp1/gwt/standard/standard css"> href="./gwtapp1/gwt/standard/standard.css > <link rel="stylesheet" href="./css/mystyles.css"> 72
  • 36. © 2009 Marty Hall Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Summary • Create an Eclipse application – Press “g” button at top, or File  New  Web Application Project g top • Edit auto-generated HTML (AppName.html) – Give ids to regions where controls will be placed • But see later section on panels You might have few (one?) region panels. region. • Edit auto-generated Java (AppName.java) – Edit onModuleLoad • Create controls controls. Button b = new Button( ); Button(...); • Give them event handlers. b.addClickHandler(…); • Insert controls into HTML page. RootPanel.get("id").add(b); • Test in hosted mode (always) – Click Run button at top or R-click  Run As  Web App • Test in local Web mode (occasionally) – Press C Compile/Browse in hosted mode b il / i h d d browser • Deploy to normal Java server (at end) 74 – Copy/rename “war” folder or put contents into .war file
  • 37. © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.