11.Java Web之Vue和Axios

vue.js、axios.js、gson-2.2.4.jar(链接:https://pan.baidu.com/s/197Up14ZJjJU2YPU_HS__5g 提取码:uvej)

1.vue快速入门

1.1 准备Vue.js环境

java语言的程序包:jar包

JavaScript语言的程序包:外部js文件

在webapp下创建script文件夹,然后将vue.js导入

在html中导入vue.js

<script type="text/javascript" src="script/vue.js">script>
  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表示侦听属性
    • 生命周期

1.2 声明式渲染

对id="div0"的标签进行渲染

demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    msg:"hello world!"
                }
            });

        }
    script>
head>
<body>
    <div id="div0">
        <span>{{msg}}span>
    div>
body>
html>

1.3 绑定元素属性

基本语法
v-bind:HTML标签的原始属性名

Demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    msg:"hello world!",
                    uname:"张三丰"
                }
            });

        }
    script>
head>
<body>
    <div id="div0">
        <span>{{msg}}span>
        

        <input type="text" :value="uname"/>
    div>
body>
html>

1.4 双向数据绑定

使用了双向绑定后,就可以实现:页面上数据被修改后,Vue对象中的数据属性也跟着被修改。

Demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    msg:"hello world!"
                }
            });

        }
    script>
head>
<body>
    <div id="div0">
        <span>{{msg}}span>
        

        
        
        <input type="text" v-model.trim="msg"/>
    div>
body>
html>

在text文本框中修改内容,span中的结果也会跟着改变

1.5 条件渲染

根据Vue对象中,数据属性的值来判断是否对HTML页面内容进行渲染。
v-if
v-if和v-else
v-show

demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    num:1
                }
            });

        }
    script>
head>
<body>
<div id="div0">
    <input type="text" v-model="num">
    
    <div v-if="num%2==0" style="width:200px;height: 200px;background-color: chartreuse;"> div>

    <div v-else="num%2==0" style="width:200px;height: 200px;background-color: coral;"> div>

    
    
    <div v-show="num%2==0" style="width:200px;height: 200px;background-color: blueviolet;"> div>
div>
body>
html>

改变文本框的数值时显示颜色会发生改变

1.5 列表渲染

迭代一个简单的数组

demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    fruitList:[
                        {fname:"苹果",price:5,fcount:100,remark:"苹果好吃"},
                        {fname:"菠萝",price:5,fcount:100,remark:"菠萝好吃"},
                        {fname:"香蕉",price:5,fcount:100,remark:"香蕉好吃"},
                        {fname:"西瓜",price:5,fcount:100,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 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>

1.6 事件驱动

demo:字符串顺序反转

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    msg:"hello world"
                },
                methods:{
                    myReverse:function (){
                        this.msg = this.msg.split("").reverse().join("");
                    }
                }
            });

        }
    script>
head>
<body>
<div id="div0">
    <span>{{msg}}span>
    
    

    <input type="button" value="反转" @click="myReverse()"/>
div>
body>
html>

1.7 监听属性

监听就是对某个属性进行监控,当其发生变化时调用对应的函数

demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    num1:0,
                    num2:0,
                    num3:0
                },
                watch:{
                    //监听属性num1和num2
                    //当num1的值有改动时,name需要调用后面定义的方法,numValue值得就是num1的新值
                    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">
    <input type="text" v-model="num1" size="2">
    +
    <input type="text" v-model="num2" size="2">
    =
    <span>{{num3}}span>
div>
body>
html>

1.7 vue的生命周期

demo

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    msg:"hello"
                },
                methods:{
                    changeMsg:function (){
                        this.msg = "你好";
                    }
                },
                /*vue对象创建之前*/
                beforeCreate:function (){
                    console.log("beforeCreate:vue对象创建之前...");
                    console.log(msg);
                },
                /*vue对象创建之后*/
                created:function (){
                    console.log("created:vue对象创建之后...");
                    console.log(msg);
                },
                /*数据装载之前*/
                beforeMount:function (){
                    console.log("beforeMount:数据装载之前...");
                    console.log("span:"+document.getElementById("span").innerText);
                },
                /*数据装载之后*/
                mounted:function (){
                    console.log("mounted:数据装载之后...");
                    console.log("span:"+document.getElementById("span").innerText);
                },
                /*数据更新之前*/
                beforeUpdate:function (){
                    console.log("beforeUpdate:数据更新之前...");
                    console.log("msg:"+this.msg);
                    console.log("span:"+document.getElementById("span").innerText);
                },
                /*数据更新之后*/
                updated:function (){
                    console.log("updated:数据更新之后...");
                    console.log("msg:"+this.msg);
                    console.log("sapn:"+document.getElementById("span").innerText);

                }
            });

        }
    script>
