I am trying to figure out how I will manage to return a JSON output from a Controller. For the time being, I am returning my results and getting them with the use of freemarker view resolver. The code inside my controller is the following:
@RequestMapping(value = "query", method = RequestMethod.GET)
public ModelAndView search(
@RequestParam(required = true) String q
){
ModelAndView mv = new ModelAndView(getPartial("template"));
mv.addObject("terms",q.replace(","," "));
mv.addObject("results",getResultsForQuery(q));
return mv;
}
and the configuration for the freemarker:
<!-- freemarker config -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/freemarker/"/>
<property name="freemarkerSettings">
<props>
<prop key="locale">en_US</prop>
</props>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="order" value="1"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="cache" value="false"/>
<property name="suffix" value=".ftl"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
As far as I have understood so far, there are two ways of returning a JSON object, a)by modifying the controller and b)without modifying it by changing the configuration. Moreover, I have read about returning JSON throuh ResponseBody but not sure what should I change to configuration. Could anyone first of all, verify whether the above conclusions are valid or not, and second help me returning JSON from this GET method?
*UPDATE** If I use ResponseBody and configuration like this:
<!-- json config -->
<bean id="viewName" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
should I remove the freemarker confiuration?
Thank you in advance for your help.