Tuesday, March 18, 2014

GWT - client server communication - json

So far my discussions about GWT are exclusively front end technologies, today let's move on to the more exciting client server communication world.

By far, I think the easiest way to expose server side functionality is to build some JSON services. There is even a funny name for it, "thin server architecture". Without further ado, let's build the simplest possible JSON service and deploy to tomcat.
@WebServlet("/serverTime")
public class ServerTimeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.getWriter().write(String.format("{\"time\":\"%s\"}",
                new Date().toString()));
    }
}

and test it
Now setup a new gwt client project, to access the XMLHttpRequest functionality, we need to make use of the RequestBuilder.
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "/gwtjson-server/serverTime");

rb.setCallback(requestCallback);
rb.setRequestData("");
rb.send();

the vanilla RequestCallback can only accept text response, we need to parse the JSON string using JSONParser.
private void processJson(String jsonText) {
    JSONValue json = JSONParser.parseStrict(jsonText);
    String serverTime = json.isObject().get("time")
                            .isString().stringValue();
    Window.alert("Server time is: " + serverTime);
}

However, JSON package is not enabled by default, so we need to add the following line to the gwt.xml file
<inherits name="com.google.gwt.json.JSON" />
Now run the gwtjson-client project as well as start the super dev mode,

Navigate to sdm.html (super dev mode host page), compile the project if necessary. For working with super dev mode, please refer to my previous post.
Notice, we are not constrained with java servers here, it is possible to serve the serverTime request with any capable servers, Apache, Node.js, .Net etc. The client project has nearly zero knowledge of the server side technology.

And for any sensible team you should not stop here, the request builder api is still quite primitive and cumbersome to use (Java 8 I am looking at you!). You are encouraged to come up with your own wrappers with a more fluent API. Here is an example
Ajax.url("/login")
    .param("username", username)
    .param("password", password)
    .post(callback);


Codes are available here https://github.com/verydapeng/gwt-tutorials, under gwtjson-client and gwtjson-server folders.

Happy Coding