Tuesday, March 31, 2009

An Annotated AJAX (via JSON) Spring Controller

Because I could not find an example of an annotated Spring AJAX (via JSON) controller in Google, I forged ahead and figured this one out on my own. I thought I would share this code snippet with the blogosphere. Without further ceremony here is the code example:

public class AjaxController {
public void handler(@RequestParam("myParam") Object myParam,
HttpServletResponse response) {
JSONObject json = new JSONObject();
response.setHeader("Cache-Control", "no-cache");

The URL request mapping is specified with the RequestMapping annotation. Make sure the path is accessible by properly configuring with web.xml with the correct servlet-mapping. Note that the annotated Spring controller offers tremendous flexibility with respect to the method signature. We can leverage this feature for building the AJAX request handler method. Moreover, you can specify the required URL parameters via the RequestParam annotation and bind them to the method arguments. Lastly, you will need the HttpServletResponse object for the JSON response. Notice that the method returns void because the JSON response is returned via the response object.

The JSON library I used can be found here.

Handle the JSON in the browser with your favorite JavaScript library (e.g. YUI).


Sam Brodkin said...

Excellent thanks! This is exactly what I needed.

armyofda12mnkeys said...

How would you do this with many params being passed in?

like @RequestParam("year")
and @RequestParam("month") etc.