© 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.

More Related Content

PDF
Enhancing Spring MVC Web Applications Progressively with Spring JavaScript
PDF
Javantura 2014 - Java 8 JavaScript Nashorn
PPTX
Gradle.Enemy at the gates
PDF
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
PDF
Polyglot Plugin Programming
PDF
Groovy Tutorial
PPTX
Preparing for java 9 modules upload
PDF
History of Java 2/2
Enhancing Spring MVC Web Applications Progressively with Spring JavaScript
Javantura 2014 - Java 8 JavaScript Nashorn
Gradle.Enemy at the gates
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Polyglot Plugin Programming
Groovy Tutorial
Preparing for java 9 modules upload
History of Java 2/2

What's hot (19)

PDF
Alpes Jug (29th March, 2010) - Apache Maven
PDF
Performance tuning the Spring Pet Clinic sample application
PDF
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
PDF
Lausanne Jug (08th April, 2010) - Maven
PDF
Riviera JUG (20th April, 2010) - Maven
PDF
Introduction in Apache Maven2
PPT
QEWD.js: Have your Node.js Cake and Eat It Too
PDF
Apache Maven - eXo TN presentation
PPTX
Java 9 Module System Introduction
PPTX
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
PDF
Geneva Jug (30th March, 2010) - Maven
PPTX
Scala in the Wild
PDF
The Modern Java Web Developer - JavaOne 2013
PDF
PDF
Groovy Testing Sep2009
PPTX
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
PDF
Dojo (QCon 2007 Slides)
KEY
4 maven junit
PDF
Lorraine JUG (1st June, 2010) - Maven
Alpes Jug (29th March, 2010) - Apache Maven
Performance tuning the Spring Pet Clinic sample application
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
Lausanne Jug (08th April, 2010) - Maven
Riviera JUG (20th April, 2010) - Maven
Introduction in Apache Maven2
QEWD.js: Have your Node.js Cake and Eat It Too
Apache Maven - eXo TN presentation
Java 9 Module System Introduction
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Geneva Jug (30th March, 2010) - Maven
Scala in the Wild
The Modern Java Web Developer - JavaOne 2013
Groovy Testing Sep2009
Modules in Java? Finally! (OpenJDK 9 Jigsaw, JSR376)
Dojo (QCon 2007 Slides)
4 maven junit
Lorraine JUG (1st June, 2010) - Maven
Ad

Viewers also liked (7)

PDF
Social media pedro_fernandes
PDF
Business seminar "Branding versus Performance" April 2012
PDF
Presentación Hernan Litvac - eCommerce Day Bolivia 2016
PPTX
Nivel topografico
DOC
Trabajo Comunicacion Practica 4
PPT
Agua par Taba (Senegal)
Social media pedro_fernandes
Business seminar "Branding versus Performance" April 2012
Presentación Hernan Litvac - eCommerce Day Bolivia 2016
Nivel topografico
Trabajo Comunicacion Practica 4
Agua par Taba (Senegal)
Ad

Similar to GWT-Basics (20)

PPTX
Gwt overview & getting started
PPTX
GWT HJUG Presentation
PPT
GWT Training - Session 1/3
PPT
PPT
Google Web Toolkit Introduction - eXo Platform SEA
PDF
Introduction to Google Web Toolkit - part 1
PPTX
Gwt session
PPTX
Gwt session
PDF
Google Web Toolkit
PPT
GWT Introduction for Eclipse Day
PDF
Automatically generating-json-from-java-objects-java-objects268
PDF
An introduction to GWT and Ext GWT
PDF
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
PDF
GWT - Building Rich Internet Applications Using OO Tools
PDF
Gwt Presentation
PPT
GWT_Framework
PPTX
GWT = easy AJAX
PPTX
Google web toolkit ( Gwt )
PDF
GWT training session 1
PDF
Introduction to Google Web Toolkit
Gwt overview & getting started
GWT HJUG Presentation
GWT Training - Session 1/3
Google Web Toolkit Introduction - eXo Platform SEA
Introduction to Google Web Toolkit - part 1
Gwt session
Gwt session
Google Web Toolkit
GWT Introduction for Eclipse Day
Automatically generating-json-from-java-objects-java-objects268
An introduction to GWT and Ext GWT
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
GWT - Building Rich Internet Applications Using OO Tools
Gwt Presentation
GWT_Framework
GWT = easy AJAX
Google web toolkit ( Gwt )
GWT training session 1
Introduction to Google Web Toolkit

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
PDF
&lt;img src="../i/r_14.png" />
PDF
&lt;img src="../i/r_14.png" />
PDF
Standardization and Knowledge Transfer – INS0
PDF
xhtml_basics
PDF
xhtml_basics
PDF
xhtml-documentation
PDF
xhtml-documentation
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
HowTo_CSS
PDF
HowTo_CSS
PDF
BloggingWithStyle_2008
PDF
BloggingWithStyle_2008
PDF
cascadingstylesheets
PDF
cascadingstylesheets
&lt;img src="../i/r_14.png" />
TopStyle Help &amp; &lt;b>Tutorial&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" />
Standardization and Knowledge Transfer – INS0
xhtml_basics
xhtml_basics
xhtml-documentation
xhtml-documentation
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
HowTo_CSS
HowTo_CSS
BloggingWithStyle_2008
BloggingWithStyle_2008
cascadingstylesheets
cascadingstylesheets

Recently uploaded (20)

PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
August Patch Tuesday
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PPTX
Chapter 5: Probability Theory and Statistics
PDF
STKI Israel Market Study 2025 version august
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Five Habits of High-Impact Board Members
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
DOCX
search engine optimization ppt fir known well about this
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
PPTX
Tartificialntelligence_presentation.pptx
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
Developing a website for English-speaking practice to English as a foreign la...
A comparative study of natural language inference in Swahili using monolingua...
August Patch Tuesday
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
Chapter 5: Probability Theory and Statistics
STKI Israel Market Study 2025 version august
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Five Habits of High-Impact Board Members
O2C Customer Invoices to Receipt V15A.pptx
Group 1 Presentation -Planning and Decision Making .pptx
search engine optimization ppt fir known well about this
Hindi spoken digit analysis for native and non-native speakers
A review of recent deep learning applications in wood surface defect identifi...
1 - Historical Antecedents, Social Consideration.pdf
Zenith AI: Advanced Artificial Intelligence
Tartificialntelligence_presentation.pptx
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
observCloud-Native Containerability and monitoring.pptx
Developing a website for English-speaking practice to English as a foreign la...

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 [email protected] 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.