I'm trying to send a JSON representation of a Map into my controller as a POST parameter.
@RequestMapping(value = "/search.do", method = RequestMethod.GET, consumes = { "application/json" })
public @ResponseBody Results search(@RequestParam("filters") HashMap<String,String> filters, HttpServletRequest request) {
//do stuff
}
I found that @RequestParam would just throw a 500 error, so I tried using @ModelAttribute instead.
@RequestMapping(value = "/search.do", method = RequestMethod.GET, consumes = { "application/json" })
public @ResponseBody Results search(@ModelAttribute("filters") HashMap<String,String> filters, HttpServletRequest request) {
//do stuff
}
This would correctly respond to requests, but I realized that the Map was empty. With later experimentation, I found that any object (not just HashMap) would be instantiated, but no fields would be filled in. I do have Jackson on my classpath, and my controllers will respond with JSON. However, it would appear that my current configuration is not allowing Spring to read JSON in via a GET/POST parameter.
How does one pass JSON representations of objects from a client-side AJAX request to a Spring controller as a request parameter and get a Java object out?
EDIT Adding my relevant Spring configuration
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean 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>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="true" />
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
On the suggestion of a commenter, I tried @RequestBody. This will work, so long as the JSON strings are quoted with double quotes.
@RequestMapping(value = "/search.do", method = RequestMethod.POST, consumes = { "application/json" })
public @ResponseBody Results<T> search(@RequestBody HashMap<String,String> filters, HttpServletRequest request) {
//do stuff
}
This does solve my immediate issue, but I'm still curious as to how ou might pass in multiple JSON objects via an AJAX call.