Tags First GWT

Tags First GWT

by Zack Grossbart on May 31, 2009

The Google Web Toolkit (GWT) speaks to all the Java programmers left petrified by the thought of web programming. GWT has a siren’s call: forget about cross browser issues, don’t bother with JavaScript, stay away from HTML. In reality, GWT requires deft piloting to stay off the rocks.

In case you’ve never heard of it, GWT is an open source project from Google that compiles Java code into JavaScript. You write your Java code just like a desktop application and get JavaScript on the other end. Instead of onClick=myFunction() you write myObject.addClickListener(this);

Desktop programmers love this style of programming because… well… we hate web programming. JavaScript feels beneath us. It isn’t strongly typed, isn’t object oriented, and doesn’t even have a compiler. A friend of mine described JavaScript this way: “You get a bunch of type safety bugs from the 1980’s.”

Desktop programmers want to focus on the implementation and the data; GWT speaks to us. “Don’t use a table tag, just use a FlexTable. Don’t use a div tag, just use a FlowPanel. Don’t worry about HTML. Forget about CSS. We’ll handle it for you.” And therein lies the rub. It does abstract away some of the complexity, but you can’t use GWT without an understanding of HTML and CSS. Without that, the developers and the designers have big problems. It happened in my company.

We started using GWT last year. We combined a team of seasoned desktop programmers with a designer who knows web programming. The designer spent awhile creating a prototype in HTML, CSS, and JavaScript. When he was satisfied with the prototype he sent it to the programmers and they said, “We can’t do that in GWT.”

Prototyping in HTML and then adding the data binding is a time tested design pattern. Why doesn’t it work with GWT? GWT doesn’t let you control the tags. You get table tags when you want div and div tags when you want span. GWT gave away a more polished UI for easier coding, and that is one exchange your users will never be thankful for.

StudyBlue ran into the same problem and their response was emphatic: “Use GWT to build the house, not to paint it.” Write the tags first. Don’t start with your database design or a UML diagram. Start with the HTML. Designing a prototype in HTML and working from that is possible. We’ll use the WordPress login screen as an example.

WordPress Login In GWT

wp_login

I use WordPress almost every day. Their admin UI is clean, functional, and polished. It’s one of the few web applications that makes me forget it is a web application. Let’s take the WordPress 2.7.1 login panel and write it in GWT.

Start by understanding the page. Notice that it has rounded corners, nice spacing, and pleasing background colors. It has something else. The HTML and CSS are already written. This is really important since most desktop programmers don’t have the experience to write CSS.

Using GWT’s FlexTable for this would meant rewriting the HTML and therefore the CSS. GWT widgets generate their own HTML tags and they don’t match up with the existing CSS. The goal is to keep the tags and use GWT for data binding. In order to use the existing CSS we need to keep the original HTML. Let’s look at it.

<form method="post" action="wp-login.php" 
id="loginform" name="loginform">
  <p>
    <label>Username<br/>
      <input type="text" class="input" 
      id="user_login" name="log"/>
    </label>
  </p>
  <p>
    <label>Password<br/>
      <input type="password" class="input" 
      id="user_pass" name="pwd"/>
    </label>
  </p>
    <p class="forgetmenot">
      <label>
        <input type="checkbox" value="forever" 
        id="rememberme" name="rememberme"/> 
        Remember Me
      </label>
    </p>
  <p class="submit">
    <input type="submit" value="Log In"
    id="wp-submit" name="wp-submit"/>
  </p>
</form>

This HTML doesn’t use any table or div tags. The designer used p tags and we don’t want to lose that. We’ll start by escaping the HTML into a Java string.

Escape the HTML

There is no way around it: escaping quotes is a pain in the butt. PHP has a nice syntax to include strings that haven’t been escaped, but Java doesn’t. GWT is working on a way around this which may be included in the 1.6 release. Until then we need to encode the HTML as a Java string which means we need to escape all the double quotes with backslashes. It looks like this:

