Skip to main content

Real Ajax for Real Java developers: GWT

Everyone know about GWT right ? This is Java framework for creating real rich ajax applications using the Java language and not using JavaScript. The idea is that your project have two parts : client side and server side. The server side is Java and is compiled to Java using javac and putted in the web server the client side is compiled to JavaScript using GWT Java2JavaScript compiler, the communication between server side and client side is using async call, the result is : real AJAX.

First why I call it real ajax ? The common way to make rich applications this days ( or maybe from 2005 till now) is to use non ajax web framework and use custom ajax controls that uses UpdatePanel or AjaxPanel that makes “partial rendering”.
In typical Non Ajax application (lets use ASP.net or JSF) when we submit the form or make a call using a button server creates the HTML result and send it to the browser. The browser just visualized the HTML and “voala” we have regular page. To create the view in server side is not the best idea but it was used for the last 10 years or more.

Lets create a simple ASP.net page ( I will create ASP.net page not JSF page because it is faster there is no difference in the result and the way how it is created, they are almost the same).

The ASP.net page looks like this:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
</html>



 



When we click the button with ID Button1 we invoke some server side logic. So to invoke it we make a submit of our form and executes the action(method) it is the same like we did with Struts in 2002. Our method just changes the text in the TextBox1 LOL we can make it with JavaScript but in 2002 till 2005 no one wants to hear about JavaScript so we have :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Voala";
}
}



when we make a submit of this page the server returns the whole new response and the browser refreshes. I will use firebug to see the response of the call it looks like this:




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0MDM4MzYxMjNkZPJve7rYC/PGVOdFFdRTdiGKYG/K" />
</div>

<div>

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLE77ufDwLs0bLrBgKM54rGBv3Oo8jrqGGAkfJCVYhL30amEfxf" />
</div>
<div>
<input name="TextBox1" type="text" value="Voala" id="TextBox1" />
<br />
<input type="submit" name="Button1" value="Button" id="Button1" />
</div>
</form>
</body>
</html>



Wow the result was 804B just for the text Voala, maybe here some Dojo/Mojo etc developer will laugh and say just create a JavaScript function man.



In typical AJAX application using ASP.net and or JSF we have some kind of updatable panel and some JavaScript libraries that are inserted automatically from the framework and that makes the partial rendering.  To create an ASP.net AJAX application because it is simpler than JSF RichFaces application. The ASP.net AJAX page looks like this :




<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>



The idea is that when we make a request the response sended from the server is only the content of this UpdatePanel so the response is “HTML” and the JavaScript AJAX library just replaces the old content with the new content (yes it makes a lot of other things like adding listeners to components and etc.) But when we make a call the response looks like this :




189|updatePanel|UpdatePanel1|
<input name="TextBox1" type="text" value="Voala" id="TextBox1" />
<br />
<input type="submit" name="Button1" value="Button" id="Button1" />
|48|hiddenField|__VIEWSTATE|/wEPDwUINzcxOTk0MDJkZHSPHZdmYurKtHlUqe6IDY0NDG3E|56|hiddenField|__EVENTVALIDATION|/wEWAwKA97K8CgLs0bLrBgKM54rGBocZWWYZCHRaxZUGe6GQYbkXE1Wy|0|asyncPostBackControlIDs|||0|postBackControlIDs|||13|updatePanelIDs||tUpdatePanel1|0|childUpdatePanelIDs|||12|panelsToRefreshIDs||UpdatePanel1|2|asyncPostBackTimeout||90|12|formAction||Default.aspx|



Yes there is some VIEWSTATE “SHIT” that is ASP.net SHIT but you know the idea(you can see this buy yourself with firebug). The result is 584B WOW if you ask me 804B vs 584B not a big deal. The only plus is better use experience because its page doesn't blink. Anyway the RichFaces + JSF example is almost the same the result looks like this




<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body><span id="j_id359:textBox1"
>Voala</span><meta name="Ajax-Update-Ids" content="j_id359:name" /><span id="ajax-view-state"
><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="j_id2"
/></span><meta id="Ajax-Response" name="Ajax-Response" content="true" /></body></html>



The result is almost the same but there is no BIG viewstate.value. Anyway I’ve hear the term AJAH from one MAX conf so we can say that THIS IS NOT AJAX THIS IS AJAH why ? because the response is HTML so this is Asynchronous JavaScript and HTML, in typical AJAX application like the applications that we want to create we must use JSON for the response and we will want the view to be in the client and we will want to use the server as a server.