head>
<body>
<div id="div0">
    <span id="span">{{msg}}span>
    <input type="button" value="改变msg的值" @click="changeMsg">
div>
body>
html>

2.Ajax

Ajax : 异步的JavaScript and XML
目的: 用来发送异步的请求,然后当服务器给我响应的时候再进行回调操作
好处: 提高用户体验;局部刷新:降低服务器负担、减轻浏览器压力、减轻网络带宽压力
使用Axios和使用Vue一样,导入对应的*.js文件即可。
官方提供的script标签引入方式为:

<script src="https://unpkg.com/axios/dist/axios.min.js">script>

基本用法:https://heavy_code_industry.gitee.io/code_heavy_industry/pro001-javaweb/lecture/chapter12/verse02.html

开发步骤:

  1. 创建XMLHttpRequest
  2. 调用open进行设置:“GET” , URL , true
  3. 绑定状态改变时执行的回调函数 - onreadystatechange
  4. 发送请求 - send()
  5. 编写回调函数,在回调函数中,我们只对XMLHttpRequest的readystate为4的时候感兴趣
    我们只对XMLHttpRequest的status为200的时候感兴趣

XMLHttpRequest的readystate
0: (Uninitialized) the send( ) method has not yet been invoked.
1: (Loading) the send( ) method has been invoked, request in progress.
2: (Loaded) the send( ) method has completed, entire response received.
3: (Interactive) the response is being parsed.
4: (Completed) the response has been parsed, is ready for harvesting.

0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了

3.Axios

Axios是Ajax的一个框架,简化Ajax操作
Axios执行Ajax操作的步骤:
1.添加并引入axios的js文件
2-1.客户端向服务器端异步发送服务请求
基本格式:axios().then().catch()
示例:

axios({
    method:"POST",
    url:"...",
    params:{
        uname:"lina",
        pwd:"ok"
    }
})
.then(function(response){}) //成功响应时的回调 response.data可以获取到服务器响应的内容
.catch(function(error){})   //有异常时执行的回调 error.response.data可以获取到响应的内容
                            //reson.message / reason.stack 可以查看错误的信息

2-2.客户端想服务器发送JSON格式的数据
什么是JSON
JSON是一种数据格式
XML也是一种数据格式

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

<students>
    <student sid="s001">
        <sname>jimsname>
        <age>18age>
    student>
    <student sid="s002">
        <sname>tomsname>
        <age>19age>
    student>
students>

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

[{sid:"s001",sname:"jim",age:10},{sid:"s002",sname:"tom",age:19}]

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

3.1 实验:发送一个带普通请求参数值的异步请求

① demo07.html(发送异步请求)

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript" src="script/axios.min.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    uname:"lina",
                    pwd:"ok"
                },
                methods:{
                    axios01:function (){
                        axios({
                            method:"POST",
                            url:"axios01.do",
                            params:{
                                uname: vue.uname,
                                pwd: vue.pwd
                            }
                        })
                            .then(function(response){
                                console.log(response);
                            })
                            .catch(function (error) {
                                console.log(error);
                            })
                    }
                }
            });

        }
    script>
