spring3 controller 使用json format返回数据
实现标题这个议题,首先我们需要加入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保证一致,这个不用解释了吧。
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30