详解SpringMVC @RequestBody接收Json对象字符串
作者:椰汁菠萝 时间:2022-03-20 05:00:10
页面提交请求参数有两种,一种是form格式提交,一种json格式提交
通常情况下我们使用的都是form格式提交的数据,数据格式:k=v&k=v,这个时候用springMVC接收参数没有问题,但有时候前端会通过json向后端传递数据,就会出现springMVC获取不到参数值的情况
注意:jQuery的$.post方法虽然也可以传递json格式数据,但实际上是用的form格式提交,jquery会帮你把json转成form格式提交后台
所以其实可以通过$.post,$.get来提交json格式,让jquery帮你转换,可是如果后端用restful,那就只能用以下方法解决
JavaScript 代码:
<script type="text/javascript">
$(document).ready(function(){
var saveDataAry=[];
var data1={"userName":"test","address":"gz"};
var data2={"userName":"ququ","address":"gr"};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
type:"PUT",
url:"/user",
dataType:"json",
contentType:"application/json;charset=utf-8",
data:JSON.stringify(saveData),
success:function(data){
}
});
});
</script>
后端springMVC接收
@RequestMapping(value = "user", method = RequestMethod.PUT )
@ResponseBody
public void saveUser(@RequestBody List<User> users) {
userService.batchSave(users);
}
注意:提交的data必须为json格式字符串,content-type为'application/json; charset=utf-8'表明提交的类型和编码格式,dataType是预期服务端返回的数据类型,其中对json字符串的格式有严格要求,形如:'{"type":"type","fileftppath":"fileftppath","map":{"id":1,"name":"suo"}}',字符串,key的双引号是必须的,否则400 bad request,当然如果你数据格式不正确,也会400,比如你传了个"step1",后端用Integer接收,也是400,直接从json对象转json串,这个json串格式是不会有问题的,如果400,只能是数据格式了
来源:http://blog.csdn.net/suo082407128/article/details/51436388
标签:requestbody,json
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android Handler消息机制分析
2023-10-01 13:22:26
![](https://img.aspxhome.com/file/2023/8/87268_0s.jpg)
Android WebView基础应用详解
2023-09-30 07:36:46
Spring如何基于注解配置使用ehcache
2022-08-16 03:24:32
SpringBoot 开发提速神器 Lombok+MybatisPlus+SwaggerUI
2022-07-08 07:40:23
![](https://img.aspxhome.com/file/2023/6/61516_0s.jpg)
java数据结构-堆实现优先队列
2023-11-25 08:30:20
![](https://img.aspxhome.com/file/2023/5/59335_0s.jpg)
Java使用HttpUtils实现发送HTTP请求
2021-06-11 07:08:39
![](https://img.aspxhome.com/file/2023/4/61034_0s.jpg)
java递归实现拼装多个api的结果操作方法
2023-11-24 23:44:35
kill命令在Java应用中使用的注意事项小结
2023-11-11 13:01:55
![](https://img.aspxhome.com/file/2023/9/58889_0s.jpg)
Idea中maven项目实现登录验证码功能
2023-11-29 16:50:51
![](https://img.aspxhome.com/file/2023/5/60575_0s.png)
springboot实现FastJson解析json数据的方法
2023-11-27 22:12:48
从try-with-resources到ThreadLocal,优化你的代码编写方式
2023-11-11 03:19:52
java处理数据库不支持的emoji表情符问题解决
2021-08-21 00:16:58
简单探索 Java 中的惰性计算
2023-11-16 20:25:28
ConcurrentHashMap是如何实现线程安全的你知道吗
2023-11-28 23:14:25
![](https://img.aspxhome.com/file/2023/5/60195_0s.jpg)
浅析java移位符的具体使用
2023-12-21 09:36:13
Android实现登录注册功能
2023-07-31 09:35:44
![](https://img.aspxhome.com/file/2023/1/84741_0s.jpg)
基于JavaMail的Java邮件发送
2022-10-30 18:56:56
![](https://img.aspxhome.com/file/2023/1/60931_0s.jpg)
老生常谈java中cookie的使用
2023-11-11 04:37:59
java导出数据库的全部表到excel
2023-11-25 09:38:33
IDEA解决maven包冲突easypoi NoClassDefFoundError的问题
2023-10-16 14:51:38
![](https://img.aspxhome.com/file/2023/2/61812_0s.png)