Welcome to my blog, hope you enjoy reading
RSS

Saturday 17 November 2012

Gwt Json


Gwt Json

Step1: Create the GWT project

Step2: Create the Servlet in server package
example:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JsonStockData extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try
{
PrintWriter out = resp.getWriter();
out.println('[');==================//Start of the json data
String name = req.getParameter("q");
String encryption=byteArrayToHexString(computeHash(name));
out.println(" {");===============//Start of the object
out.print(" \"name\": \"");=========//key for pojoclass variable
out.print(name+"\");=================//value for pojoclass variable
out.println(",");===================//separetion for the variables
out.print(" \"encryption\": \"");
out.print(encryption+"\"");
out.println(" },");===============//end of the object
out.println(']');==================//end of the json data
out.flush();
}catch(Exception e)
{
System.out.println(e);
}
}
public byte[] computeHash(String x) throws Exception
{
java.security.MessageDigest d =null;
d = java.security.MessageDigest.getInstance("SHA-1");
d.reset(); d.update(x.getBytes());
return d.digest();
}
public String byteArrayToHexString(byte[] b)
{
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++)
{
int v = b[i] & 0xff;
if (v < 16)
{
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
}
Step 3: Add the following data in web.xml
example:
<servlet>
<servlet-name>jsonStockData</servlet-name>
<servlet-class>com.json.server.JsonStockData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jsonStockData</servlet-name>
<url-pattern>/jsonproject/jsonproj</url-pattern>
</servlet-mapping>

Step4: Write the jsonobject class in client package

example:
import com.google.gwt.core.client.JavaScriptObject;

public class jsondata extends JavaScriptObject
{
protected jsondata(){}
// JSNI methods to get stock data.
public final native String getName() ======//javaobject see servlet(step2)
/*-{ return this.name; }-*/;
public final native String getEncryption()
/*-{ return this.encryption; }-*/;
}

Step 5: Call the url in the client side
Step 5.1: formate the url
example:
private static final String JSON_URL = GWT.getModuleBaseURL() + "jsonproj?q=";

Step 5.2:Add the query Strings
example:
String url = JSON_URL+”name”;
url = URL.encode(url);


Step 5.3:Send request to the server
example:
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
Window.alert("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response)
{
if (200 == response.getStatusCode())
{
Window.alert(response.getText());
updateTable(asArrayOfJsonData(response.getText()));
}
else {
Window.alert("Couldn't retrieve JSON2 (" + response.getStatusText()
+ ")");
}
}
});
} catch (RequestException e) {
Window.alert("Couldn't retrieve JSON1");
}

Internal methods for the above code:
==========This method for the getting and divide the json objects=====
private void updateTable(JsArray<jsondata> jsArray)
{
for (int i = 0; i < jsArray.length(); i++) {
updateTable(jsArray.get(i));
}
}
==========This method for getting the each object and values=====
private void updateTable(jsondata jsondata)
{
Window.alert(jsondata.getName()));
Window.alert(jsondata.getEncryption()));
}

==========Convert the string of JSON into JavaScript object=====
private final native JsArray<jsondata> asArrayOfJsonData(String json)
/*-{
return eval(json);
}-*/;

0 comments: