Spring MVC JSON response with @ResponseBody annotation 

Joined:
01/02/2012
Posts:
9

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 @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:
  1. Add annotation-driven to the org.springframework.web.servlet.DispatcherServlet config 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>
    

  2. Put Jackson jar files on CLASSPATH (i.e., under WEB-INF/lib), which includes jackson-core-asl-1.6.4.jar and jackson-mapper-asl-1.6.4.jar.
Share |
| Comment  | Tags