Java web 2022跟学尚硅谷(十一) Vue基础和Axios基础和json基础

Vue

在js中定义对象的2种方式

方式一

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <!--<script type="" language="JavaScript" src="script/vue.js">-->
    <script type="" language="JavaScript">
        function hello() {
            person.sayHello();
        }

         var person = new Object();
         person.pid = "p01";
         person.pname = "Jim";
         person.sayHello = function () {
             alert("Hello " + person.pid + person.pname);
         }


        window.onload = function () {
            var vue = new Vue({});
        }
    </script>
</head>
<body>
<div id="div0">
    <span>Hello</span>
    <input type="button" value="打招呼" onclick="hello()"></input>
</div>

</body>
</html>

方式二

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <!--<script type="" language="JavaScript" src="script/vue.js">-->
    <script type="" language="JavaScript">
        function hello() {
            person.sayHello();
        }

        var person = {
            "pid": "p001",
            "pname": "Tonny",
            sayHello: function () {
                alert("Hello " + person.pid + person.pname);
            }

        }
        window.onload = function () {
            var vue = new Vue({});
        }
    </script>
</head>
<body>
<div id="div0">
    <span>Hello</span>
    <input type="button" value="打招呼" onclick="hello()"></input>
</div>

</body>
</html>

输出结果
输出结果

简单的Vue代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    msg: "hello Rose"
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span>
</div>

</body>
</html>

绑定元素的属性

方式一 v-bind:value

代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    msg: "hello Rose",
                    uname: "张三丰"
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span>
    <input type="text" v-bind:value="uname"></input>
</div>

</body>
</html>

效果:
绑定元素的属性

方式二 :value

代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    msg: "hello Rose",
                    uname: "小龙女"
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span>
    <input type="text" :value="uname"></input>
</div>

</body>
</html>

显示
显示

双向数据绑定 v-model:

方式一

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    msg: "hello Rose"
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span><br/>
    <!-- v-model:双向绑定
        也就是说v-bind:是单向绑定,是通过msg这个变量的值来控制input输入框
        现在v-model:不仅msg来控制input输入框,反过来input输入框也会改变msg的值
     -->
    <input type="text" v-model:value="msg"></input>
</div>

</body>
</html>

输出结果:
input里面更改值,span里面也会改变
input里面更改值,span里面也会改变

方式二 :value可以省略,trim去除首尾空格

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    msg: "hello Rose"
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span><br/>
    <!-- v-model:双向绑定
        也就是说v-bind:是单向绑定,是通过msg这个变量的值来控制input输入框
        现在v-model:不仅msg来控制input输入框,反过来input输入框也会改变msg的值
     -->
    <input type="text" v-model.trim="msg"></input>
</div>

</body>
</html>

效果
效果

条件渲染 v-if

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    num: 2
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <input type="text" v-model="num"></input>
    <div v-if="num%2==0" style="width: 200px;height: 200px;background-color: aqua;">&nbsp;</div>
</div>

</body>
</html>

效果1:输入被2整除的数时
效果
效果2:输入不能被2整除的数时
效果2

条件渲染 v-else

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    num: 2
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <input type="text" v-model="num"></input>
    <div v-if="num%2==0" style="width: 200px;height: 200px;background-color: aqua;">&nbsp;</div>
    <div v-else="num%2==0" style="width: 200px;height: 200px;background-color: crimson;">&nbsp;</div>
</div>

</body>
</html>

输入奇数的时候
输入偶数的时候

条件渲染 特别注意

特别注意 v-if和 v-else中间不能有其它结点或者元素,否则失效

条件渲染 v-show

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    num: 2
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <input type="text" v-model="num"></input>
    <div v-show="num%2==0" style="width: 200px;height: 200px;background-color: lime;">&nbsp;</div>

</div>

</body>
</html>

显示效果1:
当被2整除的时候,显示方框
效果1
显示效果2:
当不被2整除的时候,不显示方框,源代码增加了一个属性
显示效果2

v-show和v-if、v-else的区别

v-show通过属性display控制标签是否展示,v-if直接将不满足条件的标签移除。
即v-show标签还在,只是不展示,而v-if和v-else不展示的话,标签也不在了。