head>
<body>
<div id="div0">
    uname:<input type="text" v-model="uname"/><br/>
    pwd:<input type="text" v-model="pwd" /><br/>
    <input type="button" @click="axios01" value="发送一个带普通请求参数值的异步请求"/>
div>
body>
html>

② 创建Axios01Servlet接收请求

package com.example.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;

@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);
    }
}

③ 访问:http://localhost:8080/demo07.html
然后点击按钮,查看idea是否收到请求

3.1 实验2:服务端返回数据

package com.example.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;

@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);
    }
}

3.3 实验:发送JSON格式的参数值给服务器端

①demo08.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script type="text/javascript" src="script/vue.js">script>
    <script type="text/javascript" src="script/axios.min.js">script>
    <script type="text/javascript">
        window.onload=function (){
            var vue = new Vue({
                el:"#div0",
                data:{
                    uname:"lina",
                    pwd:"ok"
                },
                methods:{
                    axios01: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">
    uname:<input type="text" v-model="uname"/><br/>
    pwd:<input type="text" v-model="pwd" /><br/>
    <input type="button" @click="axios01" value="发送JSON格式数据"/>
div>
body>
html>

② 服务端接受JSON格式数据

package com.example.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.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@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 = null;
        while((str=bufferedReader.readLine())!=null){
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        System.out.println(str);
    }
}

3.4 实验:服务器端将接收到的JSON数据转化为JavaObject

导入gson的jar包

修改Axios02Servlet

package com.example.axios;

import com.example.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;
import java.io.PrintWriter;

@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 = null;
        while((str=bufferedReader.readLine())!=null){
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
//        System.out.println(str);

        //已知String
        //需要转化成 JavaObject
        Gson gson = new Gson();
        //Gson有两个API
        //1.fromJson(String,T) 将字符串转化为java object
        //2.toJson(java Object) 将javaobject转化成json字符串,这样才能响应给客户端
        User user = gson.fromJson(str, User.class);
        System.out.println(user);
    }
}

创建User类

package com.example.pojo;

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

    public User(){}

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

    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;
    }

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

打印到的结果:User{uname=‘lina’, pwd=‘ok’}

3.4 实验:服务器端将javaobject转化为json格式数据返回给客户端

服务器端将javaobject转化为json格式数据发送给客户端

package com.example.axios;

import com.example.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;
import java.io.PrintWriter;

@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 = null;
        while((str=bufferedReader.readLine())!=null){
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
//        System.out.println(str);

        //已知String
        //需要转化成 JavaObject
        Gson gson = new Gson();
        //Gson有两个API
        //1.fromJson(String,T) 将字符串转化为java object
        //2.toJson(java Object) 将javaobject转化成json字符串,这样才能响应给客户端
        User user = gson.fromJson(str, User.class);
//        System.out.println(user);
        user.setUname("小王");
        user.setPwd("123456");

        //假设User是从数据库查询出来的,现在需要讲起转化成json格式的字符串,然后响应给客户端
        String userJsonStr = gson.toJson(user);
        response.setCharacterEncoding("utf-8");
        //MIME-TYPE
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(userJsonStr);
    }
}

添加家客户端接受到json数据的处理

axios01:function (){
    axios({
        method:"POST",
        url:"axios02.do",
        data:{
            uname: vue.uname,
            pwd: vue.pwd
        }
    })
        .then(function(response){
            console.log(response);
            var data = response.data;
            //data对应的数据
            //{uname: '小王', pwd: '123456'}
            vue.uname=data.uname;
            vue.pwd=data.pwd;

            //此处value中的data返回的是js object 因此可以直接点出属性
            //如果我们获取的是一个字符串:“{uname: '小王', pwd: '123456'}”
            //js语言中也有字符串和js对象之间互转的API
            //String JSON.stringify(obj)
            //object JSON.parse(String)


        })
        .catch(function (error) {
            console.log(error);
        })
}

你可能感兴趣的:(java,前端,mvc)