0
点赞
收藏
分享

微信扫一扫

json数据交互与@RequestBody


@RequestBody

@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。传统的请求参数:
itemEdit.action?id=1&name=zhangsan&age=12
现在的请求参数:
使用POST请求,在请求体里面加入json数据
 

{
"id": 1,
"name": "测试商品",
"price": 99.9,
"detail": "测试商品描述",
"pic": "123456.jpg"
}

请求json,响应json实现

1.加入jar包

2.编写action

//json数据交互
@RequestMapping(value = "/json.action")
public @ResponseBody
Items json(@RequestBody Items items){

return items;
}

3.编写model

public class Items {
private Integer id;

private String name;

private Float price;

private String pic;

private Date createtime;

private String detail;


省略get set方法

3.编写jsp

这里不加触发事件,直接页面加载完就出发,接受到json数据后也不处理,直接返回。

<script type="text/javascript">
$(function(){
var params = '{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';
$.ajax({
url : "${pageContext.request.contextPath }/json.action",
data : params,
contentType : "application/json;charset=UTF-8",//发送数据的格式
type : "post",
dataType : "json",//回调
success : function(data){
alert("获取到的数据的name为:"+data.name);
}

});
});
</script>

4.配置json转换器

如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器。

在springmvc.xml配置文件中,给处理器适配器加入json转换器:

<!--处理器适配器 -->
<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>

成功后回调,将传回来的数据赋给形参data,此时data可以直接调用model 的属性。

完成最简单的前后端数据交互。

 

json数据交互与@RequestBody_json数据

举报

相关推荐

0 条评论