后台通过GSON格式数据传入前端以及前端的接收

业务缘由: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!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值