Friday, July 6, 2012

Spring and JSON requests

In modern web applications it's almost vital to enable asynchronous page load protocols, such as AJAX.
This pattern is usually implemented with a client library (such as jQuery) that performs asynch calls to your web application and implementing controllers that handles this request returning JSON data.
To show this I'm going to suppose to load asynchronously the employes based on the office ID they work in.
First, the client side. Using jQuery it is very simple:
function loadEmployesByOffice(officeId){
 $.ajax({
  type : "GET",
  url : employes_service_uri_byofficeid,
  data : {
   "officeId" : officeId
  },
  dataType : "json",
  success : function(employes) {
   // some code to show the employes
  },
  error: function(){
   alert("Error");
  }
 });
}
where the var employes_service_uri_byofficeid is a valid uri pointing to your web application.
Next step is implementing the controller. Be careful: it must respond on the same path as the url parameter in the $.ajax call. I'm assuming something like
http://domain.com/services/json/employes
@Controller
@RequestMapping(value = "/services/json/employes")
class EmployeeService{
 ...

 @RequestMapping(value="/byofficeid", method=RequestMethod.GET, produces="application/json; charset=utf-8")
 @ResponseBody public String loadEmployesByOfficeId(@RequestParam("officeId") Long officeId){
  Collection employes = .... // load the employes
  return (new Gson()).toJson(employes);
 }

 ...
}
Here I'm assuming to use Gson as JSON marshaller. That is not the only choice: you could use Jackson or, if you are using Spring Roo, just add JSON support to your entities by adding the @RooJson annotation to your entity.
Note that the name "officeId" is the same in the jQuery call and in the @RequestParam annotation. This  can be omitted if the formal parameter in controller method has the same name.
Also, note the
produces="application/json; charset=utf-8"
this is important for IE that otherwise could fail while parsing the response.

You can check out a sample application built with Spring Roo 1.2.1. at this url.
That's all.

Bye,
Stefano

No comments:

Post a Comment