String html = 
"<form method=\"post\" action=\"wp-login.php\"" + 
"id=\"loginform\" name=\"loginform\">" +
  "<p>" +
    "<label>Username<br/>" +
    "<input type=\"text\" class=\"input\"" +
    "id=\"user_login\" name=\"log\"/></label>" +
  "</p>" +
  "<p>" +
    "<label>Password<br/>" +
    "<input type=\"password\" class=\"input\"" + 
    "id=\"user_pass\" name=\"pwd\"/></label>" +
  "</p>" +
  "<p class=\"forgetmenot\">" +
     "<label>" +
        "<input type=\"checkbox\" value=\"forever\"" + 
        "id=\"rememberme\" name=\"rememberme\"/>" +
        "Remember Me" + 
     "</label>" + 
  "</p>" +
  "<p class=\"submit\">" +
    "<input type=\"submit\" value=\"Log In\"" + 
    "id=\"wp-submit\" name=\"wp-submit\"/>" +
  "</p>" +
"</form>";

Is this really necessary?

Escaping and embedding your HTML into a Java file is not ideal and there is an alternative. GWT includes an HTML file which anchors the JavaScript GWT will use. Normally this page includes only a single script tag.

We could add the HTML for our form there, but that would mean losing modularity. As your application gets more complicated the utility of separating different functions will become clear. Breaking your HTML up into separate pieces also encourages you to keep your HTML simple and use GWT to focus on data binding. Techniques like CSS-based form layout are a good way to simplify your HTML.

Remove the Fields

The power of GWT is in its data binding. We have the HTML, but we want to use GWT to bind the data. So we take all the fields out of the HTML and we are left with this:

String html = 
"<form method=\"post\" action=\"wp-login.php\" " + 
"id=\"loginform\" name=\"loginform\">" +
  "<p>" +
    "<label>Username<br/>" +
  "</p>" +
  "<p>" +
    "<label>Password<br/>" +
  "</p>" +
  "<p class=\"forgetmenot\">" + 
    "<label>Remember Me</label>" + 
  "</p>" +
  "<p class=\"submit\">" +
  "</p>" +
"</form>";

Create Your HTMLPanel

The format is ugly, but this chunk of HTML is very manageable. We can make it a GWT widget using GWT’s HTMLPanel. Using the string of HTML we just defined to create an HTMLPanel is easy:

HTMLPanel myPanel = new HTMLPanel(html);

Add Element IDs

The HTMLPanel really is that simple. However, we have two more steps before we can add the fields back. Each of our container tags must have an ID. I’ll show you why in a moment. We also want to remove the form tag. GWT submits all forms using JavaScript so you don’t need the form tag. We replace the form tag with a div tag, add IDs, and we get this:

String html = 
"<div id=\"loginform\" name=\"loginform\">" +
  "<p id=\"username\" >" +
    "<label>Username<br/>" +
  "</p>" +
  "<p id=\"password\">" +
    "<label>Password<br/>" +
  "</p>" +
  "<p id=\"forgetmenot\" class=\"forgetmenot\">" +
    "<label>Remember Me</label>" +
  "</p>" +
  "<p id=\"submit\" class=\"submit\">" +
  "</p>" +
"</div>";

Bind the Fields

Now we are ready to bind the fields. The field binding happens by using HTMLPanel to do some very simple DOM mnipulation. We also set an ID for the TextBox’s element and apply a class (GWT calls it a style name) from our CSS. It looks like this:

TextBox user = new TextBox();
user.addStyleName("input");
user.getElement().setId("user_login");
myPanel.add(user, "username");

The last line here is where the magic happens. The HTMLPanel will add the new TextBox as a child of the element with the id username. We’ll add the rest of the fields the same way:

TextBox password = new PasswordTextBox();
password.addStyleName("input");
password.getElement().setId("user_pass");
myPanel.add(password, "password");

CheckBox forgetMeNot = new CheckBox();
forgetMeNot.getElement().setId("rememberme");
myPanel.add(forgetMeNot, "forgetmenot");

Button submit = new Button("Log In");
submit.getElement().setId("wp-submit");
myPanel.add(submit, "submit");

