1、为何使用 jsonhtml
json 数据格式在接口调用中、html页面中较经常使用,json数据结构简单,解析方便。 好比,webservice接口,传输json数据。前端
2、springmvc 中进行json交互java
1.请求的是json串、输出json串,在前端须要将请求的内容转换成json串,不太方便。
2.请求的是key/value、输出json串,此方法较经常使用。jquery
3、.配置json转换器web
注意:若是使用的是注解驱动标签,则不须要手动配置:ajax
<mvc:annotation-driven conversion-service="conversionService" validator="validator"/>
不然,须要在注解适配器中加入messageConverters。spring
<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>
4、json交互测试json
jsonTest.jsp数据结构
<html> <head> <title>json交互测试</title> <%-- 导入js外部文件 --%> <script language="JavaScript" src="${pageContext.request.contextPath}/js/jquery-1.4.4.min.js"></script> <%-- 自定义js函数--%> <script language="JavaScript"> function requestJson() { $.ajax({ type: 'post', url: '${pageContext.request.contextPath}/requestJson.action', contentType: 'application/json;charset=utf-8', data: '{"name":"手机","price":999}', success: function (data) { alert(data.name); } }); } function responseJson() { $.ajax({ type: 'post', url: '${pageContext.request.contextPath}/responseJson.action', data: 'name=手机&price=999', success: function (data) { alert(data.name); } }); } </script> </head> <body> <input type="button" onclick="requestJson()" value="请求json,输出json"/> <input type="button" onclick="responseJson()" value="请求key/value,输出json"/> </body> </html>
jsonTest.javamvc
@Controller public class JsonTest { //第一个@ResponseBody,将页面商品信息的json转成itemsCustom对象 //第二个@ResponseBody,把返回的itemsCustom对象转成json串输出。 @RequestMapping("requestJson") public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom) { return itemsCustom; } //输入是key/value ,输出是 json数据 @RequestMapping("responseJson") public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom) { return itemsCustom; } }
区别
**测试结果: **
1.使用jquery 的ajax 提交json串,对输出的json结果进行解析。
json 请求参数:
json 响应参数:
2.使用jquery 的ajax 提交key/value 串,对输出的json结果进行解析。
key/value 请求参数:
json 响应参数: