Spring MVC JSON response with @ResponseBody annotation
January 25, 2012 16:07:29 Last update: January 25, 2012 16:07:29
A JSON response is auto-magically returned when you add the
For magic to happen, you must:
@ResponseBody annotation to the return value of a @RequestMapping annotated method:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MyController { @RequestMapping(value="/the/request/path", method={RequestNethod.POST}) public @ResponseBody Object processFormSubmit(HttpServletRequest request) { return new String[] { "one", "two", "three" }; } }
For magic to happen, you must:
- Add
annotation-drivento theorg.springframework.web.servlet.DispatcherServletconfig xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <mvc:annotation-driven /> <beans>
- Put Jackson jar files on
CLASSPATH(i.e., underWEB-INF/lib), which includesjackson-core-asl-1.6.4.jarandjackson-mapper-asl-1.6.4.jar.