1. Vue概述

1.1 认识Vue

Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层。Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。它不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。

前端框架三巨头:Vue.js、React.js、AngularJS,vue.js以其轻量易用著称,vue.js和React.js发展速度最快。

渐进式:可以选择性的使用该框架的一个或一些组件,这些组件的使用也不需要将框架全部组件都应用;而且用了这些组件也不要求你的系统全部都使用该框架。

官网:添加链接描述 参考:添加链接描述

1.2 MVVM模式

MVVM是Model-View-ViewModel的简写。它本质上就是MVC 的改进版。MVVM 就是将其中的View 的状态和行为抽象化,让我们将视图 UI 和业务逻辑分开

MVVM模式和MVC模式一样,主要目的是分离视图(View)和模型(Model)

Vue.js 是一个提供了 MVVM 风格的双向数据绑定的 Javascript 库,专注于View 层。它的核心是 MVVM 中的 VM,也就是 ViewModel。 ViewModel负责连接 View 和 Model,保证视图和数据的一致性,这种轻量级的架构让前端开发更加高效、便捷

Vue嵌入Java代码 vue java_java

2. Vue快速入门

2.1 插值表达式

数据绑定最常见的形式就是使用“Mustache”语法 (双大括号) 的文本插值,Mustache 标签将会被替代为对应数据对象上属性的值。无论何时,绑定的数据对象上属性发生了改变,插值处的内容都会更新。
Vue.js 都提供了完全的 JavaScript 表达式支持。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>快速入门</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            {{message}}  <!--Vue的插值表达式,把data中定义的数据显示到此处-->

            <!--三元运算符-->
            {{ true ? "OK" : "NO" }}

            <!--数学运算-->
            {{number*3.14}}

            <!--插值表达式不支持
                {{var a = 1;}}
                {{if(a=10){}}}
            -->


        </div>
    </body>
    <script>
        //view model
        //创建vue对象
        new Vue({
            el:"#app", //由vue接管id为app区域
            data:{
                message:"Hello Vue!",  //注意:此处不要加分号
                number:100
            }
        });
    </script>
</html>

Vue.js 支持数值运算,三元运算:

{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}

Vue.js 不支持语句,流控控制:

<!-- 这是语句,不是表达式 -->
{{ var a = 1 }}
<!-- 流控制也不会生效,请使用三元表达式 -->
{{ if (ok) { return message } }}

2.2 VueJS 常用系统指令

2.2.1 v-on

可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码

2.2.1 v-on:click
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-on:click</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            {{message}}
            <button v-on:click="fun1('Vue v-on')">vue的onclick</button>
        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app",  //表示当前vue对象接管了div区域
            data:{
                message:"Hello Vue!" //注意不要写分号结尾
            },
            methods:{
                fun1:function (msg){
                    alert("Hello");
                    this.message=msg;
                }
            }
        });
    </script>
</html>
2.2.2 v-on:keydown

以下为使用传统方式和vue方式分别实现输入框只能输入数字,输入其他无效。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-on:keydown</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            Vue:<input type="text" v-on:keydown="fun($event)">
            <hr/>
            传统js:<input type="text" onkeydown="showKeyCode()" />
        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app",
            methods:{
                /* $event 它是vue中的事件对象,和我们传统js的event对象是一样的 */
                fun:function(event){
                    var keyCode = event.keyCode;
                    if (keyCode < 48 || keyCode > 57){
                        //不让键盘的按键起作用
                        event.preventDefault()
                    }
                }
            }
        });

        //传统js的键盘按下事件
        function showKeyCode(){
            //event对象和我们的document对象以及Window对象是一样的,可以不用定义直接使用
            var keyCode = event.keyCode;
            if (keyCode < 48 || keyCode > 57){
                //不让键盘的按键起作用
                event.preventDefault()
            }
            //alert(keyCode);
            // if (event.keyCode == 13){
            //     alert("你按的是回车");
            // }
        }
    </script>
</html>
2.2.3 v-on:mouseover

这里实现鼠标移动到指定位置出现弹框,

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-on:mouseover</title>
        <script src="js/vuejs-2.5.16.js"></script>
        <style>
            #div {
                background-color: red;
                width: 300px;
                height: 300px;
            }
        </style>
    </head>
    <body>
        <div id="app">
            <div v-on:mouseover="fun1" id="div">
                <textarea v-on:mouseover="fun2($event)">这是一个文件域</textarea>
            </div>

            <!--<div onmouseover="divmouseover()" id="div">
                <textarea onmouseover="textareamouseover()">这是一个文件域</textarea>
            </div>-->

        </div>
    </body>
    <script>
        //view model
        /*
            @事件名称  就是 v-on:事件名称的简写方式
            @mouseover 就等同于  v-on:mouseover
        * */
        new Vue({
            el:"#app", //由vue接管id为app区域
            methods:{
                fun1:function(){
                    alert("鼠标悬停在div上")
                },
                fun2:function(event){
                    alert("鼠标悬停在textarea上")
                    event.stopPropagation();  //消除传递,否则textarea在div内,textarea的弹框弹完还会弹div的弹框
                }
            }
        });

        //传统的js方式
        function divmouseover(){
            alert("鼠标移动到div上了");
        }
        function textareamouseover(){
            alert("鼠标移动到textarea上了");
            event.stopPropagation();  //消除传递,否则textarea在div内,textarea的弹框弹完还会弹div的弹框
        }

    </script>
