Monthly Archives: October 2011

Want to serve JSON from one of your spring-mvc controller ?

Want to serve JSON from one of your spring-mvc controller ?
This is how to do it in 3 steps!
1- Download Jackson JSON processor here:http://jackson.codehaus.org/
If you”re using maven, add this dependency to you pom.xml :


<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.8.5</version>
</dependency>

Be sure jackson is in your classpath.
2- Add the mvc context and the mvc:annotation-driven in your servlet configuration file (in my case : dispatcher-servlet.xml) :


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- To serve JSON -->
<mvc:annotation-driven/>
<context:annotation-config />
<!-- Scan for controller -->
<context:component-scan base-package="net.nakama.example.controller"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

3- Write a simple controller. This controller must contain a method with a proper @RequestMapping tag. This method must return the object your want to “serialize” as JSON and must contain the tag @RequestBody :


package net.nakama.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import net.nakama.example.datamodel.Foo;
@Controller
public class JsonExampleController {
@RequestMapping(value = "/getfoo/{name}")
public @ResponseBody Foo getFoo(@PathVariable String name) {
Foo foo = new Foo();
foo.setBar(name);
return foo;
}
}

Enjoy!!!
Resources:
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
http://wiki.fasterxml.com/JacksonDocumentation