All of these fields are first class GWT widgets. We can submit them back to the server using AJAX calls, add listeners to fire events when the user changes them, or set their values programmatically. We have full support for any data binding we want.

Now that we have all the pieces, let’s put it together into a GWT EntryPoint. An EntryPoint is the main page for your application and it gets initialized when the onModuleLoad method is called. This method is where we need to put all the code we have.

Put It All Together

GWT is Java and in Java you must define a class. We’ll combine all of our HTML and data bound widgets into a class that implements EntryPoint. We can then add our HTMLPanel to the main page using RootPanel and add a ClickListener so we can see when the user presses the login button. The result is:

public class MyModule
implements EntryPoint, ClickListener {
  private static final String html = 
    "<div id=\"loginform\" name=\"loginform\">" +
      "<p id=\"username\" >" +
        "<label>Username<br/>" +
      "</p>" +
      "<p id=\"password\">" +
        "<label>Password<br/>" +
      "</p>" +
      "<p id=\"forgetmenot\" class=\"forgetmenot\">" +
        "<label>Remember Me</label>" +
      "</p>" +
      "<p id=\"submit\" class=\"submit\">" +
      "</p>" +
    "</div>";
  
  public void onModuleLoad() {
    HTMLPanel myPanel = new HTMLPanel(html);
    
    // The username field
    TextBox user = new TextBox();
    user.addStyleName("input");
    user.getElement().setId("user_login");
    myPanel.add(user, "username");

    // The password field
    TextBox password = new PasswordTextBox();
    password.addStyleName("input");
    password.getElement().setId("user_pass");
    myPanel.add(password, "password");

    // The forget me not checkbox
    CheckBox forgetMeNot = new CheckBox();
    forgetMeNot.getElement().setId("rememberme");
    myPanel.add(forgetMeNot, "forgetmenot");

    // The log in button
    Button submit = new Button("Log In");
    submit.getElement().setId("wp-submit");
    myPanel.add(submit, "submit");
    submit.addClickListener(this);

    /*
     * Add our panel to the page
     */
    RootPanel.get().add(myPanel);
  }

  public void onClick(Widget sender) {
    /*
     * Our button was clicked...
     */
  }
}

The results will be exactly the same as the existing WordPress login, but have full data binding support from GWT.

Tags First

This example is simple, but the technique is a powerful way to write GWT applications. Tags first. You already know what you want the HTML to look like, so make GWT generate it. This technique has some clear advantages over the standard GWT way of doing things.

  1. You get total control over the tags.
  2. You don’t have to change your CSS.
  3. The integration between designers and programmers is much easier.
  4. You can still use standard GWT widgets when you want to.

This approach also scales very well. Create whatever complex HTML you need and then add the data binding. Want to create CSS form layouts like LinkedIn? No problem. Need to dazzle your clients with websites that rival Jason Santa Maria? You can still use the fast coding of GWT!