</html>
2.2.4 事件修饰符

Vue.js 为 v-on 提供了事件修饰符来处理 DOM 事件细节,如:event.preventDefault() 或 event.stopPropagation()。
Vue.js通过由点(.)表示的指令后缀来调用修饰符。

  • .stop 阻止单击事件继续传播
  • .prevent 阻止事件的默认行为
  • .capture 实现捕获触发事件的机制,即从外部事件开始执行
  • .self 实现只有点击当前元素才会触发事件处理函数
  • .once 实现事件的触发次数为一次
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-on:事件修饰符</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            <form @submit.prevent action="http://www.itheima.com" method="post">
                <input type="submit" value="提交">
            </form>

            <form action="http://www.itheima.com" method="post" onsubmit="return checkForm()">
                <input type="submit" value="提交">
            </form>

        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app"
        });

        //传统js方式
        function checkForm(){
            alert(1);
            //表单验证必须有一个明确的boolean类型返回值
            //在应用验证方法时必须加上 return 方法名称
            return false;
        }

    </script>
</html>
2.2.5 按键修饰符

Vue 允许为 v-on 在监听键盘事件时添加按键修饰符
全部的按键别名:

  • .enter
  • .tab
  • .delete (捕获 “删除” 和 “退格” 键)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right
  • .ctrl
  • .alt
  • .shift
  • .meta
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-on:按键修饰符</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            Vue:<input type="text" v-on:keydown.enter="fun1">
        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app",
            methods:{
                fun1:function (){
                    alert("按下的是回车");
                }
            }
        });

    </script>
</html>

2.3 v-text与v-html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-text与v-html</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            <div v-text="message"></div>
            <div v-html="message"></div>
            <!--<div id="div1"></div>
            <div id="div2"></div>-->
        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app",
            data:{
                message:"<h1>Hello Vue</h1>"
            }
        });


        //传统js的innerText和innerHTML
        window.onload = function (){
            document.getElementById("div1").innerHTML="<h1>Hello</h1>";
            document.getElementById("div2").innerText="<h1>Hello</h1>";
        }

    </script>
</html>

2.4 v-bind

插值语法不能作用在 HTML 特性上,遇到这种情况应该使用 v-bind指令

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-bind</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            <font size="5" v-bind:color="ys1">船只</font>
            <font size="5" :color="ys2">黑马</font>
        </div>
    </body>
    <script>
        //view model
        //插值表达式不能用于html标签的属性取值
        //要想给html标签的属性设置变量的值,需要使用v-bind
        //v-bind也可以简化写法  直接使用:
        new Vue({
            el:"#app",
            data:{
                ys1:"red",
                ys2:"green"
            }

        });

    </script>
</html>

v-bind简写方式

<!-- 完整语法 -->
<a v-bind:href="url">...</a>
<!-- 缩写 -->
<a :href="url">...</a>

2.5 v-model

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-model</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            <form action="" method="post">
                用户名:<input type="text" name="username" v-model="user.username" ><br/>
                密码:<input type="text" name="password" v-model="user.password" ><br/>
            </form>
        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app",
            data:{
                user:{
                    username:"test",
                    password:"1234"
                }
            }
        });
    </script>
</html>

2.6 v-for

操作array

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>v-for示例1</title>
		<script src="js/vuejs-2.5.16.js"></script>
	</head>
	<body>
		<div id="app">
			<ul>
				<li v-for="(item,index) in list">{{item+" "+index}}</li>
			</ul>
		</div>
		<script>
			new Vue({
				el:'#app', //表示当前vue对象接管了div区域
				data:{
					list:[1,2,3,4,5,6]
				}
			});
		</script>
	</body>
</html>

操作对象

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>v-for示例2</title>
		<script src="js/vuejs-2.5.16.js"></script>
	</head>
	<body>
		<div id="app">
			<ul>
				<li v-for="(value,key) in product">{{key}}--{{value}}</li>
			</ul>
		</div>
		<script>
			new Vue({
				el:'#app', //表示当前vue对象接管了div区域
				data:{
					product:{id:1,pname:"电视机",price:6000}
				}
			});
		</script>
	</body>
</html>

操作对象数组

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>v-for示例3</title>
		<script src="js/vuejs-2.5.16.js"></script>
	</head>
	<body>
	<div id="app">
		<table border="1">
			<tr>
				<td>序号</td>
				<td>名称</td>
				<td>价格</td>
			</tr>
			<tr v-for="p in products">
				<td>{{p.id}}</td>
				<td>{{p.pname}}</td>
				<td>{{p.price}}</td>
			</tr>
		</table>
	</div>
		<script>
			new Vue({
				el:'#app', //表示当前vue对象接管了div区域
				data:{
					products:[
					{id:1,pname:"电视机",price:6000},
					{id:2,pname:"电冰箱",price:8000},
					{id:3,pname:"电风扇",price:600}]
				}
			});
		</script>
	</body>
</html>

2.6 v-if 和 v-show

v-if是根据表达式的值来决定是否渲染元素
v-show是根据表达式的值来切换元素的display css属性

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>v-if和v-show</title>
        <script src="js/vuejs-2.5.16.js"></script>
    </head>
    <body>
        <div id="app">
            <span v-if="flag">船只</span>
            <span v-show="flag">itcast</span>
            <button @click="toggle">切换</button>
        </div>
    </body>
    <script>
        //view model
        new Vue({
            el:"#app",
            data:{
                flag:false
            },
            methods:{
                toggle:function (){
                    this.flag = !this.flag;
                }
            }
        });
    </script>
