SpringBoot利用@RequestBody注解以对象的形式进行接收 ajax提交的对象
1、前端ajax写法:
function toBack(){
var student = {
"name":1,
"age":2,
"score":3
};
$.ajax({
url:"/wms/queryStock/test",
contentType:"application/json;charset=UTF-8",
type:'POST',
dataType:'json',//json 返回值类型
data: JSON.stringify(student),//转化为json字符串
success:function(data){
},
error:function(){
});
}
2、后端springboot写法:
controller层的代码如下:
@RequestMapping(value = "/test",method = RequestMethod.POST)
public void deleteByPrimaryKey(@RequestBody Student student){
System.out.println(student);
}
其中再创建一个pojo,名字叫:Student.java,代码如下:
public class Student {
private String name;
private int age;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
3、pom.xml需要引入jackson-databind,否则无法解析成对象,并报错。pom.xml中加入如下:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>