This article is about integrating GWT with Grails. Here, GWT makes request to the Grails server which then returns a JSON object back to the GWT client.

Here’s a way to do post using GWT



RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
 "http://localhost:9098/json/json/jsontest");
rb.setHeader("Content-Type",
                   "application/x-www-form-urlencoded");
try
{
    rb.sendRequest("jsontext="+hellothere.toString(),
                          new DateCallbackHandler());
}
catch (RequestException e) {
    Window.alert(e.toString());
}

By the way, its calling a controller of a grails project.

Here’s how it handles it


def jsontest = {
   String _json = (params.jsontext)?
                         params.jsontext:'{"JSON":"text"}'
   JSONObject obj = new JSONObject(_json)
   render obj.getString("JSON")
}

Edit:

Mary, you should be able to find that info somewhere on the web. Essentially, you create a RequestBuilder, send a request using

sendRequest(java.lang.String requestData, RequestCallback callback)

callback should be a class that inherits RequestCallback interface. Now RequestCallback has a method

onResponseReceived(Request request, Response response)

that you should implement, and Response has some methods like getText() that you can use.

Cheers

4 Comments

  1. very cool code, was looking for it for a long time…

  2. I’m starting on GWT, can you give other examples where you are using the way “RequestBuilder” for RPC in GWT

  3. I was trying to send a POST request to “http://www.google.com/accounts/ClientLogin” but i get: “The URL
    http://www.google.com/accounts/ClientLogin is invalid or violates the same-origin security restriction” (i get this for anything starting with http:// or localhost). How can i get pass this? is there NO WAY to send a request to server/servlet in another domain??

  4. @And:
    You’re violating the Same Origin Policy (SOP), that’s a restriction of GWT to prevent Cross Site Scripting (XSS) attacks, so that you can only request elements hosted on your same domain.

    There are some ways to get around this which are documented in the GWT Docs. I recall reading about a technique called “JSON with Padding” or JSOP that allowed you to do something like what you’re trying to do ;)

    Hope this helps in any way.


Post a Comment

*
*