您的位置:首页 > 编程语言 > Java开发

SpringMvc处理json数据

2017-05-26 15:30 295 查看
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对象的相应的属性中

配置

如果使用了下面的这种简略的配置方式:

<mvc:annotation-driven conversion-service="conversionService" />


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

使用原始的配置

如果在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类型之间的转换,数据的验证
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: