SpringMVC进行Json交互:前端
客户端发送请求。若该请求K/V串是Json串时,这时会通过controller的参数绑定,进行Json数据的转换,转换时,在SpringMVC中,经过注解@RequestBody将Json串转成Java对象。@ResponseBody将Java对象转成Json串输出。若该请求只是K/V,而不是Json串,则只是用@ResponseBody将Java对象转成Json串输出。最终都输出Json数据,为了在前端页面方便对请求结果进行解析。web
请求Json、响应Json实现:ajax
SpringMVC默认使用MappingJacksonHttpMessageConverter对Json数据进行转换(@RequestBody和ResponseBody),须要加入jackson包。spring
配置Json转换器,在注解适配器中加入messageConverters。json
<!-- 注解适配器 注:若使用注解驱动标签mvc:annotation-driven则不用定义该内容 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>
输入Json,输出Json:mvc
使用Jquery的ajax提交json串,对输出的json结果进行解析。app
$.ajax({ type:"post", url:"${pageContext.request.contextPath }/requestJson.action", contentType:"application/json;charset=utf-8", data:{} success:function(){ }, error:function(){ } });
输入key/value,输出Json:post
$.ajax({ type:"post", url:"${pageContext.request.contextPath }/responseJson.action?key=value", success:function(){ }, error:function(){ } });
@Controller public class GoodsJsonTest{ //@RequestBody GoodsCustom goodsCustom将请求的data中输入的Json串转成Java对象GoodsCustom //@ResponseBody GoodsCustom将Java对象转Json @RequestMapping("/requestJson")//指定页面 public @ResponseBody GoodsCustom requestJson(@RequestBody GoodsCustom goodsCustom){ return goodsCustom; } @RequestMapping("/responseJson") public @ResponseBody GoodsCustom requestJson(GoodsCustom goodsCustom){ return goodsCustom; } }