</html>

3. Vuejs生命周期

Vue嵌入Java代码 vue java_html_02

vue生命周期:

1. 创建阶段:beforeCreate();created()

  1. 新建 vue 实例 new vue()
  2. 读取配置项,加载生命周期方法
  3. 调用 beforeCreate()
  4. 设置 data、methods、computed… 等配置项
  5. 调用created()

2. 挂载阶段:beforeMount();mounted()

  1. 判断是否拥有 template 配置项
    有:传入 render 函数,编译template
    没有:把 el 对应的 outerHTML 当成 template 传入 render 函数编译
  2. 调用 beforeMount()
  3. 使用编译后结果替换 el 作用的 dom
  4. 调用 mount()

3. 更新阶段:beforeUpdate();updated()

只有数据发生变化,并且 dom 使用了该数据,dom 才会更新,此时才执行更新的生命周期方法,更新前和更新后不是数据更新的状态,而是 dom 更新前与更新后。

  1. 数据发生变化
  2. 调用 beforeUpdate()
  3. 重新渲染 dom
  4. 调用 updated()

4. 销毁阶段:beforeDestroy();destroyed()

  1. 执行 vm.$destroy() 销毁实例
  2. 调用 beforeDestroy()
  3. 实例移除 data、methods、computed…
  4. 调用 destroyed()

vue代码演示生命周期:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>生命周期</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>

<body>
<div id="app">
    {{message}}
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            message: 'hello world'
        },
        beforeCreate: function() {
            console.log(this);
            showData('创建vue实例前', this);
        },
        created: function() {
            showData('创建vue实例后', this);
        },
        beforeMount: function() {
            showData('挂载到dom前', this);
        },
        mounted: function() {
            showData('挂载到dom后', this);
        },
        beforeUpdate: function() {
            showData('数据变化更新前', this);
        },
        updated: function() {
            showData('数据变化更新后', this);
        },
        beforeDestroy: function() {
            vm.test = "3333";
            showData('vue实例销毁前', this);
        },
        destroyed: function() {
            showData('vue实例销毁后', this);
        }
    });
    function realDom() {
        console.log('真实dom结构:' + document.getElementById('app').innerHTML);
    }
    function showData(process, obj) {
        console.log(process);
        console.log('data 数据:' + obj.message)
        console.log('挂载的对象:')
        console.log(obj.$el)
        realDom();
        console.log('------------------')
        console.log('------------------')
    }
    //vm.message="good...";
    //vm.$destroy();
</script>
</body>
</html>

Vue嵌入Java代码 vue java_vue_03


将上述代码中倒数第五行注释代码放开运行数据如下:

console.log('------------------')
        console.log('------------------')
    }
    vm.message="good...";
    //vm.$destroy();
</script>
</body>
</html>

Vue嵌入Java代码 vue java_vue_04


将上述代码中倒数第五行注释代码放开运行数据如下:

console.log('------------------')
        console.log('------------------')
    }
    //vm.message="good...";
    vm.$destroy();
</script>
</body>
</html>

Vue嵌入Java代码 vue java_java_05


上述测试代码已上传至码云添加链接描述

4. Vuejs ajax

vue-resource是Vue.js的插件提供了使用XMLHttpRequest或JSONP进行Web请求和处理响应的服务。 当vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的axios。
vue-resource的github: https://github.com/pagekit/vue-resource

4.1 axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
axios的github:添加链接描述

4.2 get请求

//通过给定的ID来发送请求
axios.get('/user?ID=12345')
	.then(function(response){
		console.log(response);
	})
	.catch(function(err){
		console.log(err);
});
//以上请求也可以通过这种方式来发送
axios.get('/user',{
		params:{
		ID:12345
		}
	})
	.then(function(response){
		console.log(response);
	})
	.catch(function(err){
		console.log(err);
});

4.3 post请求

axios.post('/user',{
		firstName:'Fred',
		lastName:'Flintstone'
	})
	.then(function(res){
		console.log(res);
	})
	.catch(function(err){
		console.log(err);
});

5. 案例

5.1 案例需求

完成用户的查询与修改操作

5.2 数据库设计与表结构

CREATE DATABASE vuejsdemo;
USE vuejsdemo;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) DEFAULT NULL,
  `username` varchar(20) DEFAULT NULL,
  `PASSWORD` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `sex` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', '33', '张老师', '123', 'zzz@itcast.cn', '男 ');
INSERT INTO `user` VALUES ('2', '31', '刘老师', '123', 'lll@itcast.cn', '女');
INSERT INTO `user` VALUES ('3', '17', '赵工', '213', 'zg@itcast.cn', '女');
INSERT INTO `user` VALUES ('4', '40', '高管', '213', 'gg@itcast.cn', 'female');
INSERT INTO `user` VALUES ('5', '28', '李总', '312', 'lz@jxjt.com', 'male');
INSERT INTO `user` VALUES ('6', '34', '王董', '312', 'wd@jxjt.com', 'male');
INSERT INTO `user` VALUES ('7', '55', '孙老板', '4321', 'slb@xzjt.com', '男');
INSERT INTO `user` VALUES ('8', '19', '陈秘书', '4321', 'cms@xzjt.com', '女');