The promise of GWT is a powerful one: stop writing JavaScript. Not: stop writing JavaScript if you don’t care how your application looks. No tool is worth it if it doesn’t do what you want.

  • kebernet

    Why would you not just use UIBinder or Kiyaa?

  • http://www.clarityaccounting.com Dobes Vandermeer

    We built our product, Clarity Accounting, using GWT and I ran into the same issue. To get around this I created a templating language based on facelets (another java technology for rendering XHTML pages). Basically you write the HTML page and the mark it up with special tags and attributes to attach your UI to it. A GWT generator converts the template into Java code that is compiled and run to invoke your events and so on.

    Learn more at the Kiyaa! GWT Toolkit project:

    http://code.google.com/p/kiyaa/

  • Zack

    Thank you both for commenting.

    I stayed away from UI Binder and Kiyaa because I didn’t want to introduce a new templating mechanism or special tags. My goal was to keep the HTML as close to the real thing as possible. I have also had problems with templating engines in the past from a maintainability point of view. Breaking the page into smaller pieces makes everything more reusable.I also wanted to avoid all logic in the HTML template.

    All of that said, it depends on the application you’re writing. I used the techniques in this article to create a set of reusable widgets that are totally compatible with standard GWT. If you are creating a smaller application the simplicity of a templating mechanism would probably be the way to go.

  • Sakuraba

    If you would like to stay “html-centric”, why not use GwtQuery and use progressiv enhancements?

  • Zack Grossbart

    Sakuraba,

    Thank you for commenting. I am a big fan of JQuery and often combine it with GWT applications. I haven’t used GWTQuery yet, mostly because it is so new. Looking at the documentation it looks like a good idea and yet another paradigm to work with.

    I’m also a little skeptical of the GWTQuery claims of progressive enhancement. GWT applications are very reliant on JavaScript. Supporting browsers without it may be technically possible, but it feels like it goes against the philosophy of GWT.

  • http://clay.lenharts.net/blog/ Clay Lenhart

    Here is a blog entry on how to have complete control over the HTML tags in a GWT way: http://clay.lenharts.net/blog/2009/05/25/gwt-is-flexible-iphone-demo/

    It uses two classes to accomplish this: GenericContainerTag and GenericTextTag.

  • shivaji

    i want to write an action for button like calculate
    I have two text boxes which consists of values if i want to add both
    it is xhtml+gwt

  • Zack Grossbart

    Hello Shivaji,

    Thank you for your comment, but I’m not sure exactly what you mean. Can you give me a few more details or an example of what you are trying to do?

    Thanks

  • David Pinn

    “You get table tags when you want div and div tags when you want span.”

    Yes, that’s true; but what about simpler widgets? I notice that you’re trusting TextBox, PasswordTextBox, Button, and CheckBox to produce the HTML you expect. So which widgets do we trust, and which do we not?

  • Zack Grossbart

    David,

    Thanks for the comment. I’ve grown to like the GWT widget model. The design pattern works well, but I have a few issues with individual widgets. In general I trust the form control widgets (Label being the exception) and I’m wary of the once used for layout. But that is just a rule of thumb. You need to look at each control and understand the pluses and minuses before you put it into a deployed application.

  • Pingback: Next: Trying to have nicely styled GWT forms « More Is Not Always Better

  • Dale

    Very new here, like 2 hours ago I did a search ‘gwt introduction’. But let me throw my naive observations out there and see if i get a response (this is an old blog post).

    1. Would a viable approach to avoid inlining html (which to my eye is very gross) be to create the html in jsp with the bindings to the containers as described above? What I’m wondering is, if you are leaning on GWT cheifly for data-binding, can you just make a reg ol jsp app, with pages served up par usual, just bound to gwt containers? (really asking here)

    2. Maybe a different development lifecycle is required for gwt applications. say:
    Functional Design -> gwt implementation -> styling. Place the polish and style at the end, certainly done that pattern before (thats how we approach our Flex development here).

  • http://www.zackgrossbart.com Zack Grossbart

    Hello Dale,

    Thanks for the comment. You can’t really mix GWT and JSPs that way. GWT becomes JavaScript that runs in your browser and JSPs become servlets that run on your server. You could do some back flips to make them work together, but it really wouldn’t be worth it.

    I’m also worried about leaving style and polish to the end. You can change the colors or the fonts at the last minute, but you can’t redesign your application and that is a big part of the polish.

    I’ve been using this tags first pattern for a while now and in practice you don’t write very much inline HTML. Most of your pages are very simple of you’re doing all of your layout in JavaScript. The HTML you’re adding is really just placeholders.

    You might be interested in a presentation about how we took this approach forward into an entire application: Our Spiffy UI.

  • ahmed shoeib

    now i need to build my application Interface using html
    this step done successfully

    — but now i need to send the data to server and get HTML Response
    can i do that or not ?
    and if not what is the best way to do that ?

  • http://www.zackgrossbart.com Zack Grossbart

    This method is just about the display of your application. You can make HTTP calls using the built-in GWT RPC mechanism or the REST. You might be interested in Calling REST from GWT with a little bit of JQuery

  • ahmed shoeib

    do you mean that if need to send and receive request from server using requestBuilder or RPC.
    and Tag First GWT not compatible to to send and receive response from server or what ?

  • http://www.zackgrossbart.com Zack Grossbart

    Creating your GWT UI in the style of this article is separate from how you call the server. It works well with any method you wish to use to access server data.

  • ahmed shoeib

    good. you mean that i can get my JSON Response from server side im my client side using
    ” Tag First GWT “.
    but this article not declared how to get response from server and handle it on the client side.
    how can i do that ?

  • http://www.zackgrossbart.com Zack Grossbart

    Ahmed,

    This article is just about handling the rendering of your GWT application. If you’re interested in handling JSON data you might want to look at the Google Web Toolkit Overview.

    Cheers,
    Zack

  • ahmed shoeib

    Mr.Zack
    Sorry for disturbing you
    but what i mean that i need to get the HTML Response from the server using ” Tag First GWT ” . i know how to handle JSON on the client side.
    but i need to get the HTML Response from server using “Tag First GWT ”

    I hope you have understood my purpose

  • http://www.zackgrossbart.com Zack Grossbart

    Ahmed,

    I don’t think I understand your question. If you use this “tags first” approach it doesn’t change anything about how you make calls to the server or handle JSON. You still end up with a GWT widget and can set values into it using all of the standard mechanism. Am I missing something about your question?

    Thanks,
    Zack

  • ahmed shoeib

    Mr.Zack,
    i mean how to call server if i use “tag first”. i don’t know how to call server ( send Data and get Response).
    i need an example explain using of “tag first” to send form content to server and do some logic on it. then return string which i need to get it on the client.

  • http://www.zackgrossbart.com Zack Grossbart

    Hello Ahmed,

    This article really doesn’t have anything to do with JSON handling. You can just use any of the standard mechanisms you would normally use with GWT.

    You should look at JSON <-> Java serialization that works with GWT on StackOverflow which is a great place to ask questions about these topics.

    Good luck with your application and thank you for reading.

    -Zack

  • Anonymous

    How does this work with custom widgets? I.e., I assume you don’t just have one big HTML file, right? How do you break it up into reusable custom widgets/HTML fragments? I can see how this works at the lowest level (where you’re working with HTML directly) but how does it work one or more levels up?nnAnd how do you handle dynamically added (custom) widgets?

  • http://www.zackgrossbart.com Zack Grossbart

    Hello Hilco,nnWe have a few examples of more complex custom widgets using this method. Check out:nnCreating A Multi-Valued Auto-Complete Field Using GWT SuggestBox And RESTnCreating A GWT Wrapper For The JQuery UI SlidernnThese both wrap JQuery controls, but it would work the same with GWT controls.

  • Pingback: What should a UX style guide contain? - Quora

  • Hilco Wijbenga

    Hi Zack,nnHow do you create/guarantee unique ids? You do reuse your widgets, right? So what do you do to get unique ids for each instance? (Specifically the ids for the elements that make up the widget.)nnDo your designers edit a string (that represents the HTML) in a Java file? Or do you somehow read in the HTML from an external (HTML) file during the build or at runtime?

  • http://www.zackgrossbart.com Zack Grossbart

    We try to keep the HTML for reusable widgets very small and we just embed it in the Java code. Each widget works a little differently. Sometimes we pass the ID in as an argument to the constructor and other times we generate a unique ID using the createUniqueId method on HTMLPanel.

  • http://twitter.com/rbrugier Raphau00ebl Brugier

    Hi,nnI’ve been really interesting in your article and the idea of writing clean html to get a perfect layout, but I also stongly disagree with the idea of writing html in a string without any control.nI think you should consider using UiBinder instead.nnI’ve rewrite your wordpress login example with UiBinder and post an article on my blog.nPlease seenhttp://www.raphael-brugier.fr/blog/2011/01/wordpress-login-form-with-gwt-and-uibinder/nnThanks,nnRaphau00ebl.

  • http://www.zackgrossbart.com Zack Grossbart

    Hello Raphau00ebl,nnThanks for the awesome UiBinder example. I’ve looked into UiBinder before, but it always feels really heavy weight for the simple HTML we’re generating. Your example UiBinder file is pretty large for a very small form. It also pushes most of the styles into that proprietary file instead of the CSS file.nnThe reality of the tags first method is that we try to modularize everything. We make the HTML we use for each widget very simple and then move it around to different places in the application. The goal is to avoid a single large file defining all of your UI.

  • http://twitter.com/manxomfoe Brian

    For my part, having the relevant css exist with the component is a big advantage. It’s all compiled into an external / cacheable css document anyway, complete with compile time collision detection and other workarounds to css deficiencies (like variables). When the alternative is looking up your class name from a 2000 line external CSS file… nnIt also reduces risk in change-controlled projects where multiple engineers are all poking at the same CSS file. Have fun merging and porting changes around. Ick.

  • http://www.lacostepoloshirtsshop.co.uk lacoste polo shirts

    Great review and an interesting topic. Nice job! I will bookmark your site. I think you are right. . This is my second visit to this blog. Your blog provided us with important information to work with!! You definitely answered all the questions!! Thanks very much! I really enjoyed reading this… Valuable information and excellent design you got here!!! This is a cool blogging platform. Aw, this was a really quality post. Took me awhile to read all the comments, but I really love the article?

  • Tom Carchrae

    I don’t think you need to inline the CSS in UiBinder, and the UiBinder docs even say so ( http://code.google.com/webtoolkit/doc/latest/DevGuideUiBinder.html#Hello_Stylish_World ).  My initial impression of UiBinder was one of contempt as well – now I’m starting to warm up to it a bit.  I’m sure it’s just the first date thing, will see how I feel tomorrow…

  • yuval heftman

    Use HTML tags and GWT DOM … combine with GWTQuery  and write logic in pure GWT …

    HTML:

    GWT:
    Element div = DOM.getElementById(‘myDiv’);

    CSS with GWTQuery:
    $(div).click(…………….)

  • Philippe Lhoste

    With UiBinder, you can have the CSS in a separate file while still having compile-time security: you can declare the styles (classes) in interfaces and refer to them in code or in the UiBinder file itself, you can use @def and other facilities to improve consistency (even if it is less flexible than SASS / LESS / similar). You can choose to keep the names clear (beware of conflicts) or they can be obfuscated by GWT. It is quite flexible with that.
    Another advantage is that you can freely use GWT components anywhere.
    And internationalization, while verbose, is convenient and flexible, something that would be harder to do with pure HTML. Having one HTML file per language would be a nightmare to maintain! Other solutions would be equivalent to reinvent PHP or some kind of template library… UiBinder is already there for that!
    A good point is that UiBinder is compatible with an HTML design: wrap it in an HTMLPanel, add ui:fields to parts you want to control, tweak here and there, and you are good to go.

    BTW, good articles, thanks for them.

  • http://www.facebook.com/seth.mart Seth Martin

    This is a fantastic tip and I have been converting all of my initial screens to follow this approach. Thanks a bundle!

  • Michael Herman

    This is a much better approach and one that I now implement religiously. Write the HTML and then escape it and put it in GWT as a string, that sounds like a pain. To put this in other words people should do this:
    Use UiBinder and an g:HTMLPanel. start wiritng the HTML in the panel. Most elements you could care less about but the ones you want to interact with gwt will need to be replaced with a gwt widget. Know what widgets give you what, HTMLPanel and flow panel give you a div. Anchor gives you an anchor (InlineHyperlink gives you an anchor but has a nice feature of already haveing a click handler on it that uses GWT’s history). You’ll need to write your own ul, li, ol and i widgets if you need to control them from GWT. you can google code for these and just copy and paste. HTML elements can contain class= and widgets can use styleName= so you can use css from a different file. One thing I reccomend is removing GWT’s css file, this can be done in the gwt.xml file. That way GWTs widgets will do what your css tells it to and not what GWT tells it.