DoJo and plain web app: how to get JSON Ajax result?

how-to
May 17, 20091 min

I’m working on a simple web app built with plain JSPs, Struts 1 and DoJo. Now there is that need to be able to call server-side methods and get responses wrapped in JSON. That is often solved by DWR, but it’s too heavy for my plain dumb project. Instead of that I turned to JSON Plugin from Struts 2 project. It’s just one small JAR library capable of converting any (complex) Java object into a JSON String:

Having JSON Plugin in classpath I can create a small servlet that calls a Java method depending on the request parameters, and sends its result in response as a JSON String.


Object oRes = someObect.someMethod();
String sResJson;
try {
  sResJson = JSONUtil.serialize(oRes);
} catch (JSONException e) {
  log.error(e);
  throw new ServletException(e);
}
resp.setCharacterEncoding("UTF8");
resp.getWriter().write(sResJson);

On the JavaScript side everything is simple, taken from the DoJo user guide:


dojo.xhrGet({
  url: "<a href="http://someurl/JsonDelegate?class=SomeClass&method=someMethod">http://someurl/JsonDelegate?class=SomeClass&method=someMethod</a>¶m=1",
  handleAs: "json",
  timeout: 5000,
  load: function(response, ioArgs) {
    // response is JSON result
    return response;
  },

  error: function(response, ioArgs) {
    alert("HTTP status code: " + ioArgs.xhr.status);
    return response;
  }
});