SpringMvc处理json数据

SpringMvc提供了处理JSON格式请求响应的HttpMessageConverter接口,springmvc默认使用Jackson开源类包实现这个接口,即MappingJacksonHttpMessageConveter

在客户端以json格式的参数请求数据

在这里我么使用ajax请求

<script type="text/javascript">
    function jsonrequest(){
        $.ajax({
            type:"POST",
            url:"${pageContext.request.contextPath}/queryitemsUsejson.action",
            contentType:"application/json",
            /* 注意data的写法,不能是"{'id':1}" 
            throws java.lang.Exception]: org.springframework.http.converter.HttpMessageNotReadableException: 
            Could not read JSON: Unexpected character (''' (code 39)): was expecting double-quote to start field name*/
            data:'{"id":1}',
            dataType:"json",
            success:function(data){
                alert(data.name+"\t"+data.id+"\t"+data.detail)
            },
            error:function(){
                alert("未知错误")
            }
        })
    }
</script>

注意
type:”POST”
contentType:”application/json” 表示请求的参数是json格式的
dataType:”json” 表示服务端返回的数据是json格式的
data:’{“id”:1}’ 请求的参数,双引号必须在里面

服务端处理请求

@RequestMapping("/queryitemsUsejson")
    public @ResponseBody ItemsCustomer queryitemsUsejson(@RequestBody ItemsCustomer ic) throws Exception{
        ItemsCustomer itemsCustomer = itemsService.findItemsById(ic.getId());
        return itemsCustomer;
    }

springmvc会解析json中传递的数据,将对应的属性设置到ItemsCustomer对象的相应的属性中

配置

  1. 如果使用了下面的这种简略的配置方式:
<mvc:annotation-driven conversion-service="conversionService" />

那么这个其中已经默认为我们配置好了读写Json功能,使用Jackson实现

  1. 使用原始的配置
    如果在springweb的容器中显示定义了一个RequestMappingHandlerAdapter(像下面这样的),那么springMvc的RequestMappingHandlerAdapter默认装配的HttpMessageConverter将不再起作用,需要自己手动装配
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!-- 配置json解析器 -->
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
            </list>
        </property>
    </bean>

为什么配置在处理器适配器中:
因为在执行handler之前是通过HandlerAdapter将请求的参数转换为相应的形参的属性值的,这里面涉及到json数据的转换,java类型之间的转换,数据的验证

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值