SpringMVC之ajax异步交互
Springmvc默认用MappingJackson2HttpMessageConverter对json数据进行转换,需要加入jackson的包;同时使用 <mvc:annotation-driven />
@RequestBody
该注解用于Controller的方法的形参声明,当使用ajax提交并指定contentType为json形式时,通过HttpMessageConverter接口转换为对应的POJO对象。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<script src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>
<%--ajax异步交互--%>
<button id="btn1">ajax异步提交</button>
<script>
$("#btn1").click(function () {
let url = '${pageContext.request.contextPath}/ajaxRequest';
let data = '[{"id":1,"username":"张三"},{"id":1,"username":"李四"}]';
$.ajax({
type:'POST',
url:url,
data:data,
contentType:'application/json;charset=utf-8',
success:function (resp) {
alert(JSON.stringify(resp));
}
})
})
</script>
@RequestMapping("/ajaxRequest")
public void ajaxRequest(@RequestBody List<User> list){
System.out.println(list);
}
<!--配置处理器映射器及处理器适配器-->
<!--此标签进行了功能增强:支持json的读写-->
<mvc:annotation-driven></mvc:annotation-driven>
@ResponseBody
该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端。
@RequestMapping("/ajaxRequest")
@ResponseBody
public List<User> ajaxRequest(@RequestBody List<User> list){
System.out.println(list);
return list;
}