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