Directory Structure:
introduction jquery file, try the version 2.0 or higher. You can download the official website, there is a demand can leave a message below.
<%--
Created by IntelliJ IDEA.
User: LFY
Date: 2020/2/6
Time: 21:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script>
//页面加载 绑定单机事件
$(function () {
$("#btn").click(function () {
// alert("Hello btn");
//发送ajax请求
$.ajax({
//编写json格式,设置属性和值
url:"user/testAjax",
contentType:"application/json;charset:UTF-8",
data:'{"username":"fy","password":"123","age":"20"}',
dataType:"json",
type:"POST",
success:function (data) {
//data服务器端响应的json的数据,进行解析
alert(data.username);
alert(data.password);
alert(data.age);
}
});
});
});
</script>
</head>
<body>
<!--响应式返回值是String-->
<a href="user/testString">testString</a><br/>
<!--响应式返回值是void-->
<a href="user/voidString">voidString</a><br/>
<!--响应式返回值是ModelAndView-->
<a href="user/testModelAndView">testModelAndView</a><br/>
<button id="btn">发送ajax的请求</button><br/>
</body>
</html>
We ajax request, JSON data server response parsing.
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
System.out.println("testAjax方法执行了....");
//客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
System.out.println(user);
//作响应,模拟查询数据库
user.setUsername("飞扬");
user.setAge(10);
return user;
}
@RequestBody passed through here, @ ResponseBody came
<!--前端控制器,那些静态资源不拦截-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
Because in web.xml we dispatcherServlet to intercept all requests, so we need to add in the configuration file configuration, not to intercept those static resources, css and images here, I have written.
<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>
If you want to convert to json data, you need to join jackson jar package.
Finally, we come to the effect that: