Spring MVC无法正确接收From表单参数的解决方案
问题描述
先看有问题的代码:
controller:
@ResponseBody
@PostMapping(value = "/addUser")
public String addUser(@RequestBody AdminPersonVo adminPersonVo) {
return "success";
}
js:
$(form).ajaxSubmit({
url:"/addUser",
type:"POST",
contentType: 'application/json;charset=utf-8',
filtering: function(el, index) {
if ( !$(el).hasClass('ignore') ) {
return el;
}
},
success: function (data) {
alert(data);
}
});
表单提交报错如下:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN
错误信息大概意思是: jackson 无法正确解析 json 。
开始踏上寻找解决之路……
看完上面代码能看出问题所在的话可以不用往下面看了
知识要点
要点一
ajax请求中的 contentType: ‘application/json;charset=utf-8’ 如果不加的话,会报如下错误:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
表达意思也很清晰,默认的请求参数类型是: application/x-www-form-urlencoded;charset=UTF-8,而现在的代码不支持这种类型的参数请求。
要点二
聚焦 @RequestBody 这个注解。
@RequestBody 注解常用来处理 content-type 不是默认的 application/x-www-form-urlencoded 编码的内容,比如说:application/json 或者是 application/xml 等。
这就是为什么代码不支持 application/x-www-form-urlencoded 的原因。
解决办法
将 controller 中的 @RequestBody 去掉,将 JS 中的 contentType: ‘application/json;charset=utf-8’ 去掉,就能正常接收参数了
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
解决IDEA报错Caused by: org.springframework.boot.web.se
遇到IDEA启动报错,可尝试以下方法:打开项目设置(Ctrl+Shift+Alt+S),将JDK版本修改为1.8;或者检查TomCat依赖,若有问题可尝试删除,此外,确保每次拉取项目后,maven地址设置为本地,并且JDK版本设置为1.8,以上为个人解决经验,希望对大家有所帮助2024-09-09
SpringBoot2.7 WebSecurityConfigurerAdapter类过期配置
这篇文章主要为大家介绍了SpringBoot2.7中WebSecurityConfigurerAdapter类过期应该如何配置,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-06-06


最新评论