Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Wednesday, September 13, 2006

Spring MVC and AJAX with JSON

One of the main decisions to be taken while developing AJAX applications is the format of messages passed by the server to the client browser. There are many options to choose from including plain text, XML, CSV etc. One of the more popular choices today is the JavaScript Object Notation (JSON). JSON provides a nice name-value pair data format that is easy to generate and parse. This is especially true when using an AJAX toolkit like Dojo that provides built-in functionality to parse JSON messages at the client. If you are using Spring MVC as your web framework, generation of these JSON messages is very straight-forward as well. Below we understand how to produce JSON messages while using Spring MVC.

Spring MVC defines the View interface to render views to the client. The framework provides a number of implementations including JstlView, RedirectView, TilesView etc. In order to return JSON messages we implement the View interface to create a new class that returns data formatted using the JSON notation. We shall call this class JSONView.

The method that we need to implement is render(Map model, HttpServletRequest request, HttpServletResponse response). The render method accepts a Map as it's first parameter and produces the output. We could manually iterate through the Map, process and produce the JSON output. However, there is a Java library called JSON-lib that produces the JSON notation. The code below shows our JSONView class that can be used as a Spring MVC View to return JSON output to the client.

import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.View;
 
public class JSONView implements View {
    public void render(Map map, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
        JSONObject jsonObject = JSONObject.fromMap(map);
        PrintWriter writer = response.getWriter();
        writer.write(jsonObject.toString());
    }
 
    ...
}

As can be seen from the code above, Spring exploits MVC to it's full potential and provides the flexibility to tailor the view to exactly suit our needs.