今天使用$.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依赖
我SSM框架的maven依赖com.fasterxml.jackson.core jackson-databind2.9.8 com.fasterxml.jackson.core jackson-core2.9.8 com.fasterxml.jackson.core jackson-annotations2.9.8
ssm框架烦烦烦烦,springbootYYDS
4.0.0 org.example ssmbuildpom 1.0-SNAPSHOT school-01 school-02 school-03 school-04-system 8 8 com.fasterxml.jackson.core jackson-databind2.9.8 com.fasterxml.jackson.core jackson-core2.9.8 com.fasterxml.jackson.core jackson-annotations2.9.8 com.github.pagehelper pagehelper5.1.6 org.mybatis.generator mybatis-generator-core1.3.7 commons-fileupload commons-fileupload1.3.3 javax.servlet javax.servlet-api4.0.1 org.projectlombok lombok1.18.12 junit junit4.12 mysql mysql-connector-java5.1.47 com.mchange c3p00.9.5.5 javax.servlet servlet-api2.5 javax.servlet.jsp jsp-api2.2 javax.servlet jstl1.2 org.mybatis mybatis3.5.2 org.mybatis mybatis-spring2.0.2 org.springframework spring-webmvc5.1.9.RELEASE org.springframework spring-jdbc5.1.9.RELEASE com.alibaba fastjson1.2.80 src/main/java ***.xml false src/main/resources ***.xml false org.mybatis.generator mybatis-generator-maven-plugin1.3.7 true true