列表渲染 v-for迭代

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {
                    fruitList: [
                        {fname: "苹果", price: 6, fcount: 30, remark: "青苹果乐园"},
                        {fname: "香梨", price: 7, fcount: 20, remark: "库尔勒香梨"},
                        {fname: "菠萝", price: 8, fcount: 10, remark: "海南大菠萝"},
                        {fname: "荔枝", price: 9, fcount: 40, remark: "深圳妃子笑"}
                    ]
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <table border="1" width="400" cellpadding="4" cellspacing="0">
        <tr>
            <th>名称</th>
            <th>单价</th>
            <th>库存</th>
            <th>备注</th>
        </tr>
        <tr align="center" v-for="fruit in fruitList">
            <td> {{fruit.fname}}</td>
            <td> {{fruit.price}}</td>
            <td> {{fruit.fcount}}</td>
            <td> {{fruit.remark}}</td>
        </tr>
    </table>
</div>
</body>
</html>

显示结果
显示结果

事件驱动

方式一 v-on:click

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {msg: "helloworld"},
                methods: {
                    myReverse: function () {
                        this.msg = this.msg.split("").reverse().join("");
                    }
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span><br/>
    <input type="button" value="反转" v-on:click="myReverse"></input>
</div>
</body>
</html>

显示结果
点击结果1
点击结果2

方式二 @click

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                // # 表示id
                // . 表示class
                "el": "#div0",
                "data": {msg: "hello Tony"},
                methods: {
                    myReverse: function () {
                        this.msg = this.msg.split("").reverse().join("");
                    }
                }
            });
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span><br/>
    <!--<input type="button" value="反转" v-on:click="myReverse"></input>-->
    <input type="button" value="反转" @click="myReverse"></input>
</div>
</body>
</html>

反转1
反转2

侦听属性 watch

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                    // # 表示id
                    // . 表示class
                    "el": "#div0",
                    "data": {
                        num1: 1,
                        num2: 2,
                        num3: 0
                    }, watch: {
                        num1: function (newValue) {
                            this.num3 = parseInt(newValue) + parseInt(this.num2);
                        },
                        num2: function (newValue) {
                            this.num3 = parseInt(this.num1) + parseInt(newValue);
                        }
                    }
                })
            ;
        }
    </script>
</head>
<body>
<div id="div0">
    <span>{{msg}}</span><br/>
    <input type="text" v-model="num1"></input>
    +
    <input type="text" v-model="num2"></input>
    =
    <span>{{num3}}</span>

</div>
</body>
</html>

结果
结果

生命周期

生命周期
相关样例

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                        // # 表示id
                        // . 表示class
                        "el": "#div0",
                        "data": {
                            msg: "hello"
                        },
                        // vue实例对象创建之前
                        beforeCreate: function () {
                            console.log("beforeCreate: vue对象创建之前");
                            console.log("msg = " + this.msg);
                        },
                        // vue对象创建之后
                        created: function () {
                            console.log("created: vue对象创建之后");
                            console.log("msg = " + this.msg);
                        },
                        // 数据装载之前
                        beforeMount: function () {
                            console.log("beforeMount: 数据装载之前");
                            var spanValue = document.getElementById("span").innerText;
                            console.log("msg = " + spanValue);
                        },
                        // 数据装载之后
                        mounted: function () {
                            console.log("mounted: 数据装载之后");
                            var spanValue = document.getElementById("span").innerText;
                            console.log("msg = " + spanValue);
                        },
                        // 数据更新之前
                        beforeUpdate: function () {
                            console.log("beforeUpdate: 数据更新之前");
                            var spanValue = document.getElementById("span").innerText;
                            console.log("更新的spanValue = " + spanValue);
                            console.log("更新的msg = " + this.msg);
                        },
                        // 数据更新之后
                        updated: function () {
                            console.log("updated: 数据更新之后");
                            var spanValue = document.getElementById("span").innerText;
                            console.log("更新的spanValue = " + spanValue);
                            console.log("更新的msg = " + this.msg);
                        }
                        ,
                        methods: {
                            changeMsg: function () {
                                this.msg = this.msg + "D";
                            }
                        }
                    }
                )
            ;
        }
    </script>
