Pages

Monday, May 18, 2009

Gwt Rpc - Json

Share it Please

In this blog iam going to explain how can we get a send and retrive Json Data from server using Gwt Rpc .

Lets write the interface necessary for making a RPC call.

public interface JsonService extends RemoteService {

public String getJsonData();

public void sendJsonData(String string);

public static class Util {

public static JsonServiceAsync getInstance(){

JsonServiceAsync async=(JsonServiceAsync)GWT.create(JsonService.class);

((ServiceDefTarget)async).setServiceEntryPoint(GWT.getModuleBaseURL()+"/server/callback");

return async;

}

}

}

//Don’t forget to add the servlet tag in .gwt.xml file:

//<servlet path="/server/callback" class="com.example.server.JsonServiceImpl"/>

Async interface For the Above Interface :

public interface JsonServiceAsync {

public void getJsonData(AsyncCallback callback);

public void sendJsonData(String string,AsyncCallback callback);

}

And the implementation class on the server side .

public class JsonServiceImpl extends RemoteServiceServlet implements JsonService {

public String getJsonData() {

JSONObject json = new JSONObject();

json.put("city", "Mumbai");

json.put("country", "India");

return json.toString();

}

public void sendJsonData(String string) {

System.out.println(string);

}

}

The JSONObject used here is not the Gwt releated Json object . this object belongs to Json library . u can see I constructed a JSONObject and returned a String representation of the json object.

Now lets see how can we access or send json data to the server side.in the onModuleLoad() , we can call as

Callback=new AsyncCallback() {

public void onFailure(Throwable caught) {

System.out.println("in Failure");

}

public void onSuccess(Object result) {

System.out.println("In Success");

}

};

myButton=new Button("Click Me",new ClickListener(){

public void onClick(Widget sender) {

JSONString str=new JSONString("jagadesh");

String myString=str.stringValue();

JsonService.Util.getInstance().sendJsonData(myString, Callback);

}

});

RootPanel.get().add(myButton);

You can see I constructed the JSONString object of gwt and set a value of “jagadesh”. Since these json objects cannot be moved thorough wire since these objects cannot be serialized . so I extracted a string object from the transferred it to the server side. Where on the server u can construct a jsonString object by using any json libraries .

Execute the application and check out the result.

No comments :

Post a Comment