How typical ASP.net, PHP, XXX where XXX is everything developers make real AJAX? with JavaScript this will be the way how the things will be done in ASP.net 4.0 too with JavaScript client side controls that will make async calls to ASP.net methods. I can say only OMG. I don't want JavaScript because I dont like Scripting languages and because they dont have the great IDE support that we Java developers want (there is no JavaScript ide like IntelliJ IDEA right ? ). The Java community have an option that other developers dont have : GWT or Real AJax without JavaScript. The result is that we use real AJAX without JavaScript like no one else.



Real AJAX way: lets create a GWT project and add the fallowing content. This is 100% Java code no JavaScript :




public class TestGWTModule implements EntryPoint {
private Button clickMeButton;
public void onModuleLoad() {
RootPanel rootPanel = RootPanel.get();

final TextBox textBox=new TextBox();
clickMeButton = new Button();

rootPanel.add(textBox);
rootPanel.add(clickMeButton);

clickMeButton.setText("Click me!");
clickMeButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
textBox.setText("Voala");
}
});
}
}



And yes we can make async call if we want in the event handler. You can read how we can do that in free GWT documentation provided by google it is easy.In this code we can even use Generics and ArrayLists and almost whatever we will need, yes for example we cant use Threads but do we have Threads in javaScript ? The result is that when we invoke this code we get 0B response why ? Because it is compiled to JavaScript !



Lets make it AJAX so we will need a GWT RPC service you can read how to create one here : http://code.google.com/webtoolkit/tutorials/1.6/RPC.html When we change the clickHandler to make an Ajax call the new handler looks like this :




clickMeButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
HelloServiceAsync helloService=GWT.create(HelloService.class);
((ServiceDefTarget)helloService).setServiceEntryPoint("/hello");
helloService.sayVoala(new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
textBox.setText(result);

}
@Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});

}
});