</head>
<body>
<div id="div0">
    <span id="span">{{msg}}</span><br/>
    <input type="button" value="更改msg的值" @click="changeMsg"></input>
</div>
</body>
</html>

图示
图示

总结

Vue
(1) {{}} - 相当于innerText
(2) v-bind:attr 绑定属性值。例如,v-bind:value - 绑定value值
简写: :value
(3) v-model 双向绑定
v-model:value , 简写 v-model
(4) v-if , v-else , v-show
v-if和v-else之间不能有其他的节点
v-show是通过样式表display来控制节点是否显示
(5) v-for 迭代
v-for={fruit in fruitList}
(6) v-on 绑定事件
(7) 其他:

  • trim:去除首尾空格 , split() , join()
  • watch表示侦听属性
  • 生命周期

Axios

Axios基本介绍

Axios是Ajax的一个框架简化Ajax操作

Axios执行的基本步骤

Axios执行Ajax操作的步骤
Axios示例
简单写一个代码样例

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script language="JavaScript" src="script/axios.min.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                        // # 表示id
                        // . 表示class
                        "el": "#div0",
                        "data": {
                            uname: "jack",
                            pwd: "ok"
                        },
                        methods: {
                            axios01: function () {
                                axios({
                                    "method": "post",
                                    "url": "axios01.do",
                                    "params": {
                                        "userName": vue.uname,
                                        "pwd": vue.pwd
                                    }
                                }).then(function (response) {
                                    console.log(response);
                                }).catch(function (error) {
                                    console.log(error);
                                });
                            }
                        }
                    }
                )
            ;
        }
    </script>
</head>
<body>
<div id="div0">
    账号:<input type="text" v-model="uname"></input>
    密码:<input type="text" v-model="pwd"></input>
    <input type="button" @click="axios01" value="提交"></input>
</div>
</body>
</html>

java代码

package com.atguigu.axios;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: Axios01Servlet
 * @Description:
 * @Author: wty
 * @Date: 2022/12/15
 */
@WebServlet("/axios01.do")
public class Axios01Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");

        System.out.println("uname =" + uname);
        System.out.println("pwd" + pwd);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(uname + "_" + pwd);

        //throw new NullPointerException("这里故意抛出一个空指针异常....");
    }
}

显示效果
前台接收到后台的返回值
显示效果1
后台的数据成功被前台获取
显示效果2

发送请求体json

什么是json

JSON是一种数据格式
XML也是一种数据格式
XML格式表示两个学员信息的代码如下:

  <students>
    <student sid="s001">
        <sname>jim</sname>
        <age>18</age>
    </student>
    <student sid="s002">
        <sname>tom</sname>
        <age>19</age>
    </student>
  </students>

JSON格式表示两个学员信息的代码如下:

  [{sid:"s001",age:18},{sid:"s002",age:19}]

JSON特点

JSON表达数据更简洁,更能够节约网络带宽

客户端发送JSON格式的数据给服务器端

(1) 客户端中params需要修改成: data:
(2) 服务器获取参数值不再是 request.getParameter()…
而是:

StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = request.getReader();
String str = null ;
while((str=bufferedReader.readLine())!=null){
	stringBuffer.append(str);
}
str = stringBuffer.toString() ;

(3) 我们会发现 str的内容如下:

{"uname":"lina","pwd":"ok"}

服务器端给客户端响应JSON格式的字符串,然后客户端需要将字符串转化成js Object

导入jar包 Gson

导入jar包 Gson

相关代码 后端接收到数据

demo10.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>演示Axios发送json格式给服务器</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script language="JavaScript" src="script/axios.min.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                        // # 表示id
                        // . 表示class
                        "el": "#div0",
                        "data": {
                            uname: "jack",
                            pwd: "ok"
                        },
                        methods: {
                            axios02: function () {
                                axios({
                                    "method": "post",
                                    "url": "axios02.do",
                                    "data": {
                                        "uname": vue.uname,
                                        "pwd": vue.pwd
                                    }
                                }).then(function (response) {
                                    console.log(response);
                                }).catch(function (error) {
                                    console.log(error);
                                });
                            }
                        }
                    }
                )
            ;
        }
    </script>
</head>
<body>
<div id="div0">
    账号:<input type="text" v-model="uname"></input>
    密码:<input type="text" v-model="pwd"></input>
    <input type="button" @click="axios02" value="提交"></input>
