.Net转Java自学之路—SpringMVC框架篇七(Json数据交互)

SpringMVC进行Json交互:

  客户端发送请求。若该请求K/V串是Json串时,这时会经过controller的参数绑定,进行Json数据的转换,转换时,在SpringMVC中,通过注解@RequestBody将Json串转成Java对象。@ResponseBody将Java对象转成Json串输出。若该请求只是K/V,而不是Json串,则只是用@ResponseBody将Java对象转成Json串输出。最终都输出Json数据,为了在前端页面方便对请求结果进行解析。

请求Json、响应Json实现:

  SpringMVC默认使用MappingJacksonHttpMessageConverter对Json数据进行转换(@RequestBody和ResponseBody),需要加入jackson包。

  配置Json转换器,在注解适配器中加入messageConverters。

<!-- 注解适配器
    注:若使用注解驱动标签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:

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

$.ajax({
    type:"post",
    url:"${pageContext.request.contextPath }/requestJson.action",
    contentType:"application/json;charset=utf-8",
    data:{}
    success:function(){
    
    },
    error:function(){
        
    }
});

  输入key/value,输出Json:

$.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;
    }
}
原文地址:https://www.cnblogs.com/zltao/p/10665870.html