5.3 服务器端

5.3.1 配置文件

pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>9</maven.compiler.source>
    <maven.compiler.target>9</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>
  <dependencies> <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency> <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency> <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
  </dependencies>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>

  <!-- 手动指定 spring 配置文件位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。该间监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 -->
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <!-- 配置 spring mvc 的核心控制器 -->
  <servlet>
    <servlet-name>springmvcDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置初始化参数,用于读取 springmvc 的配置文件 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!-- 配置 servlet 的对象的创建时间点:应用加载时创建。取值只能是非 0 正整数,表示启动顺 序 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvcDispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- 配置 springMVC 编码过滤器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!-- 设置过滤器中的属性值 -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!-- 启动过滤器 -->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <!-- 过滤所有请求 -->
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置创建 spring 容器要扫描的包 -->
    <context:component-scan base-package="com.xmx.web.controller"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置 spring 创建容器时要扫描的包 -->
    <context:component-scan base-package="com.xmx">
        <!--制定扫包规则,不扫描@Controller 注解的 JAVA 类,其他的还是要扫描 -->
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置 MyBatis 的 Session 工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 配置 Mapper 扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xmx.dao"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 配置事务的通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<tx:attributes>
    		<tx:method name="*" propagation="REQUIRED" read-only="false"/>
    		<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
    	</tx:attributes>
    </tx:advice>
    <!-- 配置aop -->
    <aop:config>
    	<aop:pointcut expression="execution(* com.xmx.service.impl.*.*(..))" id="pt1"/>
    	<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>
</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/vuejsdemo
jdbc.username=root
jdbc.password=root

5.3.2 domain

User

package com.xmx.domain;

import java.io.Serializable;

/**
 * @Author Xumx
 * @Date 2021/3/15 11:09
 * @Version 1.0
 */
public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String sex;
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

5.3.3 dao

IUserDao

package com.xmx.dao;

import com.xmx.domain.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 用户的持久层接口
 * @Author Xumx
 * @Date 2021/3/15 11:13
 * @Version 1.0
 */
public interface IUserDao {

    /*
    *  查询用户列表
    * */
    @Select("select * from user")
    List<User> findAll();

    /*
    *   根据id查询
    * */
    @Select("select * from user where id = #{userId}")
    User findById(Integer userId);

    /*
    *   更新用户
    * */
    @Update("update user set username=#{username},password=#{password},age=#{age},sex=#{sex},email=#{email} where id = #{id}")
    void updateUser(User user);
}

5.3.4 service

IUserService

package com.xmx.service;

import com.xmx.domain.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @Author Xumx
 * @Date 2021/3/15 11:21
 * @Version 1.0
 */
public interface IUserService {
    /*
     *  查询用户列表
     * */
    List<User> findAll();

    /*
     *   根据id查询
     * */
    User findById(Integer userId);

    /*
     *   更新用户
     * */
    void updateUser(User user);
}

5.3.5 service.impl

IUserServiceImpl

package com.xmx.service.impl;

import com.xmx.dao.IUserDao;
import com.xmx.domain.User;
import com.xmx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Xumx
 * @Date 2021/3/15 11:23
 * @Version 1.0
 */
@Service
public class IUserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }
}

5.3.5 controller

UserController

package com.xmx.web.controller;

import com.xmx.domain.User;
import com.xmx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author Xumx
 * @Date 2021/3/15 11:52
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {

    @Autowired
    private IUserService userService;

    /*
    *   查询所有
    * */
    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }

    /*
    *   根据id查询
    * */
    @RequestMapping("/findById")
    public User findById(Integer id){
        return userService.findById(id);
    }

    /*
    *   更新
    * */
    @RequestMapping("/updateUser")
    public void updateUser(@RequestBody User user){
        userService.updateUser(user);
    }
}

5.4 客户端

5.4.1 user.html页面

<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>数据 - AdminLTE2定制版</title>
    <meta name="description" content="AdminLTE2定制版">
    <meta name="keywords" content="AdminLTE2定制版">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    
    <link rel="stylesheet" href="plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="plugins/ionicons/css/ionicons.min.css">
    <link rel="stylesheet" href="plugins/iCheck/square/blue.css">
    <link rel="stylesheet" href="plugins/morris/morris.css">
    <link rel="stylesheet" href="plugins/jvectormap/jquery-jvectormap-1.2.2.css">
    <link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
    <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css">
    <link rel="stylesheet" href="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
    <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">
    <link rel="stylesheet" href="plugins/treeTable/jquery.treetable.css">
    <link rel="stylesheet" href="plugins/treeTable/jquery.treetable.theme.default.css">
    <link rel="stylesheet" href="plugins/select2/select2.css">
    <link rel="stylesheet" href="plugins/colorpicker/bootstrap-colorpicker.min.css">
    <link rel="stylesheet" href="plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
    <link rel="stylesheet" href="plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="plugins/ionslider/ion.rangeSlider.css">
    <link rel="stylesheet" href="plugins/ionslider/ion.rangeSlider.skinNice.css">
    <link rel="stylesheet" href="plugins/bootstrap-slider/slider.css">
    <link rel="stylesheet" href="plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.css">
</head>

<body class="hold-transition skin-purple sidebar-mini">