</div>
</body>
</html>

获取到user对象

Axios02Servlet

package com.atguigu.axios;

import com.atguigu.pojo.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.org.apache.bcel.internal.generic.NEW;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: Axios02Servlet
 * @Description:
 * @Author: wty
 * @Date: 2022/12/15
 */
@WebServlet("/axios02.do")
public class Axios02Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuffer stringBuffer = new StringBuffer("");

        BufferedReader bufferedReader = request.getReader();
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        System.out.println("str = " + str);

        // str = {"uname":"jack","pwd":"ok"}

        // 需要第三方jar包
        // 方式1
        Gson gson = new Gson();

        // 方式2:可以格式化
        //Gson gson1 = new GsonBuilder().create();

        User user = gson.fromJson(str, User.class);
        System.out.println(user);


    }
}

User.java

package com.atguigu.pojo;

/**
 * @ClassName: User
 * @Description:
 * @Author: wty
 * @Date: 2022/12/15
 */

public class User {
    private String uname;
    private String pwd;

    public User() {
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public User(String uname, String pwd) {
        this.uname = uname;
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "uname='" + uname + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

后台输出结果

str = {"uname":"jack","pwd":"ok"}
User{uname='jack', pwd='ok'}

后端接收数据后以json object返回给前端

demo11.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>演示Axios发送异步请求给服务器,服务器响应请求给客户端</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script language="JavaScript" src="script/axios.min.js"></script>
    <script type="" language="JavaScript">
        window.onload = function () {
            var vue = new Vue({
                        // # 表示id
                        // . 表示class
                        "el": "#div0",
                        "data": {
                            uname: "jack",
                            pwd: "ok"
                        },
                        methods: {
                            axios03: function () {
                                axios({
                                    "method": "post",
                                    "url": "axios03.do",
                                    "data": {
                                        "uname": vue.uname,
                                        "pwd": vue.pwd
                                    }
                                }).then(function (response) {
                                    var data = response.data;
                                    console.log(data);
                                    vue.uname = data.uname;
                                    vue.pwd = data.pwd;
                                }).catch(function (error) {
                                    console.log(error);
                                });
                            }
                        }
                    }
                )
            ;
        }
    </script>
</head>
<body>
<div id="div0">
    账号:<input type="text" v-model="uname"></input>
    密码:<input type="text" v-model="pwd"></input>
    <input type="button" @click="axios03" value="提交"></input>
</div>
</body>
</html>

Axios03Servlet

package com.atguigu.axios;

import com.atguigu.pojo.User;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @ClassName: Axios03Servlet 
 * @Description:
 * @Author: wty
 * @Date: 2022/12/15
 */
@WebServlet("/axios03.do")
public class Axios03Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuffer stringBuffer = new StringBuffer("");

        BufferedReader bufferedReader = request.getReader();
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        System.out.println("str = " + str);

        // str = {"uname":"jack","pwd":"ok"}

        // 需要第三方jar包
        // 方式1
        Gson gson = new Gson();

        // 方式2:可以格式化
        //Gson gson1 = new GsonBuilder().create();

        User user = gson.fromJson(str, User.class);
        user.setUname("小明");
        user.setPwd("1234");
        System.out.println(user);

        // 假设user是数据库查询查来的,需要转换成json格式给客户端
        String userJsonStr = gson.toJson(user);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(userJsonStr);

    }
}

输出结果
结果1
将后台的赋值,传到了前台
结果2

前台JSON对象和String的转换

var str = "";
// object → string
JSON.stringify(str);
//  string→ object
JSON.parse(str);

代码示例

js中的String转换成Object

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>JS中的字符串和Object之间互转的API</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script language="JavaScript" src="script/axios.min.js"></script>
    <script type="" language="JavaScript">
        function hello01() {
            var str = "{\"uname\":\"lina\",\"age\":20}";
            var user = JSON.parse(str);
            alert(typeof user);
            alert(user.uname + "_" + user.age);
        }
    </script>
</head>
<body>
<div id="div0">
    <input type="button" value="提交" onclick="hello01()"></input>
</div>
</body>
</html>

js中的Object变成string

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>JS中的字符串和Object之间互转的API</title>
    <meta content="" charset="UTF-8">
    <script language="JavaScript" src="script/vue.js"></script>
    <script language="JavaScript" src="script/axios.min.js"></script>
    <script type="" language="JavaScript">
        function hello01() {
            var str = "{\"uname\":\"lina\",\"age\":20}";
            var user = JSON.parse(str);
            alert(typeof user);
            alert(user.uname + "_" + user.age);
        }

