1五、SpringMVC进行json交互

SpringMVC进行json交互

json数据格式在接口调用中、html页面中较经常使用,json格式比较简单,解析还比较方便。html

  • 请求json、输出json。要求请求的是json串,前端页面中须要将请求的内容转成json,不太方便。
  • 请求key/value、输出json。此方法比较经常使用。

环境准备

添加json转换的依赖

<!-- json 转换-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.2</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

查看依赖树前端

[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.2:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.7.2:compile
[INFO] \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO]    \- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile

配置json转换器

在注解适配器中加入messageConvertersjava

<!--注解适配器 -->
<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>

注意:若是使用<mvc:annotation-driven/>则不用定义上边的内容。jquery

输入json串,输出是json串

使用jquery的ajax提交json串,对输出的json结果进行解析。web

  • jsp页面
//请求json,输出是json
function requestJson(){
    $.ajax({
        type:'post',
        url:'${pageContext.request.contextPath }/requestJson.action',
        contentType:'application/json;charset=utf-8',
        //数据格式是json串,商品信息
        data:'{"name":"手机","price":999}',
        //返回json结果
        success:function(data){
            alert(data);
        }
    });
}
  • controller
@RequestMapping("/requestJson")
public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){
    return itemsCustom;
}
  • @RequestBody将请求的商品信息的json串转成itemsCustom对象
  • @ResponseBody将itemsCustom转成json输出

输入key/value,输出是json串

使用jquery的ajax提交key/value串,对输出的json结果进行解析ajax

  • jsp页面
//请求key/value,输出是json
function responseJson(){
    $.ajax({
        type:'post',
        url:'${pageContext.request.contextPath }/responseJson.action',
        //请求是key/value这里不须要指定contentType,由于默认就 是key/value类型
        //contentType:'application/json;charset=utf-8',
        //数据格式是json串,商品信息
        data:'name=手机&price=999',
        //返回json结果
        success:function(data){
            alert(data.name);
        }
    });
}
  • controller
@RequestMapping("/responseJson")
public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){
    return itemsCustom;
}
相关文章
相关标签/搜索