业务缘由:json数据的特点(主要):快,小,所有语言都支持
实例场景:后台传给前端需要的数据→前端接受并使用数据
pom
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
json 是Google的产品所以别导错了
jsp(前端的处理)
<%--
Created by IntelliJ IDEA.
User: TianXinKun
Date: 2021/9/10
Time: 10:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>GsonTest</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script type="text/javascript">
function dian(){
var httpRequest = new XMLHttpRequest();
httpRequest.open("post","/json.do",true);
httpRequest.onload=function ()
{
var data = JSON.parse(httpRequest.responseText);
console.log(data)
document.getElementById("name").value=data.name;
document.getElementById("password").value=data.pssword;
document.getElementById("sex").value=data.sex;
document.getElementById("age").value=data.age;
document.getElementById("aihao").value=data.aihao;
}
httpRequest.send()
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12 text-center">姓名:
<input name="name" id="name" type="text"><br>
密码:
<input name="name" id="password" type="text"><br>
性别:
<input name="name" id="sex" type="text"><br>
年龄:
<input name="name" id="age" type="text"><br>
爱好:
<input name="name" id="aihao" type="text"><br>
<button class="btn btn-info" type="button" onclick="dian()">获取</button></div>
</div>
</div>
</body>
</html>
controller
@RequestMapping(value = "/json.do",method = RequestMethod.POST)
public void jsonTest(Writer out){
GsonUser user = new GsonUser();
user.setName("txk");
user.setPssword("123");
user.setAge("18");
user.setSex("nan");
user.setAihao("wu");
Gson gson = new Gson();
String s = gson.toJson(user);
try {
out.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
gson.toJson支持java所有的基本类型数据,可放心食用! 最终效果 ok!
|