        function hello02() {
            var user = {"uname": "lina", "age": 3};
            alert(typeof user);
            var userStr = JSON.stringify(user);
            alert(userStr);
        }
    </script>
</head>
<body>
<div id="div0">
    <input type="button" value="提交" onclick="hello02()"></input>
</div>
</body>
</html>

书城1.3最终版

购物车添加使用异步请求

index.html
<!--登录后风格-->
            <div class="topbar-right" th:unless="${session.currUser == null}">
                <span>欢迎你<b th:text="${session.currUser.getUname()}">张总</b></span>
                <a href="#" class="register">注销</a>
                <a th:href="@{/page.do(operate='page',page='cart/cart')}" class="cart iconfont icon-gouwuche">
                    购物车
                    <div class="cart-num" th:text="${session.currUser.getCart().getTotalCount()}">3</div>
                </a>
                <a href="./pages/manager/book_manager.html" class="admin">后台管理</a>
            </div>
cart.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Document</title>
    <link rel="stylesheet" th:href="@{/static/css/minireset.css}"/>
    <link rel="stylesheet" th:href="@{/static/css/common.css}"/>
    <link rel="stylesheet" th:href="@{/static/css/cart.css}"/>
    <script language="JavaScript" th:src="@{/static/script/vue.js}"></script>
    <script language="JavaScript" th:src="@{/static/script/axios.min.js}"></script>
    <script language="JavaScript" th:src="@{/static/script/cart.js}">

    </script>
</head>
<body>
<div class="header">
    <div class="w">
        <div class="header-left">
            <a th:href="@{/index.html}">
                <img th:src="@{/static/img/logo.gif}" alt=""
                /></a>
            <h1>我的购物车</h1>
        </div>
        <div class="header-right">
            <h3>欢迎<span th:text="${session.currUser.getUname()}">张总</span>光临尚硅谷书城</h3>
            <div class="order"><a th:href="@{/order.do(operate='getOrderList')}">我的订单</a></div>
            <div class="destory"><a href="../../index.html">注销</a></div>
            <div class="gohome">
                <a href="../../index.html">返回</a>
            </div>
        </div>
    </div>
</div>
<div class="list" id="cart_div">
    <div class="w">
        <table>
            <thead>
            <tr>
                <th>图片</th>
                <th>商品名称</th>