Maybe this looks strange to some of us ( which don't have experience with GWT) but it is not so hard and there is good IDE support which creates most of the code like the service interface, implementation and async object. Anyway the result is that the response is serialized by gwt and looks like this :




//OK[1,["Voala"],0,5]



and it is only 21B ! So yes THIS IS AJAX like it should be. I know that there is some .net projects like Script# that are kind of dead, maybe it is good time to resurrect them? Where is the community ? or Alt.net community ? Guys ? Anyone ? :)



I hope anyone have a clue what the ajax should be and what it is now I really hope to have fastest and better AJAX applications in the feature because this is how the browser must be used not like in 2005.

Comments

Bo said…
Hey Joke, there was a time you didn't like this "satan's" technology at all :)
Toi said…
In my opinion, you don't see something like this:

<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body><span id="j_id359:textBox1"
>Voala</span><meta name="Ajax-Update-Ids" content="j_id359:name" /><span id="ajax-view-state"
><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="j_id2"
/></span><meta id="Ajax-Response" name="Ajax-Response" content="true" /></body></html>

in GWT is because GWT changes the DOM directly (not the html source). It doesn't mean that GWT doesn't have anything like that.

Personally, I prefer using EL to bind html element values to properties of Java objects (I'm 99% sure that GWT can do the same because in the past, I almost did it) and using EL to execute a server method than

HelloServiceAsync helloService=GWT.create(HelloService.class);
((ServiceDefTarget)helloService).setServiceEntryPoint("/hello");
helloService.sayVoala(...
jNayden said…
The gwt changes the DOM directly yes but using JavaScript. The response from the server is pure JSON and when the JavaScript client side receives this response it makes changes to the DOM. In other AJAH frameworks you get the hole HTML content and the JavaScript library just replaces the old innerHtml in this id with the new innerHtml. The result is bigger responses for each call which sucks.

Anyway about the EL yes maybe the syntax for calling a method like #{managedBean.action} is better than the GWT way but this doesnt make the actual call right? you are just telling with EL that when the page is submited the facesServlet must invoke this action at certain lifecicle step, so it is not the same. Anyway this 3 lines of code ( the secound one can be omitted because you can specify it with Annotation in GWT 1.6 and you dont need to pass it before the call ) so this 3 lines can be written : GWT.create(HelloService.class).sayVoala(....) which is not so mutch more code than : #{helloService.sayHello} something else when you need to pass paraemeters I just say sayVoala(param1,param2,param3) you need to use <f:param 3 times so does EL really better ?:)
Mark Nuttall said…
FYI, it doesn't come from Microsoft but Visual WebGui looks pretty good if you gotta do .Net. Of course it is not OSS but it does have a community edition.

BTW, your post page doesn't work too well in FireFox.
jNayden said…
mnuttall about the firefox - yes i Know that is because I've used Windows Live Writer to post this blog and it is kind of buggy :)
Anonymous said…
"In other AJAH frameworks you get the hole HTML content and the JavaScript library just replaces the old innerHtml in this id with the new innerHtml."

Not at all... What you return is generated and determined server side - be it XML, JSON, HTML or whatever. All the major Javascript frameworks out there (jQuery, Prototype, YUI, Dojo, mootools etc) - and self scripted javascript - let you invoke an ajax request, return and parse the JSON response and then manipulate the DOM. Most well written UI's follow this approach.

The magic of GWT, is that you write pure java - which means you can easily unit test, don;t need to learn javascript or the quirks associated with it, and GWT compiles optimized code.
jNayden said…
Anonymous : yeah sorry I've wanted to say not "in other AJAX frameworks... " I've wanted to point only RichFaces/IceFaces + JSF and ASP.net AJAX.
Anonymous said…
Also, commenting on your blog is broken on firefox 3+. Captcha input textbox is hidden. Had to edit the css to post.
Anonymous said…
Jquery and ASP.net integrate tightly - and nicely. Particuarly with ASP.net MVC.
jNayden said…
Yeah but you have to use Client side controls so you have to manually update everything from JavaScript which is not the best way. I assume that you are a ASP.net programmer what was happened to Script# ? why this project is dead ?
jNayden said…
About the anonymous accounts and captcha I will check it, Thanks
jNayden said…
i've makes the comments to be posted in popup now the captcha looks fine I think.
Unknown said…
@JOke: "Real AJAX way: lets create a GWT project and add the fallowing content. This is 100% Java code no JavaScript"

Give a try to ItsNat.

In a few words ItsNat is DHTML in the server. It mixes the best of both worlds:

Pure HTML with no logic.
Java W3C DOM code for view logic.

Is strongly based on AJAX and promotes Single Page Interface applications.

Popular posts from this blog

Convert PFX certificate to JKS, P12, CRT

I recently had to use a PFX certificate for client authentication (maybe another post will be coming) and for that reason I had to convert it to a Java keystore (JKS).  We will create BOTH a truststore and a keystore, because based on your needs you might need one or the other.  The difference between truststore and keystore if you are not aware is(quote from the JSSE ref guide : TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted. KeyManager: Determines which authentication credentials to send to the remote host. Ok that's enough what you will need is openssl and Java 7+ ;) ! First let's generate a key from the pfx file, this key is later used for p12 keystore. openssl pkcs12 -in example.pfx -nocerts -out  example .key   Enter Import Password: MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase: As shown here you will be asked for the password of the pfx file, l

Hibernate Generic DAO.

When you use Hibernate and DAO pattern it is a good idea to use a Generic Base Dao. The fallowing code snippet contains GenericDAO that is a base class for all my DAO classes. This GenericDAO uses HibernateDaoSupport from Spring for its implementation if you want you can use JpaDaoSupport or JdbcDaoSupport in your projects. My Generic DAO interface looks like this : package org.joke.myproject.dao.base; import java.io.Serializable; import java.util.List; /** * @author Naiden Gochev * @param <E> * @param <PK> */ public interface GenericDao<E,PK  extends Serializable> {     PK save(E newInstance);     void update(E transientObject);     void saveOrUpdate(E transientObject);     void delete(E persistentObject);     E findById(PK id);     List<E> findAll();     List<E> findAllByProperty(String propertyName,Object value); } All method names are very common so I don't

Patching a Maven library with your custom class.

Sometimes you use a library that has a bug. Or maybe it doesn’t has a bug but you want to change something. Of course if it is an open source you can get the sources… build them … with your change and so on. However this first takes a lot of time and second you need the sources. What you usually want .. is to just replace one class.. or few classes with something custom… maybe add a line .. or remove a line and so on. Yesterday… I had an issue with jboss-logging. The version I was using was 3.2.0Beta1 and it turns out that using this version and log4j2 2.0 final basically meant that no log is send to log4j2. The reason was a null pointer exception that was catched in jboss logging class called Log4j2Logger. The bug I submitted is here https://issues.jboss.org/browse/JBLOGGING-107 and it was fixed at the same day. However I will use it as an example since I didn’t knew when this will be fixed.. and I didn’t want to wait till it is fixed. So I was thinking what I want.. to take the j