<div class="wrapper" id="app">

    <!-- 页面头部 -->
    <header class="main-header">


        <!-- Logo -->
        <a href="all-admin-index.html" class="logo">
            <!-- mini logo for sidebar mini 50x50 pixels -->
            <span class="logo-mini"><b>数据</b></span>
            <!-- logo for regular state and mobile devices -->
            <span class="logo-lg"><b>数据</b>后台管理</span>
        </a>


        <!-- Header Navbar: style can be found in header.less -->
        <nav class="navbar navbar-static-top">
            <!-- Sidebar toggle button-->
            <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
                <span class="sr-only">Toggle navigation</span>
            </a>

            <div class="navbar-custom-menu">
                <ul class="nav navbar-nav">
                    <!-- Messages: style can be found in dropdown.less-->
                    <li class="dropdown messages-menu">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                            <i class="fa fa-envelope-o"></i>
                            <span class="label label-success">4</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li class="header">你有4个邮件</li>
                            <li>
                                <!-- inner menu: contains the actual data -->
                                <ul class="menu">
                                    <li>
                                        <!-- start message -->
                                        <a href="#">
                                            <div class="pull-left">
                                                <img src="img/user2-160x160.jpg" class="img-circle" alt="User Image">
                                            </div>
                                            <h4>
                                                系统消息
                                                <small><i class="fa fa-clock-o"></i> 5 分钟前</small>
                                            </h4>
                                            <p>欢迎登录系统?</p>
                                        </a>
                                    </li>
                                    <!-- end message -->
                                    <li>
                                        <a href="#">
                                            <div class="pull-left">
                                                <img src="img/user3-128x128.jpg" class="img-circle" alt="User Image">
                                            </div>
                                            <h4>
                                                团队消息
                                                <small><i class="fa fa-clock-o"></i> 2 小时前</small>
                                            </h4>
                                            <p>你有新的任务了</p>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <div class="pull-left">
                                                <img src="img/user4-128x128.jpg" class="img-circle" alt="User Image">
                                            </div>
                                            <h4>
                                                Developers
                                                <small><i class="fa fa-clock-o"></i> Today</small>
                                            </h4>
                                            <p>Why not buy a new awesome theme?</p>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <div class="pull-left">
                                                <img src="img/user3-128x128.jpg" class="img-circle" alt="User Image">
                                            </div>
                                            <h4>
                                                Sales Department
                                                <small><i class="fa fa-clock-o"></i> Yesterday</small>
                                            </h4>
                                            <p>Why not buy a new awesome theme?</p>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <div class="pull-left">
                                                <img src="img/user4-128x128.jpg" class="img-circle" alt="User Image">
                                            </div>
                                            <h4>
                                                Reviewers
                                                <small><i class="fa fa-clock-o"></i> 2 days</small>
                                            </h4>
                                            <p>Why not buy a new awesome theme?</p>
                                        </a>
                                    </li>
                                </ul>
                            </li>
                            <li class="footer"><a href="#">See All Messages</a></li>
                        </ul>
                    </li>
                    <!-- Notifications: style can be found in dropdown.less -->
                    <li class="dropdown notifications-menu">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                            <i class="fa fa-bell-o"></i>
                            <span class="label label-warning">10</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li class="header">你有10个新消息</li>
                            <li>
                                <!-- inner menu: contains the actual data -->
                                <ul class="menu">
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-users text-aqua"></i> 5 new members joined today
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-warning text-yellow"></i> Very long description here that
                                            may not
                                            fit into the page and may cause design problems
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-users text-red"></i> 5 new members joined
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-shopping-cart text-green"></i> 25 sales made
                                        </a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <i class="fa fa-user text-red"></i> You changed your username
                                        </a>
                                    </li>
                                </ul>
                            </li>
                            <li class="footer"><a href="#">View all</a></li>
                        </ul>
                    </li>
                    <!-- Tasks: style can be found in dropdown.less -->
                    <li class="dropdown tasks-menu">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                            <i class="fa fa-flag-o"></i>
                            <span class="label label-danger">9</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li class="header">你有9个新任务</li>
                            <li>
                                <!-- inner menu: contains the actual data -->
                                <ul class="menu">
                                    <li>
                                        <!-- Task item -->
                                        <a href="#">
                                            <h3>
                                                Design some buttons
                                                <small class="pull-right">20%</small>
                                            </h3>
                                            <div class="progress xs">
                                                <div class="progress-bar progress-bar-aqua" style="width: 20%"
                                                     role="progressbar" aria-valuenow="20" aria-valuemin="0"
                                                     aria-valuemax="100">
                                                    <span class="sr-only">20% Complete</span>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <!-- end task item -->
                                    <li>
                                        <!-- Task item -->
                                        <a href="#">
                                            <h3>
                                                Create a nice theme
                                                <small class="pull-right">40%</small>
                                            </h3>
                                            <div class="progress xs">
                                                <div class="progress-bar progress-bar-green" style="width: 40%"
                                                     role="progressbar" aria-valuenow="20" aria-valuemin="0"
                                                     aria-valuemax="100">
                                                    <span class="sr-only">40% Complete</span>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <!-- end task item -->
                                    <li>
                                        <!-- Task item -->
                                        <a href="#">
                                            <h3>
                                                Some task I need to do
                                                <small class="pull-right">60%</small>
                                            </h3>
                                            <div class="progress xs">
                                                <div class="progress-bar progress-bar-red" style="width: 60%"
                                                     role="progressbar" aria-valuenow="20" aria-valuemin="0"
                                                     aria-valuemax="100">
                                                    <span class="sr-only">60% Complete</span>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <!-- end task item -->
                                    <li>
                                        <!-- Task item -->
                                        <a href="#">
                                            <h3>
                                                Make beautiful transitions
                                                <small class="pull-right">80%</small>
                                            </h3>
                                            <div class="progress xs">
                                                <div class="progress-bar progress-bar-yellow" style="width: 80%"
                                                     role="progressbar" aria-valuenow="20" aria-valuemin="0"
                                                     aria-valuemax="100">
                                                    <span class="sr-only">80% Complete</span>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <!-- end task item -->
                                </ul>
                            </li>
                            <li class="footer">
                                <a href="#">View all tasks</a>
                            </li>
                        </ul>
                    </li>
                    <!-- User Account: style can be found in dropdown.less -->
                    <li class="dropdown user user-menu">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                            <img src="img/user2-160x160.jpg" class="user-image" alt="User Image">
                            <span class="hidden-xs">张猿猿</span>
                        </a>
                        <ul class="dropdown-menu">
                            <!-- User image -->
                            <li class="user-header">
                                <img src="img/user2-160x160.jpg" class="img-circle" alt="User Image">

                                <p>
                                    张猿猿 - 数据管理员
                                    <small>最后登录 11:20AM</small>
                                </p>
                            </li>

                            <!-- Menu Footer-->
                            <li class="user-footer">
                                <div class="pull-left">
                                    <a href="#" class="btn btn-default btn-flat">修改密码</a>
                                </div>
                                <div class="pull-right">
                                    <a href="#" class="btn btn-default btn-flat">注销</a>
                                </div>
                            </li>
                        </ul>
                    </li>

                </ul>
            </div>
        </nav>
    </header>
    <!-- 页面头部 /-->

    <!-- 导航侧栏 -->
    <aside class="main-sidebar">
        <!-- sidebar: style can be found in sidebar.less -->
        <section class="sidebar">
            <!-- Sidebar user panel -->
            <div class="user-panel">
                <div class="pull-left image">
                    <img src="img/user2-160x160.jpg" class="img-circle" alt="User Image">
                </div>
                <div class="pull-left info">
                    <p>张猿猿</p>
                    <a href="#"><i class="fa fa-circle text-success"></i> 在线</a>
                </div>
            </div>
            <!-- search form -->
            <!--<form action="#" method="get" class="sidebar-form">
        <div class="input-group">
            <input type="text" name="q" class="form-control" placeholder="搜索...">
            <span class="input-group-btn">
            <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
            </button>
          </span>
        </div>
    </form>-->
            <!-- /.search form -->


            <!-- sidebar menu: : style can be found in sidebar.less -->
            <ul class="sidebar-menu">
                <li class="header">菜单</li>

                <li id="admin-index"><a href="all-admin-index.html"><i class="fa fa-dashboard"></i> <span>首页</span></a>
                </li>

                <!-- 菜单 -->


                <li class="treeview">
                    <a href="#">
                        <i class="fa fa-folder"></i> <span>用户管理</span>
                        <span class="pull-right-container">
                        <i class="fa fa-angle-left pull-right"></i>
                    </span>
                    </a>
                    <ul class="treeview-menu">

                        <li id="admin-login">
                            <a href="all-admin-login.html">
                                <i class="fa fa-circle-o"></i> 查询所有用户
                            </a>
                        </li>

                    </ul>
                </li>

                <!-- 菜单 /-->
            </ul>
        </section>
        <!-- /.sidebar -->
    </aside>
    <!-- 导航侧栏 /-->

    <!-- 内容区域 -->
    <!-- @@master = admin-layout.html-->
    <!-- @@block = content -->

    <div class="content-wrapper">

        <!-- 内容头部 -->
        <section class="content-header">
            <h1>
                数据管理
                <small>数据列表</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
                <li><a href="#">数据管理</a></li>
                <li class="active">数据列表</li>
            </ol>
        </section>
        <!-- 内容头部 /-->

        <!-- 正文区域 -->
        <section class="content">

            <!-- .box-body -->
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">列表</h3>
                </div>

                <div class="box-body">

                    <!-- 数据表格 -->
                    <div class="table-box">

                        <!--工具栏-->
                        <div class="pull-left">
                            <div class="form-group form-inline">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-default" title="新建"><i
                                            class="fa fa-file-o"></i> 新建
                                    </button>
                                    <button type="button" class="btn btn-default" title="删除"><i
                                            class="fa fa-trash-o"></i> 删除
                                    </button>
                                    <button type="button" class="btn btn-default" title="开启"><i class="fa fa-check"></i>
                                        开启
                                    </button>
                                    <button type="button" class="btn btn-default" title="屏蔽"><i class="fa fa-ban"></i>
                                        屏蔽
                                    </button>
                                    <button type="button" class="btn btn-default" title="刷新"><i
                                            class="fa fa-refresh"></i> 刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="box-tools pull-right">
                            <div class="has-feedback">
                                <input type="text" class="form-control input-sm" placeholder="搜索">
                                <span class="glyphicon glyphicon-search form-control-feedback"></span>
                            </div>
                        </div>
                        <!--工具栏/-->

                        <!--数据列表-->
                        <table id="dataList" class="table table-bordered table-striped table-hover dataTable">
                            <thead>
                            <tr>
                                <th class="" style="padding-right:0px;">
                                    <input id="selall" type="checkbox" class="icheckbox_square-blue">
                                </th>
                                <th class="sorting_asc">ID</th>
                                <th class="sorting_desc">用户名</th>
                                <th class="sorting_asc sorting_asc_disabled">密码</th>
                                <th class="sorting_desc sorting_desc_disabled">性别</th>
                                <th class="sorting">年龄</th>
                                <th class="text-center sorting">邮箱</th>
                                <th class="text-center">操作</th>
                            </tr>
                            </thead>
                            <tbody>

                            <tr v-for="u in userList">
                                <td><input name="ids" type="checkbox"></td>
                                <td>{{u.id}}</td>
                                <td>{{u.username}}
                                </td>
                                <td>{{u.password}}</td>
                                <td>{{u.sex}}</td>
                                <td>{{u.age}}</td>
                                <td class="text-center">{{u.email}}</td>
                                <td class="text-center">
                                    <button type="button" class="btn bg-olive btn-xs">详情</button>
                                    <button type="button" class="btn bg-olive btn-xs" @click="findById(u.id)">编辑</button>
                                </td>
                            </tr>

                            </tbody>
                            <!--模态窗口-->
                            <div class="tab-pane" id="tab-model">

                                <div id="myModal" class="modal modal-primary" role="dialog">
                                    <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">×</span></button>
                                                <h4 class="modal-title">用户信息</h4>
                                            </div>
                                            <div class="modal-body">

                                                <div class="box-body">
                                                    <div class="form-horizontal">


                                                        <div class="form-group">
                                                            <label class="col-sm-2 control-label">用户名:</label>
                                                            <div class="col-sm-5">
                                                                <input type="text" class="form-control" v-model="user.username">
                                                            </div>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="col-sm-2 control-label">密码:</label>
                                                            <div class="col-sm-5">
                                                                <input type="text" class="form-control" v-model="user.password">
                                                            </div>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="col-sm-2 control-label">性别:</label>
                                                            <div class="col-sm-5">
                                                                <input type="text" class="form-control" v-model="user.sex">
                                                            </div>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="col-sm-2 control-label">年龄:</label>
                                                            <div class="col-sm-5">
                                                                <input type="text" class="form-control" v-model="user.age">
                                                            </div>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="col-sm-2 control-label">邮箱:</label>
                                                            <div class="col-sm-5">
                                                                <input type="text" class="form-control" v-model="user.email">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-outline" data-dismiss="modal">关闭</button>
                                                <button type="button" class="btn btn-outline" data-dismiss="modal" @click="update">修改</button>
                                            </div>
                                        </div>
                                        <!-- /.modal-content -->
                                    </div>

                                    <!-- /.modal-dialog -->
                                </div>
                                <!-- /.modal -->
                            </div>
                            <!--模态窗口/-->
                        </table>
                        <!--数据列表/-->

                        <!--工具栏-->
                        <div class="pull-left">
                            <div class="form-group form-inline">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-default" title="新建"><i
                                            class="fa fa-file-o"></i> 新建
                                    </button>
                                    <button type="button" class="btn btn-default" title="删除"><i
                                            class="fa fa-trash-o"></i> 删除
                                    </button>
                                    <button type="button" class="btn btn-default" title="开启"><i class="fa fa-check"></i>
                                        开启
                                    </button>
                                    <button type="button" class="btn btn-default" title="屏蔽"><i class="fa fa-ban"></i>
                                        屏蔽
                                    </button>
                                    <button type="button" class="btn btn-default" title="刷新"><i
                                            class="fa fa-refresh"></i> 刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="box-tools pull-right">
                            <div class="has-feedback">
                                <input type="text" class="form-control input-sm" placeholder="搜索">
                                <span class="glyphicon glyphicon-search form-control-feedback"></span>
                            </div>
                        </div>
                        <!--工具栏/-->



                    </div>
                    <!-- 数据表格 /-->


                </div>
                <!-- /.box-body -->

                <!-- .box-footer-->
                <div class="box-footer">
                    <div class="pull-left">
                        <div class="form-group form-inline">
                            总共2 页,共14 条数据。 每页
                            <select class="form-control">
                                <option>1</option>
                                <option>2</option>
                                <option>3</option>
                                <option>4</option>
                                <option>5</option>
                            </select> 条
                        </div>
                    </div>

                    <div class="box-tools pull-right">
                        <ul class="pagination">
                            <li>
                                <a href="#" aria-label="Previous">首页</a>
                            </li>
                            <li><a href="#">上一页</a></li>
                            <li><a href="#">1</a></li>
                            <li><a href="#">2</a></li>
                            <li><a href="#">3</a></li>
                            <li><a href="#">4</a></li>
                            <li><a href="#">5</a></li>
                            <li><a href="#">下一页</a></li>
                            <li>
                                <a href="#" aria-label="Next">尾页</a>
                            </li>
                        </ul>
                    </div>

                </div>
                <!-- /.box-footer-->


            </div>

        </section>
        <!-- 正文区域 /-->

    </div>
    <!-- @@close -->
    <!-- 内容区域 /-->

    <!-- 底部导航 -->
    <footer class="main-footer">
        <div class="pull-right hidden-xs">
            <b>Version</b> 1.0.8
        </div>
        <strong>Copyright © 2014-2017 <a href="http://www.itcast.cn">研究院研发部</a>.</strong> All rights reserved.
    </footer>
    <!-- 底部导航 /-->

