Saturday 25 February 2012

JSON Response with Spring Portlet MVC @ResourceMapping ,Jquery and JSON.


In recent times ,AJAX has gained momentum with the advent of javascript frameworks like jquery,Dojo etc. The server side handler can be a struts action method or Spring @Controller method.The question is how the same works in Spring portlet MVC.We can use either @RequestMapping,@ActionMapping  for the handlers.The problem with this approach is that it will cause the all the dependencies to be reinitialized and also the default RenderMapping  or the previously submitted form action will be invoked.This puts weight on the performance and also the amount of data returned. One possible and in fact best alternative is to use @ResourceMapping for the ajax handler.We have two ways of using the @ResourceMapping .
       1. ModelAndView as the return type from the handler method
       2.JSON response from the handler method.
Steps:
1.Create a portlet resource URL
<portlet:resourceURL escapeXml="false"
id="ajaxCall"  var=” ajaxCall” />
2.Use Jquery getJSON to invoke the ajax call 
     $.getJSON("${ajaxCall}", { //query params if any, function(data) {
          //data à JSON object returned
           //success call back method.here we can play around with DOM
        }
    });

3. Create a controller
@Controller
@RequestMapping("VIEW")
public class AjaxController{
}
4.Write a Resource handling method. Add the annotation @ResourceMapping
@ResourceMapping("ajaxCall")
public void ajaxHandler(ResourceRequest request, ResourceResponse response)
        throws IOException {
    OutputStream outStream = response.getPortletOutputStream();
    User user = new User();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(outStream, user);
}
For Java to JSON Conversion , we can use Jackson which is a high performance JSON processor java library and you need to have “jackson-mapper-asl” in your classpath.
Spring 3.0.5 automatically does this conversion using the @ResponseBody annotation in the handler method.However this is functional only in servlet environment and has issues in Portlet environment.
5.Another approach is returning the ModelAndView from the action method
@ResourceMapping("ajaxCall ")
public ModelAndView ajaxHandler (ResourceRequest request, ResourceResponse response) throws IOException {
   Map model = new HashMap();
   model.put("user", new User());//put your view objects
   return new ModelAndView("ajaxResponse", model);
}
In this approach, the “ajaxReposne” jsp is returned as text to the ajax callback handler method .Then we can play around with the DOM to get the desired results