Anatomy of JSON in GWT

Part 1: JSON Ajax Server

It is just a simple HttpServlet which streams back a json string

public class JSONStockData extends HttpServlet {

  private static final double MAX_PRICE = 100.0; // $100.00
  private static final double MAX_PRICE_CHANGE = 0.02; // +/- 2%

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    Random rnd = new Random();

    PrintWriter out = resp.getWriter();
    out.println('[');
    String[] stockSymbols = req.getParameter("q").split(" ");
    for (String stockSymbol : stockSymbols) {

      double price = rnd.nextDouble() * MAX_PRICE;
      double change = price * MAX_PRICE_CHANGE * (rnd.nextDouble() * 2f - 1f);

      out.println("  {");
      out.print("    \"symbol\": \"");
      out.print(stockSymbol);
      out.println("\",");
      out.print("    \"price\": ");
      out.print(price);
      out.println(',');
      out.print("    \"change\": ");
      out.println(change);
      out.println("  },");
    }
    out.println(']');
    out.flush();
  }

}

And servlet mapping in web.xml is

   <!-- Servlets -->
 <servlet>
    <servlet-name>jsonStockData</servlet-name>
    <servlet-class> gwt.stockwatcherjson.server.JSONStockData</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>jsonStockData</servlet-name>
    <url-pattern>/yourgwtmodulepath/stockPrices</url-pattern>
  </servlet-mapping>

Part 2 : url for JSON Ajax client

private static final String JSON_URL = GWT.getModuleBaseURL() + "stockPrices?q=";

Part 3: Data contract JSON Ajax client

public class StockData extends JavaScriptObject {
	
	 // Overlay types always have protected, zero argument constructors.
	  protected StockData() {}   
	  
	  // JSNI methods to get stock data.
	  public final native String getSymbol() /*-{ return this.symbol; }-*/; // (3)
	  public final native double getPrice() /*-{ return this.price; }-*/;
	  public final native double getChange() /*-{ return this.change; }-*/;

	  // Non-JSNI method to return change percentage.                       // (4)
	  public final double getChangePercent() {
	    return 100.0 * getChange() / getPrice();
	  }


}

It extends JavaScriptObject.

Part 4: request and response

// 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) {
	            displayError("Couldn't retrieve JSON");
	          }

	          public void onResponseReceived(Request request, Response response) {
	            if (200 == response.getStatusCode()) {
	              updateTable(asArrayOfStockData(response.getText()));
	            } else {
	              displayError("Couldn't retrieve JSON (" + response.getStatusText()
	                  + ")");
	            }
	          }
	        });
	      } catch (RequestException e) {
	        displayError("Couldn't retrieve JSON");
	      }

Tags:

This entry was posted on Friday, July 29th, 2011 at 3:17 am and is filed under Java, Javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Anatomy of JSON in GWT”

  1. Philly says:

    Keep these artilecs coming as they’ve opened many new doors for me.

Leave a Reply

*