json是一种数据传输的数据格式,之前有xml文件传输数据,解析文件比较麻烦,使用json格式数据更简便。
json格式的数据:
基本的json格式数据:
{
"name":"鲁班",
"age":20
}
较为复杂的:
{
"name":"鲁班",
"age":20,
"hobbies":["读书","运动"]// []代表数组
}
对象的集合:
[
{
"name":"鲁班",
"age":20
},
{
"name":"妲己",
"age":20
}
]
MVC处理json有两种方式:
- 使用response返回json格式数据
- 使用第三方json依赖包
使用response返回json格式数据
1.在jsp目录下新建json.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<button onclick="getUser()">点击</button><br>
姓名:<span id="username"></span><br>
年龄:<span id="age"></span>
</body>
</html>
<script>
function getUser(){
// 使用原生的异步请求
let xmlHttpRequest = new XMLHttpRequest();
// 打开要请求的url地址
xmlHttpRequest.open("get", "http://localhost:8080${pageContext.request.contextPath}/json/getUser");
// 发生请求
xmlHttpRequest.send();
// 处理响应结果,当请求状态发生变化时触发响应的处理
xmlHttpRequest.onreadystatechange = function (){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
// 将返回的数据转为json对象
let userStr = xmlHttpRequest.responseText;
let user = JSON.parse(userStr);
// 解析完对象之后,将对象属性拼接到相应的位置
let username = document.getElementById("username");
username.append(user.name);
let age = document.getElementById("age");
age.append(user.age);
}
}
}
</script>
2.创建JsonController
@Controller
@RequestMapping("/json")
public class JsonController {
@GetMapping("/getJson")
public void getJson(HttpServletResponse response) throws IOException {
String json = "{\"name\":\"鲁班\",\"age\":20}";// {"name":"鲁班","age":20}
OutputStream outputStream = response.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
}
}
3.部署运行,访问/jsp/json.jsp页面
MVC示使用第三方json依赖处理
1.在pom文件中加入第三方依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
2.修改spring配置文件
<mvc:annotation-driven validator="validatorFactoryBean">
<!--配置处理json数据的消息转换器-->
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 必须按照此顺序进行配置 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3.在UserController中添加以下方法
/**
* @ResponseBody用于告诉mvc将对象以json格式数据返回页面
* @return
*/
@GetMapping("/query")
@ResponseBody
public User query(){
User user = new User();
user.setUsername("韩信");
user.setPassword("123");
List<String> hobbies = new ArrayList<>();
hobbies.add("吃饭");
hobbies.add("睡觉");
hobbies.add("打鲁班");
user.setHobbies(hobbies);
user.setBirthday(new Date());
user.setTime(new Date());
return user;
}
4.在webapp的jsp目录下新建user目录,在user目录下新建userinfo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>用户个人信息</h1>
<button onclick="getUser()">查询个人信息</button><br>
姓名:<span id="username"></span><br>
密码:<span id="password"></span><br>
爱好:<span id="hobbies"></span><br>
出生日期:<span id="birthday"></span><br>
注册日期:<span id="time"></span><br>
</body>
</html>
<script>
function getUser(){
// 使用原生的异步请求
let xmlHttpRequest = new XMLHttpRequest();
// 打开要请求的url地址
xmlHttpRequest.open("get", "http://localhost:8080${pageContext.request.contextPath}/user/query");
// 发生请求
xmlHttpRequest.send();
// 处理响应结果,当请求状态发生变化时触发响应的处理
xmlHttpRequest.onreadystatechange = function (){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
// 将返回的数据转为json对象
let userStr = xmlHttpRequest.responseText;
let user = JSON.parse(userStr);
// 解析完对象之后,将对象属性拼接到相应的位置
for(let item in user){
console.log(user);
// 在控制台打印出属性名和属性值
console.log(item + " === " + user[item]);
let biaoqianSpan = document.getElementById("" + item);
biaoqianSpan.append(user[item]);
}
}
}
}
</script>
5.部署运行,访问/jsp/user/userinfo.jsp,点击看结果
如果要处理日期字段,那就修改User实体类
@JSONField(format = "yyyy/MM/dd")
private Date birthday;
@JSONField(format = "yyyy/MM/dd")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date time;
在日期字段之前加上@JSONField注解,配置日期要转换的格式
前端提交json格式数据给后端
1.在jsp目录下新建json2.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<button onclick="login()">点击</button><br>
结果:<span id="result"></span>
</body>
</html>
<script>
function login(){
let xmlHttpRequest = new XMLHttpRequest();
// 提交数据一定得用post方式
xmlHttpRequest.open("post", "http://localhost:8080${pageContext.request.contextPath}/user/login");
// 设置请求头,要是有json格式进行数据传递
xmlHttpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// 创建json对象
let user = {
"username":"libai",
"password":"123456",
"hobbies":["吃饭","睡觉","打鲁班"],
"time":"2022-11-29 14:22:30"
}
// 发生要提交的数据
xmlHttpRequest.send(JSON.stringify(user));
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
// 将返回的数据转为json对象
let resultStr = xmlHttpRequest.responseText;
let result = JSON.parse(resultStr);
// 解析完对象之后,将对象属性拼接到相应的位置
document.getElementById("result").append(result.msg);
}
}
}
</script>
2.在UserController中添加以下内容
@PostMapping("/login")
@ResponseBody
public HashMap<String, String> login(@RequestBody User user){
HashMap<String, String> result = new HashMap<>();
System.out.println(user.toString());
if("libai".equals(user.getUsername()) && "123456".equals(user.getPassword())){
result.put("msg","登录成功");
}else{
result.put("msg", "登录失败");
}
return result;
}
3.部署运行,访问/jsp/json2.jsp,点击看结果
4.将以上页面提交数据修改为动态数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form>
username:<input type="text" id="username"/><br>
password:<input type="password" id="password"/><br>
hobbies:<input type="checkbox" name="hobbies" value="读书"/>读书
<input type="checkbox" name="hobbies" value="运动"/>运动
<input type="checkbox" name="hobbies" value="听音乐"/>听音乐<br>
time:<input type="datetime-local" id="time" step="01"/><br>
</form>
<button onclick="login()">点击</button><br>
结果:<span id="result"></span>
</body>
</html>
<script>
function login(){
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("post", "http://localhost:8080${pageContext.request.contextPath}/user/login");
xmlHttpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// 获取表单中填写的数据
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let time = document.getElementById("time").value;
time = time.replaceAll("T", " ");
let aihaos = document.getElementsByName("hobbies");
// 创建数组保存勾选的数据
let hobbies = new Array();
for(let i = 0; i < aihaos.length; i++){
// 获取用户勾选的数据
if(aihaos[i].checked){
hobbies.push(aihaos[i].value);
}
}
// 将从表单中获取的数据赋值给对象属性
let user = {
"username":username,
"password":password,
"hobbies":hobbies,
"time":time
}
xmlHttpRequest.send(JSON.stringify(user));
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
// 将返回的数据转为json对象
let resultStr = xmlHttpRequest.responseText;
let result = JSON.parse(resultStr);
// 解析完对象之后,将对象属性拼接到相应的位置
// document.getElementById("result").append(result.msg);
document.getElementById("result").innerText = result.msg;
}
}
}
</script>