实现标题这个议题,首先我们需要加入2个包,
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.5.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.5.6</version> </dependency>
其次保证spring支持annotation,这里就不写配置了。
看controller:
@RequestMapping(value="/content-type/{prodId}") @ResponseBody public Map<String,List<ContentType>> listContentTypeByProdJSONFormat(HttpServletRequest request,@PathVariable("prodId") int prodId) { List<ContentType> contentTypeList = contentTypeService.listContentTypeByProduct(prodId); Map<String,List<ContentType>> contentTypes = new HashMap<String,List<ContentType>>(); contentTypes.put("contentTypes", contentTypeList); return contentTypes; }
@ResponseBody注解就是要求这个controller以text文本形式返回,这里绑定一个Map类型,实际返回的就是个json对象,格式就是map转json的格式。这样在ajax调用的时候回调函数可以这样拿:
success:function(data) { var typeList = data.contentTypes; var length = typeList.length; .... .... .... });
这的contentTypes必须和后台controller绑定的Map的key保证一致,这个不用解释了吧。