</div>


<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="plugins/jQueryUI/jquery-ui.min.js"></script>
<script>
    $.widget.bridge('uibutton', $.ui.button);
</script>
<script src="plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="plugins/raphael/raphael-min.js"></script>
<script src="plugins/morris/morris.min.js"></script>
<script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<script src="plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="plugins/knob/jquery.knob.js"></script>
<script src="plugins/daterangepicker/moment.min.js"></script>
<script src="plugins/daterangepicker/daterangepicker.js"></script>
<script src="plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<script src="plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
<script src="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<script src="plugins/fastclick/fastclick.js"></script>
<script src="plugins/iCheck/icheck.min.js"></script>
<script src="plugins/adminLTE/js/app.min.js"></script>
<script src="plugins/treeTable/jquery.treetable.js"></script>
<script src="plugins/select2/select2.full.min.js"></script>
<script src="plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
<script src="plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
<script src="plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
<script src="plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
<script src="plugins/bootstrap-markdown/js/markdown.js"></script>
<script src="plugins/bootstrap-markdown/js/to-markdown.js"></script>
<script src="plugins/ckeditor/ckeditor.js"></script>
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js"></script>
<script src="plugins/chartjs/Chart.min.js"></script>
<script src="plugins/flot/jquery.flot.min.js"></script>
<script src="plugins/flot/jquery.flot.resize.min.js"></script>
<script src="plugins/flot/jquery.flot.pie.min.js"></script>
<script src="plugins/flot/jquery.flot.categories.min.js"></script>
<script src="plugins/ionslider/ion.rangeSlider.min.js"></script>
<script src="plugins/bootstrap-slider/bootstrap-slider.js"></script>
<script src="plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.js"></script>
<script src="plugins/bootstrap-datetimepicker/locales/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="js/vuejs-2.5.16.js"></script>
<script src="js/axios-0.18.0.js"></script>
<script src="js/user.js"></script>
<script>
    $(document).ready(function () {
        // 选择框
        $(".select2").select2();

        // WYSIHTML5编辑器
        $(".textarea").wysihtml5({
            locale: 'zh-CN'
        });
    });


    // 设置激活菜单
    function setSidebarActive(tagUri) {
        var liObj = $("#" + tagUri);
        if (liObj.length > 0) {
            liObj.parent().parent().addClass("active");
            liObj.addClass("active");
        }
    }


    $(document).ready(function () {

        // 激活导航位置
        setSidebarActive("admin-datalist");

        // 列表按钮
        $("#dataList td input[type='checkbox']").iCheck({
            checkboxClass: 'icheckbox_square-blue',
            increaseArea: '20%'
        });
        // 全选操作
        $("#selall").click(function () {
            var clicks = $(this).is(':checked');
            if (!clicks) {
                $("#dataList td input[type='checkbox']").iCheck("uncheck");
            } else {
                $("#dataList td input[type='checkbox']").iCheck("check");
            }
            $(this).data("clicks", !clicks);
        });
    });
