pom.xml 引入依赖包
< dependency>
< groupId> com. fasterxml. jackson. core< / groupId>
< artifactId> jackson- databind< / artifactId>
< version> 2.9 .0 < / version>
< / dependency>
< dependency>
< groupId> com. fasterxml. jackson. core< / groupId>
< artifactId> jackson- core< / artifactId>
< version> 2.9 .0 < / version>
< / dependency>
< dependency>
< groupId> com. fasterxml. jackson. core< / groupId>
< artifactId> jackson- annotations< / artifactId>
< version> 2.9 .0 < / version>
< / dependency>
User实体类
private String username;
private String password;
private Integer age;
jQuery ajax请求函数 发送post请求
function ajax ( ) {
$. ajax ( {
url: "user/testAjax" ,
contentType: "application/json;charset=UTF-8" ,
data: '{"username":"hehe","password":"123","age":20}' ,
dataType: "json" ,
type: "post" ,
success: function ( data) {
console. log ( data)
}
} )
}
@Controller类
@RequestMapping ( value = "/testAjax" )
public @ResponseBody User testAjax ( @RequestBody User user) {
System. out. println ( user) ;
return user;
}
post发送请求的请求体为json对象,json对象的内容为实体类的属性,实体类属性值和请求的json对象里面的值是相同的,然后通过springmvc自动将请求的json转换成了实体类对象
data: '{"username":"hehe","password":"123","age":20}'
public class User implements Serializable {
private String username;
private String password;
private Integer age;
get. . . set. . .
}
注意:要从json转换到的实体类要实现Serializable接口