@ResponseBody
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
导包:
除了一些spring的包之外,还需要jackson-annotations.jar , jackson-core.jar , jackson-databind.jar 这三个包
开启@ResponseBody注解---在MVC中配置转换器:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<!-- <ref bean="mappingJacksonHttpMessageConverter" />-->
</list>
</property>
</bean>
配置完就可以直接使用了:
@RequestMapping(value="/getStudentMistakesList", method = RequestMethod.GET)
@ResponseBody
public EduReturnJson getStudentMistakesList(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String,String> map = getParamMap(request);
List<Map<String, String>> mistakesList = eduStudentMistakesService.getStudentMistakesList(map);
if(mistakesList != null){
eduReturnJson = new EduReturnJson(1, "", mistakesList);
return eduReturnJson;
}else{
return new EduReturnJson(0, "", mistakesList);
}
}
这时返回数据已经转换为json格式:
{"ret":1,"msg":"","data":[{"num":"34","courseid":"12","coursename":"语文"},{"num":"0","courseid":"13","coursename":"数学"},{"num":"0","courseid":"14","coursename":"英语"}],"count":0}