vi 1.5 Understanding the GWT compiler 19 JavaScript output style 20 ■ Additional compiler nuances 23 The compiler lifecycle 24 1.6 Summary 30 2 A New Kind of Client 32 2.1 Basic project
Trang 2GWT in Practice
Trang 4GWT in Practice
ROBERT COOPER CHARLES COLLINS
M A N N I N G
Greenwich (74° w long.)
Trang 5For online information and ordering of this and other Manning books, please visit
www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact:
Special Sales Department
Manning Publications Co
Sound View Court 3B Fax: (609) 877-8256
Greenwich, CT 06830 email: orders@manning.com
©2008 by Manning Publications Co All rights reserved
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps
Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15% recycled and processed elemental chlorine-free
Manning Publications Co Copyeditor: Andy Carroll
Sound View Court 3B Typesetters: Denis Dalinnik
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1-933988-29-0
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 12 11 10 09 08
Trang 6contents
preface xi acknowledgments xii about this book xiii about the cover illustration xvii
P ART 1 G ETTING S TARTED 1
1.4 Working with the GWT shell 16
The logging console 17 ■ The hosted mode browser 18
Trang 7vi
1.5 Understanding the GWT compiler 19
JavaScript output style 20 ■ Additional compiler nuances 23 The compiler lifecycle 24
1.6 Summary 30
2 A New Kind of Client 32
2.1 Basic project structure and components 33
Generating a project 34 ■ The standard directory structure 35 GWT starting point files 36 ■ Host pages 37 ■ Modules 38 Entry points 40
2.2 Design patterns and GWT 40
MVC and GWT 41 ■ Creating a widget 42 ■ Communicating
by observing events 46 ■ Operator strategy 48 ■ Controlling the action 51
2.3 Styling a GWT component 54
Providing a CSS file 54 ■ Connecting style names with Java 56
2.4 Running a completed project 56
Hosted mode and the GWT shell 57 ■ Web mode and the GWT compiler 58
2.5 Summary 59
3 Communicating with the Server 61
3.1 Making GWT Remote Procedure Calls 62
Starting the HelloServer project 62 ■ Defining GWT serializable data 64 ■ Creating RPC services 66 Expanding on RemoteServiceServlet 69 ■ Calling the server from the client 70 ■ Troubleshooting server communication 74
3.2 The development server—Tomcat Lite 75
The web.xml file 75 ■ The context.xml file 77
3.3 Using an external development server 79 3.4 Summary 80
P ART 2 T ASK - SPECIFIC I SSUES 83
4 Core Application Structure 85
4.1 Building a model 86
Trang 8CONTENTS vii
4.2 Building view components 90
Extending widgets 90 ■ Extending composite 93 Binding to the model with events 95
4.3 The controller and service 98
Creating a simple controller 99 ■ JPA-enabling the model 100 Creating a JPA-enabled service 104
4.4 Summary 106
5 Other Techniques for Talking to Servers 107
5.1 Web development methods and security 108
Dealing with browser security 108 ■ Understanding XMLHttpRequest 110 ■ Coding asynchronously 110 Developing GWT applications in NetBeans 111
5.2 Enabling REST and POX communications 112
Making basic HTTP requests with GWT 112 ■ Making advanced HTTP requests with GWT 114 ■ Working with XML 115
5.3 Understanding Java-to-JavaScript interaction 116
Using GWT JavaDoc annotations to serialize collections 116 Using JSON 119
5.4 Creating a cross-domain SOAP client with Flash 121
Using Flash as a SOAP client 121 ■ Setting a Flash security context 130 ■ Drawbacks and caveats 131
5.5 Incorporating applets with GWT 131
Using Java as a SOAP client 131 ■ Signing JARs for security bypass 136
5.6 Streaming to the browser with Comet 137
5.7 Summary 147
6 Integrating Legacy and Third-Party Ajax Libraries 148
6.1 A closer look at JSNI 149
JSNI basics revisited 149 ■ Potential JSNI pitfalls 151 Configuring IntelliJ IDEA 153
6.2 Wrapping JavaScript libraries 155
Creating a JavaScript module 156 ■ Creating wrapper classes 156 ■ Using the wrapped packages 159
Trang 9viii
6.3 Managing GWT-JavaScript interaction 162
Maintaining lookups 162 ■ Daisy-chaining Java listeners into JavaScript closures 166 ■ Maintaining listeners
in Java 168 ■ Conversion between Java and JavaScript 172
6.4 Wrapping JavaScript with GWT-API-Interop 178 6.5 Summary 181
7 Building, Packaging, and Deploying 183
7.1 Packaging GWT modules 184
Building and packaging modules 184 ■ Sharing modules 186
7.2 Building and deploying applications 187
The client side 188 ■ The server side 188 ■ Manually building
a WAR file 189
7.3 Automating the build 191
Extending the Ant build 191 ■ Using Maven 195
7.4 Managing Tomcat Lite from the build 205 7.5 Summary 210
8 Testing and Continuous Integration 211
8.1 GWT testing 212
Knowing what to test 212 ■ How GWT testing works 213 Testing gotchas 214 ■ Basic GWT tests 217 ■ Testing outside of GWT 224
8.2 Advanced testing concepts 226
Benchmarking 227 ■ Remote testing 229 Code coverage 231 ■ Coverage in an automated build 234
8.3 Continuous integration 239
Adding a GWT project to Hudson 240
8.4 Summary 245
P ART 3 F ULLY F ORMED A PPLICATIONS 247
9 Java Enterprise Reinvented 249
9.1 Constructing two models 251 9.2 Mapping to DTOs 257 9.3 Wiring applications with Spring 260
Trang 10CONTENTS ix
9.4 Constructing the client application 265
The controller and global model 266 ■ The basic CRUD wrapper 269 ■ The BookEdit widget 272
9.5 Summary 279
10 Building the Storefront 281
10.1 Securing GWT applications 282
10.2 Building a drag-and-drop system 289
Enabling dragging 290 ■ Handling drops 293
10.3 JSNI special effects 296
10.4 Summary 299
11 Managing Application State 300
11.1 Overview of the sample application 301
11.2 Creating a basic messaging service 304
11.3 Handling messages on the client and server 310
Messages and CometEvents 310 ■ Streaming messages
to the client 312 ■ Receiving images 315
11.4 Recording and playing back conversations 317
Capturing changes to the model layer 320 ■ Handling deep links 325 ■ When to use hyperlinks rather than history 326
11.5 Dealing with state on the server side 327
11.6 Adding a UI and cleaning up 330
Displaying events 330 ■ Sending events 331 Cleaning up 333
11.7 Summary 334
appendix A Notable GWT Projects 335
appendix B Quick Reference 338
index 351
Trang 12preface
At the Sun JavaOne conference in 2006, where GWT was first showcased, the lights immediately went on I was in attendance, and I instantly understood, as did many others, what GWT creators Bruce Johnson and Joel Webber were showing the world
GWT was something different It was not just another web framework at a Java ence but a new approach An approach that embraced the treatment of JavaScript in the browser as the “assembly language” of the web, as Arno Puder of the XML11 proj-ect once put it, and that did so by starting from Java, in order to iron out some of the terrain of the browser landscape
I was excited about leveraging this new technology in the real world, and I brought
it back to the company I worked for, where my longtime friend Charlie Collins also worked There, in Atlanta, Georgia, where the GWT team is also based, we started cranking away on several GWT applications, some tools to help support our develop-ment (such as GWT-Maven), and a framework approach to using GWT Along the way,
we got involved in the GWT community on the project-issue tracker and discussion boards, we pondered GWT at JUG meetings, and we discussed some of the finer points with the GWT team on a few special occasions
Early on, I posted a series of articles about GWT online that became rather lar That response, coupled with our practical knowledge of GWT and of web appli-cation design in general (having been involved in that field since the Servlet API
popu-itself arrived), led us to think that the time was right for a hands-on GWT “how to” book We took the concept to several book publishers and decided that Manning was right for the project based on our general fondness for their books and the fact
Trang 13ROBERT COOPER
acknowledgments
It may seem obvious that writing a book is no small endeavor, but it would probably also surprise a lot of people to know just how much work goes into the process Although there are only two names listed on the cover of this book, a host of dedi-cated, talented professionals, working behind the scenes, made this book possible
We would like to thank the entire staff at Manning for making GWT in Practice a
reality: publisher Marjan Bace, acquisitions editor Mike Stephens, development editor Cynthia Kane, copy editor Andy Carroll, as well as Mary Piergies, Karen Tegtmayer, Dottie Marisco, Elizabeth Martin, Denis Dalinnik, Ron Tomich, and Megan Yockey Many reviewers also provided essential feedback The book was honed over a series
of reviews thanks to their invaluable suggestions We would like to thank the following individuals for their time and effort in the review process: Martyn Fletcher, Todd Hoff, Devon Hillard, Jason Kolter, Adam Tacy, Robert Hanson, Andrew C Oliver, Sandy McArthur, Carl Hume, Edmon Begoli, Eric Raymond, Andrew Grothe, Mark Bauer, Carlo Bottiglieri, Julian Seidenberg, Deepak Vohra, Bill Fly, Peter Pavlovich, Marcin Leszczyn´ski and Massimo Perga Special thanks to Valentin Crettaz, who did one last technical review of the final manuscript shortly before it went to press
Trang 14ABOUT THIS BOOK xiii
Charlie Collins
To begin with, I would like to thank my coauthor, Robert Cooper “Cooper,” as he is affectionately known to friends, not only proposed this project and brought a large part of it to fruition, but he also brought me into the fold and provided the bulk of my early exposure to GWT
I would also like to thank the open source software community in general for viding me with many of the tools and software applications I used to write this book, from OpenOffice, ArgoUML, Subversion, and GIMP to Apache Tomcat, Eclipse, now Java, and, of course, GWT itself Many thanks go to the GWT team, all of the GWT con-tributors, the GWT community, and to Google Not only did I enjoy writing the book, but I also appreciate working with the toolkit on a day-to-day basis and building soft-ware with it
Lastly, I want to thank my family: my wife Erin and my daughters Skylar and Delaney, who not only put up with me in general, but also showed incredible understanding when I had to spend yet another evening or weekend at the keyboard instead of with them; and my parents, who have been supportive and helpful in everything, always
about this book
Welcome to GWT in Practice This book is intended to serve as a practical field guide for
developers working with the Google Web Toolkit While it includes some introductory information, it is not a complete introduction to all the classes and libraries included with GWT It is, however, a guide to working around common issues developers encoun-ter when building GWT applications, and to working with other Java EE technologies When getting started with GWT, there are a lot of things that will seem alien to tra-ditional web developers in the Java world This begins with GWT’s tooling—a special-ized version of Tomcat for debugging and testing your Ajax applications—and continues into the design approach—an expression of the Model View Controller (MVC) pattern more akin to desktop application development than the web frame-works you may be familiar with Hopefully this book will smooth the glide path for you
as you move into development with GWT
GWT in Practice also looks at working with technologies you may be familiar with,
but that have different usage patterns in the GWT world These include using the Java Persistence API with Hibernate or TopLink, working with build tools, testing, and con-tinuous integration These are at the core of modern enterprise application develop-ment but can be problematic for new GWT developers We’ll give you what you need
to integrate GWT applications into your enterprise development environment
Trang 15ABOUT THIS BOOK
xiv
Who should read this book
Ajax development brings advantages to both users and application providers; GWT
brings the advantages of Ajax and the benefits of Java to developers This book will be
of most help to Java developers coming to GWT’s style of Ajax development
While you don’t need to understand everything in this book to get value from it, you should have some basic experience with web development in a Java EE environ-ment and some experience working with Java application servers Obviously, a work-ing knowledge of HTML and CSS is important, as is a basic understanding of the browser DOM Some experience with JavaScript or Ajax is also beneficial
We have made an effort to cover as many tools in our examples as possible Whether you use Eclipse, NetBeans, or IntelliJ IDEA to edit code, and Ant or Maven to build your projects, you will find at least one chapter that deals with your tools Of course, this means many of the chapters will include discussions of tools that are not your own We expect you to be familiar enough with your tooling to work around the parts you don’t care about specifically
You should find this book to be helpful and a good ongoing reference while you are developing your applications If your needs are task-specific, chances are good that at least one or two chapters cover what you are looking for However, if you have limited experience with web technologies in general, we recommend you start with
GWT in Action, available from Manning as well.
Roadmap
This book is divided into three parts Part 1 is a quick introduction to the “GWT
way,” which includes tools and concepts the rest of the book relies upon Part 2 includes a series of practical examples laid out in a problem, solution, and discus-sion format Part 3 dives into a larger hands-on sample application that puts all of the GWT pieces together
In chapter 1 we take a brief historical tour and explore the roots of Ajax itself, and then address why it’s important and how GWT can help We also cover the basic tools and terminology involved in GWT
Chapter 2 starts with an exclusively client-side example that reinforces some of the basic GWT tenets and stresses a few new points, such as the fact that in GWT a lot more than the view exists on the client This is where GWT differs from many other web tool-kits—it allows a true Model View Controller (MVC) architectural approach to be used
in a browser-based application
From there the logical step is to create a full-featured client with server resources
In chapter 3 we use GWT Remote Procedure Calls (RPCs), demonstrate what able types are, and show how talking to servers works with GWT RPC We also cover some of the details of the GWT hosted mode development shell, which uses an embed-ded version of Apache Tomcat
Those first three chapters form the foundation of the book We then move into part 2 In chapter 4, we go a bit deeper into what a canonical GWT application
Trang 16ABOUT THIS BOOK xv
involves, including data binding and using the Java Persistence API (JPA) with GWT to persist data in a database
Chapter 5 concentrates on talking to servers using mechanisms other than GWTRPC Here we discuss JavaScript-to-Java details, the usage of JavaScript Object Notation (JSON), browser security, and the same-origin policy This is also where we utilize Repre-sentational State Transfer (REST) and XML over HTTP We conclude by running a Simple Object Access Protocol (SOAP) example from a GWT client (using Flash), and incorpo-rating applets This chapter runs the gamut in terms of ways to expose GWT clients to data, and it demonstrates the flexibility you have when working with GWT in general Chapter 6 then goes on to take a close look at the GWT JavaScript Native Interface (JSNI) mechanism, and the GWT-API-Interop library Both of these are used to inte-grate existing JavaScript libraries with GWT
In chapter 7 we focus on building, packaging, and deploying GWT applications with both client- and server-side components Here we discuss creating and sharing
GWT projects as libraries and creating deployable Web Application Archive (WAR) files This is also where we first touch on using an automated build with GWT, and we cover the use of both Ant and Maven
We put the automated build technique to further use in chapter 8, where we cover continuous integration and testing Testing has some unique aspects in GWT, and some complications involving performance, code coverage, and remote testing, all of which are addressed here
Then we move on to the third part of the book, “Dirty Hands.” As the title of this part implies, this is where we roll up our sleeves and crank out some non-trivial exam-ple applications In chapter 9 we cover the use of Data Transfer Objects (DTOs) as part
of the GWT application model Here we discuss the integration of server-side libraries such as Spring, and we build out an Ajax-enabled administrative CRUD (Create Read Update Delete) interface for a bookstore
In chapter 10 we continue the sample application from chapter 9 and add the user-facing storefront We further discuss security and the concept of roles, and then
we add some eye candy by creating a drag-and-drop system for GWT We also discuss
JSNI special effects
In chapter 11 we get into another sample application, this time a screen-sharing example that utilizes the Comet push technique In this example, we deal with appli-cation state using the GWT history mechanism, and we also cope with state on the server side
Finally, we conclude the book with two appendices that provide valuable reference information Appendix A describes many impressive third-party GWT applications or libraries that you can use to enhance or extend your own applications Appendix B is
a general reference that includes GWT tools and options, definitions for GWT module descriptor and host page elements, a list of emulated JRE classes available with GWT, a description of GWT serializable types, and a list of common user interface widgets and the event handling they support
Trang 17ABOUT THIS BOOK
xvi
Code conventions
In the text, the names of classes, keywords, interfaces, XML elements, code, and other code-related terms are presented in a monospacefont In longer code examples, some lines have been reformatted to fit within the available space on the page Additionally, some lines of code were so long that they simply couldn’t be represented and we have truncated them with the [ ] signifier and noted them
Code annotations are used in place of inline comments in the code These light important concepts or areas of the code Some annotations appear with num-bered bullets that are referenced later in the text The original source code also contains additional comments you might find of value
high-Code downloads
All the code referenced in this book is available for download from ning.com/GWTinPractice or www.manning.com/cooper We expect that if you are working through the book as a practical exercise, you will download and have this code available, as not all the code needed to run the projects is included in the text of the book
Once you have unzipped the example source distribution, you will find it nized by chapter Each chapter’s folder contains a readme.txt file that provides spe-cific setup instructions or considerations for working with that code There is also a top-level file that provides a detailed overview of the project layout conventions The example code works for Mac, Windows, and Linux users To get started, you should set up two environment variables: JAVA_HOME (if you don’t have it set by default), and GWT_HOME These can be set using the set command on Windows, or
orga-export on Mac OS X or Linux
Author Online
The purchase of GWT in Practice includes free access to a private forum run by
Man-ning Publications where you can make comments about the book, ask technical tions, and receive help from the authors and other users You can access and subscribe
ques-to the forum at www.manning.com/GWTinPractice This page provides information
on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct in the forum
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the authors can take place It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains voluntary (and unpaid) We suggest you try asking the authors some challenging questions, lest their interest stray! The Author Online forum and the archives of previous discussions will be accessi-ble from the publisher’s website as long as the book is in print
Trang 18about the cover illustration
The figure on the cover of GWT in Practice is a “Janissary in Ceremonial Dress.”
Janis-saries were an elite corps of soldiers in the service of the Ottoman Empire, loyal only
to the Sultan The illustration is taken from a collection of costumes of the Ottoman Empire published on January 1, 1802, by William Miller of Old Bond Street, London The title page is missing from the collection and we have been unable to track it down
to date The book's table of contents identifies the figures in both English and French, and each illustration bears the names of two artists who worked on it, both of whom would no doubt be surprised to find their art gracing the front cover of a computer programming book two hundred years later
The collection was purchased by a Manning editor at an antiquarian flea market in the “Garage” on West 26th Street in Manhattan The seller was an American based in Ankara, Turkey, and the transaction took place just as he was packing up his stand for the day The Manning editor did not have on his person the substantial amount of cash that was required for the purchase and a credit card and check were both politely turned down With the seller flying back to Ankara that evening the situation was get-ting hopeless What was the solution? It turned out to be nothing more than an old-fashioned verbal agreement sealed with a handshake The seller simply proposed that the money be transferred to him by wire and the editor walked out with the bank information on a piece of paper and the portfolio of images under his arm Needless
to say, we transferred the funds the next day, and we remain grateful and impressed by this unknown person’s trust in one of us It recalls something that might have hap-pened a long time ago
Trang 19ABOUT THE COVER ILLUSTRATION
xviii
The pictures from the Ottoman collection, like the other illustrations that appear
on our covers, bring to life the richness and variety of dress customs of two centuries ago They recall the sense of isolation and distance of that period—and of every other historic period except our own hyperkinetic present
Dress codes have changed since then and the diversity by region, so rich at the time, has faded away It is now often hard to tell the inhabitant of one continent from another Perhaps, trying to view it optimistically, we have traded a cultural and visual diversity for a more varied personal life Or a more varied and interesting intellectual and technical life
We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the computer business with book covers based on the rich diversity of regional life of two centuries ago‚ brought back to life by the pictures from this collection