This document provides an overview of Google Web Toolkit (GWT), including its architecture, key features, and how to implement common tasks. GWT is a development toolkit that allows web applications to be written in Java and compiled into JavaScript for better cross-browser compatibility. It discusses topics like building user interfaces with widgets, event handling, styling with CSS, making remote procedure calls, and accessing native JavaScript methods. Examples and demos are provided to illustrate concepts like creating custom widgets, handling events, and making asynchronous server calls. Resources for learning more about GWT are also listed.
2. Acknowledgment The presentation is adapted from Sang Shin's presentation at http://www.javapassion.com With permission from Sang Shin Java Technology Architect & Evangelist Sun Microsystems, Inc.
3. Agenda Introduction to AJAX What is & Why GWT? Building User interface GWT Widgets Event Handling Styling
4. Agenda Remote Procedural Call (RPC) Steps for building GWT RPC application Serializable types Handling exceptions JavaScript Native Interface (JSNI)
9. What is GWT? Java dev framework for easy AJAX dev Java-to-JavaScript compiler Special web browser that helps debug When pplication deploy to production, compiler translates Java application to browser-compliant JavaScript, CSS, and HTML
10. Two Modes of Running GWT App Hosted mode Application run as Java bytecode within JVM Most development in hosted mode Web mode GWT Java-to-JavaScript compiler JavaScript and HTML deployed to web server Application run as pure JavaScript and HTML End users only see the web mode version application
11. Demo: Create a new GWT Application In the beginning,....
12. Why Use Java Programming Language for AJAX Development? Static type checking in the Java boosts productivity while reducing errors. Common JavaScript errors (typos, type mismatches) are easily caught at compile time Code prompting/completion (through IDE) Automated Java refactoring Java-based OO designs are easier to communicate and understand, thus making AJAX code base more comprehensible.
13. Why GWT? No need to learn/use JavaScript language No need to handle browser incompatibilities No need to learn/use DOM APIs Use Java APIs No need to build commonly used Widgets Most of them come with GWT Various tools of Java programming language for writing/debugging/testing JUnit integration Internationalization
16. GWT Architectural Components GWT Java-to-JavaScript Compiler GWT Hosted Web Browser JRE emulation library GWT contains JavaScript implementations of the most widely used classes in the Java standard class library GWT Web UI class library Similar to Swing UI
17. The GWT Java To Javascript Compiler Parses the original Java code Full parser, almost all Java constructs will be parsed correctly. Generates a full Abstract Syntax Tree (AST) GWT's compiler isn't a parlor trick, it's a real code parser and cross-language compiler Performs optimization, dead-code elimination, dynamic analysis, and other code fixups The generated JS is fast and efficient, sometimes faster than what you might write yourself
18. GWT Javascript Code Generation Optimization All code is optimized, including some unusual tricks (like turning some methods into wrapped statics) Dead-Code Elimination Remove any code that cannot be reached, or always returns the same value(s) Javascript Generation Generate Javascript, including all necessary browser-specific checks and workarounds Javascript obfuscation and size reduction Javascript is (optionally) obfuscated to protect your trade-secrets, and to reduce it's size
19. Demo: GWTApplication Build and run GWTApplication Show HTML files and JavaScript code that are generated by translator Look at source code Debug
21. GWT User Interface Classes Swing like UI frameworks But widgets are rendered using dynamically-created HTML rather than pixel-oriented graphics Far easier to manipulate DOM using Java classes from the Widget hierarchy than using DOM API Much easier to quickly build interfaces that works correctly on all browsers using widgets
28. Custom Composite Widget Composite widget =widget contain other component (typically, a panel) The most effective way to create new widgets
29. Example: Composite Widget public static class OptionalTextBox extends Composite implements ClickListener { private TextBox textBox = new TextBox(); private CheckBox checkBox = new CheckBox(); /** * Constructs an OptionalTextBox with the given caption on the check. * * @param caption the caption to be displayed with the check box */ public OptionalTextBox(String caption) { // Place the check above the text box using a vertical panel. VerticalPanel panel = new VerticalPanel(); panel.add(checkBox); panel.add(textBox); // Set the check box's caption, and check it by default. checkBox.setText(caption); checkBox.setChecked(true); checkBox.addClickListener(this); // continued in the next slide
30. Example: Composite Widget // All composites must call initWidget() in their constructors. initWidget(panel); // Give the overall composite a style name. setStyleName("example-OptionalCheckBox"); } public void onClick(Widget sender) { if (sender == checkBox) { // When the check box is clicked, update the text box's enabled state. textBox.setEnabled(checkBox.isChecked()); } }
32. Events and Listeners Events in GWT use the "listener interface" model Define listener interface Event Listener implements listener interface Event Listener subscribes to a event by passing a reference to itself to the widget
33. Example: Event Listener public class ListenerExample extends Composite implements ClickListener { private FlowPanel fp = new FlowPanel(); private Button b1 = new Button("Button 1"); private Button b2 = new Button("Button 2"); public ListenerExample() { setWidget(fp); fp.add(b1); fp.add(b2); b1.addClickListener(this); b2.addClickListener(this); } // Event listener method from the ClickListener interface public void onClick(Widget sender) { if (sender == b1) { // handle b1 being clicked } else if (sender == b2) { // handle b2 being clicked } } }
35. Steps To Follow Create CSS file (which contains styles) KitchenSink.css Specify the CSS file in the module configuration file Use the styles in the Java code
37. Step 2: Specify the CSS file in the Module Configuration File: KitchenSink.gwt.xml <module> <inherits name='com.google.gwt.user.User'/> <entry-point class='com.google.gwt.sample.kitchensink.client.KitchenSink'/> <stylesheet src='KitchenSink.css'/> </module>
38. Step 3: Add/Remove Styles to Widgets in the Java Code: SinkList.java public void setSinkSelection(String name) { if (selectedSink != -1) list.getWidget(selectedSink). removeStyleName("ks-SinkItem-selected"); for (int i = 0; i < sinks.size(); ++i) { SinkInfo info = (SinkInfo) sinks.get(i); if (info.getName().equals(name)) { selectedSink = i; list.getWidget(selectedSink). addStyleName("ks-SinkItem-selected"); return; } } }
39. Adding/Removing Styles Style can be added to or removed from widgets via <Widget>.addStyleName(“<name-of-style>”); <Widget>.removeStyleName(“<name-of-style>”); Multiple styles can be added to a widget
41. What is and Why GWT RPC? A mechanism for interacting with the server by invoking a method asynchronously Makes it easy for the client and server to pass Java objects back and forth over HTTP Marshaling and unmarshaling of Java objects are handled by the GWT You could move all UI logic to the client improved performance, reduced bandwidth, reduced web server load, and a pleasant user experience
44. Steps for Implementing GWT RPC Write two service interface's (client & server) Synchronous interface Asynchronous interface – must pass async. callback object Implement the service at the server side Service class implements Service interface and extends RemoteServiceServlet class Configure the servlet in the web.xml Make a call from the client
45. 1. Write Two Service Interface Files Synchronous interface public interface MyHelloService extends RemoteService { public String sayHello(String s); } Asynchronous interface // Has to be named as <Synchronous-interface>Async. // Has to pass AsyncCallback object as the last parameter. // The return type is always void . interface MyHelloServiceAsync { public void sayHello(String s, AsyncCallback callback ); }
46. 2. Implement the Service Extends RemoteServiceServlet and implements the service interface public class MyHelloServiceImpl extends RemoteServiceServlet implements MyHelloService { // Provide implementation logic. public String sayHello(String s) { return "Hello, " + s + "!"; } }
47. 3. Configure the servlet in web.xml <web-app> <servlet> <servlet-name>GWTService</servlet-name> <servlet-class> my.company.server.GWTServiceImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>GWTService</servlet-name> <url-pattern>/my.company.Main/gwtservice</url-pattern> </servlet-mapping> </web-app>
48. 4. Make a call from Client Instantiate an client proxy (an object of the type of asynch. service interface) using GWT.create() Specify a service entry point URL for the service proxy using ServiceDefTarget Create an asynchronous callback object to be notified when the RPC has completed Make the call from the client
49. a. Instantiate Service Interface using GWT.create() public void menuCommandsayHello(String msg) { // (a) Create the client proxy. // Note that although you are creating the object instance of the service interface type, you cast the result to the asynchronous version of the interface. // The cast is always safe because the generated proxy implements the asynchronous interface automatically. MyHelloServiceAsync myhelloService = (MyHelloServiceAsync) GWT.create(MyHelloService.class);
50. b. Specify a service entry point URL for the service proxy using ServiceDefTarget public void menuCommandEmptyInbox() { MyHelloServiceAsync myhelloService = (MyHelloServiceAsync) GWT.create(MyHelloService.class); // (b) Specify the URL at which our service implementation is running. // Note that the target URL must reside on the same domain and port from which the host page was served. ServiceDefTarget endpoint = (ServiceDefTarget) myhelloService; String moduleRelativeURL = GWT.getModuleBaseURL() + "myhelloservice"; endpoint.setServiceEntryPoint(moduleRelativeURL);
51. c. Create an asynchronous callback object to be notified when the RPC has completed public void menuCommandEmptyInbox() { ... // (c) Create an asynchronous callback to handle the result. // AsyncCallback callback = new AsyncCallback() { public void onSuccess (Object result) { // do some UI stuff to show success } public void onFailure (Throwable caught) { // do some UI stuff to show failure } };
52. d. Make the Call public void menuCommandsayhello(String msg) { ... // (d) Make the call. Control flow will continue immediately and later // 'callback' will be invoked when the RPC completes. // myhelloService.sayHello(msg, callback ); }
56. Handling Exceptions Making RPCs opens up various possible errors Networks fail, servers crash, and problems occur while processing a server call GWT lets you handle these conditions in terms of Java exceptions RPC-related exceptions Checked exceptions Unexpected exceptions
57. Checked Exceptions Service interface methods support throws declarations to indicate which exceptions may be thrown back to the client from a service implementation Callers should implement AsyncCallback.onFailure(Throwable) to check for any exceptions specified in the service interface
58. Unchecked Exceptions An RPC may not reach the service implementation at all. This can happen for many reasons: the network may be disconnected a DNS server might not be available the HTTP server might not be listening In this case, an InvocationException is passed to your implementation of AsyncCallback.onFailure(Throwable)
61. Why JSNI? Mix JavaScript and Java code useful some times For example, the lowest-level functionality of certain core GWT Leverage various existing JavaScript toolkits Dojo toolkits, Prototype, Rico, etc. Should be used sparingly JSNI code is less portable across browsers, more likely to leak memory, less amenable to Java tools, and hard for compiler to optimize
62. What Can You Do with JSNI? Implement a Java method directly in JavaScript Wrap type-safe Java method signatures around existing JavaScript Call from JavaScript into Java code and vice-versa Throw exceptions across Java/JavaScript boundaries Read and write Java fields from JavaScript
65. How to add JavaScript Code via JSNI? When accessing the browser's window and document objects from JSNI, you must reference them as $wnd and $doc , respectively Your compiled script runs in a nested frame, and $wnd and $doc are automatically initialized to correctly refer to the host page's window and document
66. Writing Native JavaScript Methods JSNI methods are declared native and contain JavaScript code in a specially formatted comment block between the end of the parameter list and the trailing semicolon /*-{ <JavaScript code }-*/ JSNI methods are to be called just like any normal Java method They can be static or instance methods
68. Invoking Java methods from JavaScript Calling Java methods from JavaScript is somewhat similar to calling Java methods from C code in JNI. In particular, JSNI borrows the JNI mangled method signature approach to distinguish among overloaded methods. [instance-expr.]@class-name::method-name(param-signature)(arguments)
69. Accessing Java Fields from JavaScript Static and instance fields can be accessed from handwritten JavaScript [instance-expr.]@class-name::field-name
70. Resources http://www.javapassion.com Main Presentation source http://code.google.com/webtoolkit/ Main site for all things GWT http://googlewebtoolkit.blogspot.com/ GWT team blog http://code.google.com/p/google-web-toolkit/ GWT source code and issue tracker site Slides from Presentation at TSSJS (PDF) http://tinyurl.com/3y8kmx Video from Google Developer Day http://tinyurl.com/2rkq29