环境说明
- JDK 17
- SpringMVC 6.0.6
- Tomcat 10.0.12
环境准备
添加 SpringMVC 依赖和 Thymeleaf 依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
JSON数据格式
JSON 是一种轻量级的数据交换格式。它包括属性名和属性值,与JavaScript的对象极为相似,它到达前端后,可以直接转换为对象,以对象的形式进行操作和内容的读取,相当于以字符串形式表示了一个JS对象。
{"name": "杰哥", "age": 18}
[{"name": "杰哥", "age": 18}, {"name": "阿伟", "age": 18}]
{"studentList": [{"name": "杰哥", "age": 18}, {"name": "阿伟", "age": 18}], "count": 2}
let obj = JSON.parse('{"studentList": [{"name": "杰哥", "age": 18}, {"name": "阿伟", "age": 18}], "count": 2}')
// 将JSON格式字符串转换为JS对象
obj.studentList[0].name
// 将JS对象转换为JSON字符串
JSON.stringify(obj)
为了快速创建一个JSON格式的数据,可以使用fastjson:
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.34</version>
</dependency>
@RequestMapping("/index")
public String index(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("Bob", "111");
jsonObject.put("Alice", "2222");
System.out.println(jsonObject.toJSONString());
return "index";
}
实际上JSONObject就是对JSON数据的一种对象表示。同样的还有JSONArray,它表示一个数组,用法和List一样,数组中可以嵌套其他的JSONObject或是JSONArray:
@RequestMapping("/index")
public String index(){
System.out.println("处理ing...");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Bob", "111");
jsonObject.put("Alice", "2222");
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject);
System.out.println(jsonArray.toJSONString());
return "index";
}
实体类也可以通过JSON.toJSONString()方法转换为JSON 对象。
@RequestMapping(value = "/index", produces = "application/json")
@ResponseBody
public String data(){
Student student = new Student();
student.setName("杰哥");
student.setAge(18);
return JSON.toJSONString(student);
}
我们可以直接返回一个对象类型,它会被自动转换为JSON字符串格式:
@RequestMapping(value = "/data", produces = "application/json")
@ResponseBody
public Student data(){
Student student = new Student();
student.setName("杰哥");
student.setAge(18);
return student;
}
添加依赖:
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2-extension-spring6</artifactId>
<version>2.0.34</version>
</dependency>
在配置类中添加FastJSON转换器:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new FastJsonHttpMessageConverter());
}
重启服务器,访问页面时内容就会自动转换为JSON格式响应给客户端了。
Axios异步请求
前端异步请求指在前端中发送请求至服务器或其他资源,并且不阻塞用户界面或其他操作。在传统的同步请求中,当发送请求时,浏览器会等待服务器响应,期间用户无法进行其他操作。而异步请求通过将请求发送到后台,在等待响应的同时,允许用户继续进行其他操作。常见的前端异步请求方式包括使用XMLHttpRequest对象、Fetch API、使用jQuery库中的AJAX方法,以及目前最常用的Axios框架等。
向服务器端请求数据
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
</head>
<body>
<p>欢迎来到GayHub全球最大同性交友网站</p>
<p>用户名: <span id="username"></span></p>
<p>密码: <span id="password"></span></p>
</body>
</html>
js(使用axios框架直接对后端请求JSON数据):
<script>
function getInfo() {
axios.get('/mvc/test').then(({data}) => {
document.getElementById('username').innerText = data.username
document.getElementById('password').innerText = data.password
})
}
</script>
向服务器端发送数据
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
</head>
<body>
<p>欢迎来到GayHub全球最大同性交友网站</p>
<button onclick="login()">立即登录</button>
</body>
</html>
js:
<script>
function login() {
axios.post('/mvc/test', {
username: 'test',
password: '123456'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(({data}) => {
if(data.success) {
alert('登录成功')
} else {
alert('登录失败')
}
})
}
</script>
服务器端接收:
@ResponseBody
@PostMapping(value = "/test", produces = "application/json")
public String hello(String username, String password){
boolean success = "test".equals(user.getUsername()) && "123456".equals(user.getPassword());
JSONObject object = new JSONObject();
object.put("success", success);
return object.toString();
}