今天使用$.post()方法返回json字符串时,报错,一搜是因为$.post()是$.ajax()的post请求的简化版没有
contentType:'application/json'和后台数据格式对不上,行我该用了$.ajax()方法
$.ajax({
type: "post",
url: "${pageContext.request.contextPath}/add",
contentType:'application/json',
data: JSON.stringify(data.field),
dataType: "json",
success: function(data){
}
});
1.要在$.ajax中添加contentType:"application/json"可是后台还是没有显示值,行我再搜发现
springmvc中要使用@RequestBody来让实体类封装前端传来的json数据
行,我改,但一连串的报错蜂拥而至,好!!我挨个看发现要在@RequestMapping中加入
consumes = "application/json" 变成 @RequestMapping(value = "/add",consumes = "application/json")好吧,我学的不精,改遭。 结果测了一晚上,还报错!!!!!!
测了又测,搜了又搜,经历了一个多小时,四五十页的浏览,发现TM的要用
jackson 的jar包,我导入了 fastjson 的jar包,就没有管 jackson 的,气死个人,下面总结一下Springmvc接收前端传来的json数据时的问题
让前后台传递的编码一致
$.ajax({
type: "post",
url: "${pageContext.request.contextPath}/add",
contentType:'application/json',
data: JSON.stringify(data.field),
dataType: "json",
success: function(data){
}
});
2.在Controller中方法的参数上加@RequestBody
可以不加@RequestMapping(value = "/add",consumes = "application/json")中的consumes = "application/json"
@RequestMapping(value = "/add")
@ResponseBody
public String add(@RequestBody User user){
System.out.println(user);
return "ok";
}
3.最最最最最重要的是要看看配置文件和maven依赖配置好没有
jackson依赖
com.fasterxml.jackson.core
jackson-databind
2.9.8
com.fasterxml.jackson.core
jackson-core
2.9.8
com.fasterxml.jackson.core
jackson-annotations
2.9.8
我SSM框架的maven依赖
ssm框架烦烦烦烦,springbootYYDS
4.0.0
org.example
ssmbuild
pom
1.0-SNAPSHOT
school-01
school-02
school-03
school-04-system
8
8
com.fasterxml.jackson.core
jackson-databind
2.9.8
com.fasterxml.jackson.core
jackson-core
2.9.8
com.fasterxml.jackson.core
jackson-annotations
2.9.8
com.github.pagehelper
pagehelper
5.1.6
org.mybatis.generator
mybatis-generator-core
1.3.7
commons-fileupload
commons-fileupload
1.3.3
javax.servlet
javax.servlet-api
4.0.1
org.projectlombok
lombok
1.18.12
junit
junit
4.12
mysql
mysql-connector-java
5.1.47
com.mchange
c3p0
0.9.5.5
javax.servlet
servlet-api
2.5
javax.servlet.jsp
jsp-api
2.2
javax.servlet
jstl
1.2
org.mybatis
mybatis
3.5.2
org.mybatis
mybatis-spring
2.0.2
org.springframework
spring-webmvc
5.1.9.RELEASE
org.springframework
spring-jdbc
5.1.9.RELEASE
com.alibaba
fastjson
1.2.80
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.7
true
true
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)