1.导入坐标
<properties>
```
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<!--jason包-->
<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>
<!--jason包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
2.在一个按钮上或者form表单上提交ajax请求
需要jQuery
$(function () {
$("#btnAjax").click(function () {
$.ajax({
url: "view/testAjaxAndJason",
data: JSON.stringify({
"name": "zs",
"age": 18
}),
type: "post",
dataType: 'json',
contentType: 'application/json',
success: function (res) {
console.log(res);
}
})
});
});
3.SpringMVC中逻辑处理
/** * ajax请求必须是post请求,使用Jason包,自动把数据打入实体类 * @param user */
@RequestMapping("/testAjaxAndJason")
public @ResponseBody User testAjaxAndJason(@RequestBody User user){
System.out.println(user);
/*返回值写入直接@ResponseBody,让MVC自动把user对象返回成json数据*/
return user;
}