                <th>数量</th>
                <th>单价</th>
                <th>金额</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!--<tr th:each="cartItem : ${session.currUser.getCart().getMap().values()}">-->
            <tr v-for="cartItem in cart.map">
                <td>
                    <!--<img th:src="@{|/static/uploads/${cartItem.getBook().getBookImg()}|}" alt=""/>-->
                    <img v-bind:src="'static/uploads/'+cartItem.book.bookImg" alt=""/>
                </td>
                <!--<td th:text="${cartItem.getBook().getBookName()}">活着</td>-->
                <td>{{cartItem.book.bookName}}</td>
                <td>
                    <!--<span class="count" th:disabled="${cartItem.getBuyCount()==1}"-->
                    <!--      th:οnclick="|editCartMinus(${cartItem.id},${cartItem.buyCount})|">-</span>                    -->
                    <!--    <input class="count-num" type="text" th:value="${cartItem.getBuyCount()}"/>-->
                    <!--    <span class="count"-->
                    <!--          th:οnclick="|editCartAdd(${cartItem.id},${cartItem.buyCount},${cartItem.getBook().getBookCount()})|">+</span>-->
                    <!--</td>-->
                    <!--<td th:text="${cartItem.getBook().getPrice()}">36.8</td>-->
                    <!--<td th:text="|小计:${cartItem.getXj()}|">36.8</td>-->
                    <!--<td><a href="">删除</a></td>-->
                    <span class="count" v-bind:disabled="cartItem.buyCount==1"
                          v-on:click="editCartMinus(cartItem.id,cartItem.buyCount)">-</span>
                    <input class="count-num" type="text" v-bind:value="cartItem.buyCount"/>
                    <span class="count"
                          v-on:click="editCartAdd(cartItem.id,cartItem.buyCount,cartItem.book.bookCount)">+</span>
                </td>
                <td>{{cartItem.book.price}}</td>
                <td>{{cartItem.xj}}</td>
                <td><a href="">删除</a></td>
            </tr>
            </tbody>
        </table>
        <div class="footer">
            <div class="footer-left">
                <a href="#" class="clear-cart">清空购物车</a>
                <a href="#">继续购物</a>
            </div>
            <div class="footer-right">
                <!--<div>共<span th:text="${session.currUser.getCart().getTotalBookCount()}">3</span>件商品</div>-->
                <!--<div class="total-price">总金额<span th:text="${session.currUser.getCart().getTotalMoney()}">99.9</span>元-->
                <div><span>{{cart.totalBookCount}}</span>件商品</div>
                <div class="total-price">总金额<span>{{cart.totalMoney}}</span></div>
                <a class="pay" th:href="@{/order.do(operate='checkout')}">去结账</a>
            </div>
        </div>
    </div>
</div>
<div class="bottom">
    <div class="w">
        <div class="top">
            <ul>
                <li>
                    <a href="">
                        <img th:src="@{/static/img/bottom1.png}" alt=""/>
                        <span>大咖级讲师亲自授课</span>
                    </a>
                </li>
                <li>
                    <a href="">
                        <img th:src="@{/static/img/bottom.png}" alt=""/>
                        <span>课程为学员成长持续赋能</span>
                    </a>
                </li>
                <li>
                    <a href="">
                        <img th:src="@{/static/img/bottom2.png}" alt=""/>
                        <span>学员真是情况大公开</span>
                    </a>
                </li>
            </ul>
        </div>
        <div class="content">
            <dl>
                <dt>关于尚硅谷</dt>
                <dd>教育理念</dd>
                <!-- <dd>名师团队</dd>
                <dd>学员心声</dd> -->
            </dl>
            <dl>
                <dt>资源下载</dt>
                <dd>视频下载</dd>
                <!-- <dd>资料下载</dd>
                <dd>工具下载</dd> -->
            </dl>
            <dl>
                <dt>加入我们</dt>
                <dd>招聘岗位</dd>
                <!-- <dd>岗位介绍</dd>
                <dd>招贤纳师</dd> -->
            </dl>
            <dl>
                <dt>联系我们</dt>
                <dd>http://www.atguigu.com</dd>
                <dd></dd>
            </dl>
        </div>
    </div>
    <div class="down">
        尚硅谷书城.Copyright ©2015
    </div>
</div>
</body>
</html>

CartItemServiceImpl.java
    /**
     * @param
     * @return java.util.List<com.atguigu.book.pojo.CartItem>
     * @description 获取指定用户的所有购物车项列表,需要注意方法内部会查询book的详细信息
     * @param: user
     * @date 2022/12/13 17:59
     * @author wty
     **/
    @Override
    public List<CartItem> getCartItemList(User user) {
        List<CartItem> cartItemList = cartItemDAO.getCartItemList(user);
        for (CartItem cartItem : cartItemList) {
            Book book = bookService.getBook(cartItem.getBook().getId());
            cartItem.setBook(book);
            // 此处需要计算小计,执行内部代码让book的price * buyCount
            cartItem.getXj();
        }

        return cartItemList;
    }
CartItemController.java
    public String editCart(Integer cartItemId, Integer buyCount) {
        cartItemService.updateCartItemBuyCount(new CartItem(cartItemId, buyCount));
        return "";
    }

    public String cartInfo(HttpSession session) {
        User currUser = (User) session.getAttribute("currUser");
        Cart cart = cartItemService.getCart(currUser);

        // 调用Cart中的三个属性get方法,目的是计算值,否则为null
        cart.getTotalMoney();
        cart.getTotalCount();
        cart.getTotalBookCount();

        Gson gson = new Gson();
        String cartJsonStr = gson.toJson(cart);
        return "json:" + cartJsonStr;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心向阳光的天域

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值