</script>
</body>

</html>

5.4.2 user.js页面

new Vue({
    el:"#app",
    data:{
        user:{
            id:"",
            username:"",
            password:"",
            email:"",
            age:"",
            sex:""
        },
        userList:[]
    },
    methods:{
        findAll:function (){
            //在当前方法中定义一个变量,表明是vue对象
            var _this = this;
            axios.get('/user/findAll.do')
                .then(function (response){
                    //handle success
                    _this.userList = response.data;  //响应数据给userList赋值
                    console.log(response);
                })
                .cache(function (error){
                    //handle error
                    console.log(error);
                })
        },
        findById:function (userid){
            //在当前方法中定义一个变量,表明是vue对象
            var _this = this;
            axios.get('/user/findById.do',{params:{id:userid}})
                .then(function (response){
                    //handle success
                    _this.user = response.data;  //响应数据给userList赋值
                    $("#myModal").modal("show");
                })
                .cache(function (error){
                    //handle error
                    console.log(error);
                })
        },
        update:function (user){//post请求
            var _this = this;
            axios.post('/user/updateUser.do',_this.user)
                .then(function (response){
                    _this.findAll();
                })
                .cache(function (error){
                    //handle error
                    console.log(error);
                })

        }
    },
    created(){   //当我们页面加载的时候触发请求,查询所有
        this.findAll();
    }
});

上述案例项目已上传至码云添加链接描述

所遇问题与解决方案

问题1

vue使用v-on绑定事件时可以正常使用,但是报错namespace ‘v-on’ is not bound

Vue嵌入Java代码 vue java_html_06

解决方案1

在setting->Editor->inspections->XML中去掉Unbound XML namespace prefix后面的对钩。问题解决。

Vue嵌入Java代码 vue java_java_07

解决方案2

@事件名称 就是 v-on:事件名称的简写方式
@mouseover 就等同于 v-on:mouseover
这样也可以解决报红问题。

v-on简写方式

<!-- 完整语法 -->
<a v-on:click="doSomething">...</a>
<!-- 缩写 -->
<a @click="doSomething">...</a>