文章目录

  • 一、为什么要用Vue-cli?
  • 二、Vue-cli的环境搭建
    • 下载node.js
      • 为什么用vue-cli之前,要下载node.js?
      • 下载node.js步骤
      • 设置缓存node_cache、全局模块node_global、安装cnpm(淘宝镜像)
      • 在系统的环境变量中配置node_global和node_modules
      • 安装Vue和vue-cli脚手架
  • 三、vue-cli 项目创建
  • 四、项目中的目录结构解析
  • 五、启动在vue-cli脚手架中的vue项目
  • 六、深度解析项目各目录中的文件
    • config目录下的index.js文件(看源码)
    • router目录中的index.js文件(源码分析)
    • App.vue文件--根组件
    • main.js文件
    • index.html 主页面
    • 流程分析图
  • 七、自己创建一个vue对象
    • vue语法在Vue-cli脚手架的使用
    • css、js样式的导入方式
    • js对象的引入
  • 八、在vue-cli脚手架中导入Element-UI及使用
    • Element-UI的安装
    • Element-UI的使用教程
  • 九、深度解析vue-router路由
    • 为什么要用router?
    • vue-router实现原理
    • vue-router 路由导航
      • 编程式导航:
      • push() 和 replace()的区别
      • 编程式导航传参
  • 十、vue-cli域名代理
    • 什么是跨域问题?
    • 什么是域名代理?
    • 解决域名问题的方式有两种:
    • axios的安装
  • 十一、做一个前后端邮箱登录的案列
    • 前端Vue-cli脚手架
      • 使用Element-UI搭建一个前端的登录页面
    • 后端springBoot框架
      • 导入依赖
      • 在QQ邮箱中,去申请授权
      • 在application.propertise 配置文件中配置发送人(**就是你**)邮箱信息
      • 创建实体类ResultVo,用于返回信息
      • 在service层编写邮件发送逻辑
      • controller层控制URL请求
      • 在Postmanr工具软件中验证是否有邮件发送
      • springBoot整合Redis
    • 编写前端js,发送url请求;获取后端返回的数据

一、为什么要用Vue-cli?

好处:首先Vue-lic是开发工具,为了让开发者开箱即用快速开发;跟springBoot一样约定大于配置

二、Vue-cli的环境搭建

下载node.js

为什么用vue-cli之前,要下载node.js?

  • 准确的说,在使用vue-cli搭建项目时需要node.js;你也可以创建一个HTML文件,引入vue
<script src = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  • 使用node.js方便打包部署解析vue组件启动测试服务器localhost
  • 使用vue+node.js会提高开发效率

下载node.js步骤

  • node.js官方网址
  • 下载好了就安装,没啥注意事项,一直点下一步就行(建议不要安装在系统盘C:
  • 安装完毕,是这样的目录结构
  • 在这个目录中,新建两个目录:node_cachenode_global
  • 问题来了,为啥必须要这两个目录?

node_cache —>缓存目录 | node_global ----> 全局目录 目的:将安装的全局组件放在node_global中;将一些缓存放在node_cache中;你不创建这两个目录也没关系,node.js会把这些组件和缓存放在默认的系统盘中(系统盘内存满了,电脑启动会很慢

设置缓存node_cache、全局模块node_global、安装cnpm(淘宝镜像)

  • 在当前目录的浏览栏中输入cmd,打开命令提示符

npm config set cache “node_cache目录的绝对路径”
npm config set prefix “node_global目录的绝对路径”
npm install -g cnpm --registry=https://registry.npm.taobao.org

为什么要安装淘宝镜像?

国外的下载,很慢;安装了淘宝镜像,就下载很快

因为我这边是安装过了的,所以,跟你们的显示有些不一致;只要不报error,就是安装好了的

在系统的环境变量中配置node_global和node_modules

配置系统变量的目的是什么?比如,JDK

先思考这样一个问题:为什么要叫做系统变量、环境变量?我们都理解全局变量,局部变量。全局变量的使用范围是类;局部变量的使用范围是方法体;那系统变量的使用范围就是一整个操作系统。变量值是绝对地址。

安装Vue和vue-cli脚手架

安装vue

cnpm install vue -g

安装vue命令行工具Vue-cli

cnpm install vue-cli -g

三、vue-cli 项目创建

  • 打开一个你想放项目的文件目录,输入cmd

vue init webpack 项目名 项目名必须是英文

四、项目中的目录结构解析

  • 在Hbuider X 3.4.18软件中打开项目
  • HBuider X官方网址

目录 存放的资源
build 存放webpack的相关配置;当输入命令 npm run dev 加载配置文件,启动服务(了解即可)
config 项目的相关配置,其中有个文件index.js ,其内配置监听端口
node_modules 存放项目依赖包;比如,后续的Element-UI就是一个依赖包;进入项目目录,输入cmd进入终端;输入命令 npm install 依赖包名
src
index.html 主页

五、启动在vue-cli脚手架中的vue项目

  • 1.在项目路径下,cmd,输入 安装工程依赖模块 命令

cnpm install

  • 2.安装axios依赖模块

cnpm install axios

  • 3.启动项目

cnpm run dev

  • 4.千万别关闭刚刚那个终端,它现在相当于一个服务器;关闭可以使用 ctrl+c 来退出

此时,可以在浏览器输入url: localhost:8080/#/
若是刚刚的终端关闭了,就搜不到该url访问地址

六、深度解析项目各目录中的文件

config目录下的index.js文件(看源码)

'use strict'
const path = require('path')module.exports = {dev: {// static 静态资源路径 对应static目录 assetsSubDirectory: 'static',// '/' 代表 localhost:8080/assetsPublicPath: '/',//proxytable 域名代理 | 这里很重要!{}这里面是配置域名的!即:解决域名冲突问题;以后在说 proxyTable: {},// 服务器的启动地址和端口;改了的话,先保存index.js,然后重新启动服务器;一般后端端口是8080,所以这里要改一下 8000;//# ---> 相当于存储在浏览器上,下次再访问相同的url;就不需要进入node.js的vue-cli脚手架这个项目里//http协议的默认端口号为 80 ;如果你在这里改为了80端口;url就可以不写端口:localhost/#///当然你得确认是 http协议 还是 https协议  https 默认端口 443host: 'localhost', // can be overwritten by process.env.HOSTport: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined//是否自动打开浏览器autoOpenBrowser: false,//热部署 修改了非配置文件的内容时,就不需要重新启动服务器了errorOverlay: true,//若有Error时,服务器会通知你报错的信息notifyOnErrors: true,poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-/*** Source Maps*/// https://webpack.js.org/configuration/devtool/#developmentdevtool: 'cheap-module-eval-source-map',// If you have problems debugging vue-files in devtools,// set this to false - it *may* help// https://vue-loader.vuejs.org/en/options.html#cachebustingcacheBusting: true,cssSourceMap: true},build: {// Template for index.htmlindex: path.resolve(__dirname, '../dist/index.html'),// PathsassetsRoot: path.resolve(__dirname, '../dist'),assetsSubDirectory: 'static',assetsPublicPath: '/',productionSourceMap: true,// https://webpack.js.org/configuration/devtool/#productiondevtool: '#source-map',// Gzip off by default as many popular static hosts such as// Surge or Netlify already gzip all static assets for you.// Before setting to `true`, make sure to:// npm install --save-dev compression-webpack-pluginproductionGzip: false,productionGzipExtensions: ['js', 'css'],// Run the build command with an extra argument to// View the bundle analyzer report after build finishes:// `npm run build --report`// Set to `true` or `false` to always turn it on or offbundleAnalyzerReport: process.env.npm_config_report}
}

router目录中的index.js文件(源码分析)

import Vue from 'vue'
import Router from 'vue-router'
//@ 表示的是:src目录  这句话的意思是:我导入了一个在src/components/下的Helloworld.vue对象;设置别名为 HelloWorld
import HelloWorld from '@/components/HelloWorld'Vue.use(Router)export default new Router({//路由转发器routes: [{//这个 '/'  就是url中的 localhost:8000/#/   后面的那个'/'path: '/',//一个标识而已,可以随便写,但必须唯一name: 'HelloWorld',//component: XXX  映射上面的import XXX(别名) component: HelloWorld}]
})

App.vue文件–根组件

<template><div id="app"><img src="./assets/logo.png">//其他的都不重要,重要的就这一句: <router-view/>  路由视图//这一句的功能: 将src/components/目录下的所有vue对象,写到这里来//直白的说:<router-view/> 就是src下de所有vue<router-view/></div>
</template><script>
export default {name: 'App'
}
</script><style>
#app {font-family: 'Avenir', Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>

main.js文件

//1.只要没有@的,均是第三方组件
import Vue from 'vue'
//这句就是导入刚刚的 App.vue文件
import App from './App'
//这个是router 路由 第三方插件 跟router目录没有关系
import router from './router'Vue.config.productionTip = false/* eslint-disable no-new */
new Vue({//这个 el:'#app'  指的是,index.html中的id= app ;等会就到index.html文件了el: '#app',// 上面的别名router,// 映射到上面的别名 App,别名App再映射到 App.vuecomponents: { App },//表示一个 模板template: '<App/>'
})

index.html 主页面

<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>myproject</title></head><body>//对应main.js中的 el:"#app"<div id="app"></div><!-- built files will be auto injected --></body>
</html>

流程分析图

(router.js记错了,应该是router目录下的 index.js)

七、自己创建一个vue对象

注意

若你要删除HelloWorld.vue时,记得在路由index.js中把 import HelloWorld from ‘@/component/HelloWorld’ 一起删除,不然报error

MyFirst.vue

<template><div>你好,陌生人!</div>
</template><script>
</script><style>
</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'import MyFirst from '@/components/MyFirst'
Vue.use(Router)export default new Router({routes: [{path: '/myFirst',name: 'myFirst',component: MyFirst}]
})

记得保存哟,因为有: errorOverlay: true 所以不必再重新启动服务器;输入url:localhost:8000/#/myFirst
在template标签中,必须要有个div标签作为内容的根标签

vue语法在Vue-cli脚手架的使用

再次改变MyFirst.vue

<template><div>你好,陌生人!{{info}}<button type="button" @click="test()">点击</button></div>
</template><script>
//这里也是自动导入到App.vue的意思export default{name:"M",//组件描述//数据 这里可以使用axios 从后端传输数据到data()中data(){return{info:"明天见",}},//函数methods:{test(){alert(1)}},//钩子函数mounted() {console.log("钩子函数");}}
</script><style>
</style>

App.vue

<template><router-view/>
</template><script>
</script><style>
</style>

显示效果

css、js样式的导入方式

方式一

  • 在static目录中粘贴query.js或自定义的css样式;然后在index.html文件中导入
<script src="static/js/jquery-3.5.1.js"></script>

方式二

  • 在src目录下的assets目录下自定义css样式,然后在App.vue文件中导入
<template><router-view/>
</template><script>
</script><style>@import url("assets/css/test.css");
</style>
  • 在src目录下的assets目录下自定义js样式,然后在vue对象中的script标签中导入
<srcipt>
import {函数名1,函数名2} from '../../test.js'
</srcipt>

js对象的引入

  • 在assets目录下创建一个js文件;且只能在该文件中写一个user对象
/*** 一个user对象*/
var user = {name:"行",show:function(){alert("我叫"+this.name);}
}//导出外部接口对象
export default user
  • 在指定的vue对象中导入,即可
import user from '../../src/assets/user.js'

八、在vue-cli脚手架中导入Element-UI及使用

Element-UI的安装

  • Element-UI官方网址(官方就有很详尽的使用教程)
  • 在当前项目下,输入cmd,打开终端,输入命令:npm i element-ui -S

  • Element-UI导入后,就应该在main.js中配置引用Element-UI
import Vue from 'vue'
import App from './App'
import router from './router'
//===>
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
//===>
Vue.config.productionTip = false/* eslint-disable no-new */
new Vue({el: '#app',router,components: { App },template: '<App/>'
})
  • 随便扒一个Element-UI官网的样式按钮
 <el-button type="primary">主要按钮</el-button><el-button type="success">成功按钮</el-button><el-button type="info">信息按钮</el-button><el-button type="warning">警告按钮</el-button><el-button type="danger">危险按钮</el-button>
  • 添加在MyFirst.vue文件中
<template><div id="my">你好,陌生人!{{info}}<button type="button" @click="test()">点击1</button><el-button type="success">成功按钮</el-button></div>
</template><script>//引入user对象
import user from '../../src/assets/user.js'export default{name:"M",data(){return{info:"明天见",}},methods:{test(){user.show();}},mounted() {console.log("钩子函数");}}
</script><style></style>

注意

在导入Element-UI后,要重新启动服务器;且服务器可能报错
报错信息: This is probably not a problem with npm. There is likely additional logging output above

解决方案

  • 打开当前项目目录,删除node_modules目录和package-lock.json文件
  • 运行命令: npm install
  • 启动命令:npm run dev

Element-UI的使用教程

  • Element-UI官方网址(官方就有很详尽的使用教程)
  • 我这里推荐大家去Element-UI官网学习Element-UI的使用教程;更原味嘛

九、深度解析vue-router路由

为什么要用router?

通过之前的学习,大家也应该发现了一个蹊跷的地方: index.html 静态页面就只有一个!!
当你的项目准备打包时,运行npm run build命令,就会生成dist文件夹,这里面只有静态资源和一个index.html页面
之前的是用a标签进行超链接来实现页面的跳转;但现在页面就一个,所以引入了router路由

vue-router实现原理

SPA(single page application):单一页面应用程序,只有一个index.html页面;它在加载页面时,不会加载整个页面,而是只更新某个指定的容器中的内容;即更新视图而不重新请求页面

vue-router vue-router在实现单页面前端路由时,提供了两种方式:Hash模式和History模式;根据mode参数来决定采用哪一种方式。

  • Hash模式

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。 hash(#)是URL 的锚点,代表的是网页中的一个位置,单单改变#后的部分,浏览器只会滚动到相应位置,不会重新加载网页,也就是说hash 出现在 URL 中,但不会被包含在 http 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面;同时每一次改变#后的部分,都会在浏览器的访问历史中增加一个记录,使用”后退”按钮,就可以回到上一个位置;所以说Hash模式通过锚点值的改变,根据不同的值,渲染指定DOM位置的不同数据。hash 模式的原理是 onhashchange 事件(监测hash值变化),可以在 window 对象上监听这个事件。

  • History模式

由于hash模式会在url中自带#,如果不想要很丑的 hash,我们可以用路由的 history 模式,只需要在配置路由规则时,加入"mode: ‘history’"

router/index.js

import Vue from 'vue'
import Router from 'vue-router'import MyFirst from '@/components/MyFirst'
Vue.use(Router)export default new Router({//history模式,不用再加 ‘#’mode:"history",routes: [{path: '/myFirst',name: 'myFirst',component: MyFirst}]
})

vue-router 路由导航

编程式导航:

第一种方式: 使用 this.$router.replace()

myFirst.vue

<template><div id="my">你好,陌生人!<button type="button" @click="test()">点击1</button><el-button type="success" @click="replace()">成功按钮</el-button></div>
</template><script>export default{name:"myF",data(){return{}},methods:{replace(){this.$router.replace({name:"mySecond"})}},}
</script>

通过this.$router.replace({name:“vue在路由上的组件描述name值”}) 可以实现由当前页面跳转到指定页面

mySecond.vue

<template><div><el-button type="success" @click="replace()">成功按钮</el-button></div>
</template><script>export default{name:"myS",data(){return{}},methods:{replace(){this.$router.replace("/myFirst")}},}
</script>
<style>
</style>

通过this.$router.replace(“/指定vue对象在路由上的path值”) 可以实现由当前页面跳转到指定页面

router/index.js

import Vue from 'vue'
import Router from 'vue-router'import MyFirst from '@/components/MyFirst'
import MySecond from '@/components/MySecond'
Vue.use(Router)export default new Router({mode:"history",routes: [{path: '/myFirst',name: 'myFirst',component: MyFirst},{path: '/mySecond',name: 'mySecond',component: MySecond}]
})

方式二:使用this.$router.push()

使用方法与 **this.$router.replace()**一致;也是以path\name为参数进行导航至目标url或vue对象

push() 和 replace()的区别
  • 使用push方法的跳转会向 history 栈添加一个新的记录,当我们点击浏览器的返回按钮时可以看到之前的页面
  • 使用replace方法不会向 history 添加新记录,而是替换掉当前的 history 记录,即当replace跳转到的网页后,‘后退’按钮不能查看之前的页面

至于用哪种方法,视需求文档而定;比如,有些网页不希望url倒退,就可以使用replace()

编程式导航传参
  • myFirst.vue
<template><div id="my">你好,陌生人!<button type="button" @click="test()">点击1</button><el-button type="success" @click="replace()">成功按钮</el-button></div>
</template><script>export default{name:"myF",data(){return{myName:"hang"}},methods:{replace(){this.$router.replace({name:"mySecond",//参数必须在query:{}内,且在return{}中引用key;query:{"one":this.myName},});}},}
</script>
<style>
</style>
  • Mysecond.vue
<template><div><el-button type="success" @click="replace()">成功按钮</el-button>//直接接收即可, $router.query.one<span>{{$route.query.one}}</span></div>
</template><script>export default{name:"myS",data(){return{}},methods:{replace(){this.$router.replace("/myFirst")}},}
</script>
<style>
</style>

十、vue-cli域名代理

什么是跨域问题?

当一个请求URL的协议、域名、端口三者中的任意一个与当前的URL不同,即为跨域
直白的说:http:localhost:8000/XX 的前端URL去访问后端的http:localhost:8080/XX 肯定不行呀;端口都不一样;只有协议、域名、端口一样的才是一家人,才能进一家门

什么是域名代理?

即:把你前端URL的协议、端口、域名很粗暴的转换为后端的协议、端口、域名一致

解决域名问题的方式有两种:

  • 在后端springboot的跨域配置类中,配置addCorsMappings
@Configuration
public class CrossConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**")/*所有的当前站点的请求地址,都支持跨域访问*/.allowedOrigins("*")/*所有的外部域都可跨域访问*/.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")/*哪些请求 需要跨域配置*/.allowCredentials(true) /*是否支持跨域用户凭证*/.maxAge(300)/*超时时长设置为5分钟。 时间单位是秒。*/.allowedHeaders("*");/*请求体的头部*/}
}
  • 在前端vue-cli脚手架中

还记得在config目录下index.js文件吗?在第13行代码proxyTable处,添加域名代理配置

proxyTable: { //设置域名代理"/exam":{target:"http://localhost:8080",//代理服务器地址;这里是你后端的协议、端口、域名secure:false,//如果是https接口,需要配置这个参数值为 truews: true,//是否代理websocketschangeOrigin: true,//允许跨域访问 后端地址pathRewrite: {'^/exam': ''}//当实际需要请求的路径里面没有”/api“时,就用''代替}},

axios的安装

  • 还记得之前的一个命令:cnpm install axios

这个命令就是安装axios

  • 导入了axios后,还要在main.js中设置axios的全局配置
import Vue from 'vue'
import App from './App'
import router from './router'/* 引入axios */
import axios from 'axios'
/* 引入qs */
import qs from 'qs'/* 设置代理的域名 */
axios.defaults.baseURL = '/exam';
/* 设置cookie,session跨域配置 */
axios.defaults.withCredentials=true;
/* 设置post请求体*/
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
/* 设置全局axios写法 */
Vue.prototype.$http = axios
/* 设置全局qs写法 */
Vue.prototype.$qs = qsimport ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)Vue.config.productionTip = false/* eslint-disable no-new */
new Vue({el: '#app',router,components: { App },template: '<App/>'
})

十一、做一个前后端邮箱登录的案列

前端Vue-cli脚手架

使用Element-UI搭建一个前端的登录页面

创建一个src / components / email / login.vue

<template><el-container class="login-one"><el-header></el-header><el-main><br> <br> <br> <br> <br> <br><el-row><el-col :span="8">&nbsp;</el-col><el-col :span="8"  style="background-color: white;border-radius: 5px;"><br><h1 align="center">邮箱验证</h1><br><el-form :model="userInfo" label-width="100px"><el-form-item label="你的邮箱:"><el-col :span="20"><el-input v-model="userInfo.userName" ></el-input></el-col></el-form-item><el-form-item label="验证码:"><el-col :span="20"><el-input v-model="userInfo.userPwd" show-password></el-input></el-col></el-form-item><el-form-item ><el-button type="success" icon="el-icon-user-solid" size="mini">发送验证码</el-button><el-button type="success" icon="el-icon-user-solid" size="mini">登录</el-button></el-form-item></el-form></el-col><el-col :span="8">&nbsp;</el-col></el-row></el-main></el-container>
</template><script>export default {name:"hello",data(){return{userInfo:{userName:"",userPwd:""}}}}
</script><style  >html,body{margin: 0px;height: 100%;}.login-one{background-color:#1c77ac;/* 静态资源 图片的相对路径 ../ 表示当前目录的上一级 */background-image:url(../../assets/light.png);background-repeat:no-repeat;overflow:hidden;height: 100%;}
</style>

注意配置路由!!! import login from ‘@/components/email/login’

效果(随便搞的一个,不太美观)

后端springBoot框架

导入依赖
 //邮箱发送依赖包<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
在QQ邮箱中,去申请授权

在授权后,会发你一串授权码,保存起来,后端配置要用

在application.propertise 配置文件中配置发送人(就是你)邮箱信息
#qq邮件服务器地址 若果你不是QQ邮箱  那就得换
spring.mail.host=smtp.qq.com#自己的邮箱名
spring.mail.username=xxxxxxxx@qq.com#授权码
spring.mail.password=刚刚让你保存的#smtp服务端口号 默认的端口
spring.mail.port=465#配置 对smtp服务支持的java类
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
#字符编码
spring.mail.default-encoding=UTF-8
创建实体类ResultVo,用于返回信息
import lombok.Data;
// 使用@Data 必须导入Lombok依赖
@Data
public class ResultVo<T> {private boolean success;private String info;private T data;
}
在service层编写邮件发送逻辑
import com.hang.pojo.ResultVo;public interface UserInfoService {ResultVo sendCode(String email);
}
import com.hang.pojo.ResultVo;
import com.hang.service.UserInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.Random;@Service
public class UserInfoServiceImpl implements UserInfoService {//邮件发送服务类 使用 @Resource注解,@ResourceJavaMailSender javaMailSender;//获取发件人邮箱@Value("${spring.mail.username}")private String formEmail;@Overridepublic ResultVo sendCode(String email) {ResultVo rv = new ResultVo();try{//创建信封对象SimpleMailMessage message = new SimpleMailMessage();//收件人message.setTo(email);//发件人message.setFrom(formEmail);//邮件标题message.setSubject("XX公司验证码");//邮件正文 获取10000以内的随机数Random rd = new Random();String code = rd.nextInt(10000)+"";message.setText("你的验证码是:"+code);//发送邮件javaMailSender.send(message);rv.setSuccess(true);rv.setInfo("邮件发送成功");}catch (Exception e){e.printStackTrace();rv.setInfo("邮件发送失败");}return rv;}
}
controller层控制URL请求
import com.hang.pojo.ResultVo;
import com.hang.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserInfoController {@AutowiredUserInfoService userInfoService;@GetMapping("/sendCode")public ResultVo sendCode(String email){return userInfoService.sendCode(email);}
}
在Postmanr工具软件中验证是否有邮件发送

springBoot整合Redis

为什么要整合redis??
思路:发送一个验证码,是不是应该有有效时间?比如,在发送验证码的一分钟内有效。那么后端就应该存储这个验证码一分钟;用到的技术就是Redis

  • 导入依赖
<!-- !redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
  • Redis配置类
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;@Configuration
@EnableCaching // 启用缓存,使用 Lettuce,自动注入配置的方式
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {//缓存管理器@Bean@SuppressWarnings("all")public CacheManager cacheManager(LettuceConnectionFactory factory) {RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);RedisSerializationContext.SerializationPair pair =RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer(Object.class));RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();return new RedisCacheManager(writer, config);}@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);// String 序列化方式StringRedisSerializer stringSerializer = new StringRedisSerializer();// 使用Jackson2JsonRedisSerialize替换默认序列化Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);// 设置key的序列化规则redisTemplate.setKeySerializer(stringSerializer);redisTemplate.setHashKeySerializer(stringSerializer);// 设置value的序列化规则redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);return redisTemplate;}// 重新定义缓存 key 的生成策略@Bean@Overridepublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method,  Object... params){StringBuilder sb = new StringBuilder();sb.append(target.getClass().getName());sb.append(method.getName());for(Object obj:params){sb.append(obj.toString());}return sb.toString();}};}
}
  • 在service层增加Redis缓存
import com.hang.pojo.ResultVo;public interface UserInfoService {//发送验证码ResultVo sendCode(String email);//判断验证码ResultVo emailLogin(String email,String code);
}
import com.hang.pojo.ResultVo;
import com.hang.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;@Service
public class UserInfoServiceImpl implements UserInfoService {//注入Redis@AutowiredRedisTemplate<String, Object> redisTemplate;//邮件发送服务类 使用 @Resource注解,@ResourceJavaMailSender javaMailSender;//获取发件人邮箱@Value("${spring.mail.username}")private String formEmail;@Overridepublic ResultVo sendCode(String email) {ResultVo rv = new ResultVo();try{//创建信封对象SimpleMailMessage message = new SimpleMailMessage();//收件人message.setTo(email);//发件人message.setFrom(formEmail);//邮件标题message.setSubject("XX公司验证码");//邮件正文 获取10000以内的随机数Random rd = new Random();String code = rd.nextInt(10000)+"";message.setText("你的验证码是:"+code);//发送邮件javaMailSender.send(message);/** 如果邮件发送成功,那么验证码应该存入Redis中* *///唯一性//这里是:将验证码+收件人的QQ邮箱 作为 key  验证码code 作为 valueString key = "code:"+email;//存五分钟redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);rv.setSuccess(true);rv.setInfo("邮件发送成功");}catch (Exception e){e.printStackTrace();rv.setInfo("邮件发送失败");}return rv;}@Overridepublic ResultVo emailLogin(String email, String code) {ResultVo rv = new ResultVo();//判断验证码是否失效String key = "code:"+email;Object c = redisTemplate.opsForValue().get(key);if (c == null){rv.setInfo("验证码过期了");}else{if (c.equals(code)){rv.setSuccess(true);rv.setInfo("验证码还在Redis中,允许登录");}else {rv.setInfo("验证码不对");}}return rv;}
}

编写前端js,发送url请求;获取后端返回的数据

login.vue

<template><el-container class="login-one"><el-header></el-header><el-main><br> <br> <br> <br> <br> <br><el-row><el-col :span="8">&nbsp;</el-col><el-col :span="8"  style="background-color: white;border-radius: 5px;"><br><h1 align="center">邮箱验证</h1><br><el-form :model="userInfo.email" label-width="100px"><el-form-item label="你的邮箱:"><el-col :span="20"><el-input v-model="userInfo.email" placeholder="请输入QQ邮箱"></el-input></el-col></el-form-item><el-form-item label="验证码:"><el-col :span="20"><el-input v-model="userInfo.code" placeholder="请输入验证码" ></el-input></el-col></el-form-item><el-form-item ><el-button type="success" icon="el-icon-user-solid" size="mini" @click="sendCode" :disabled="isDis">发送验证码({{num}})</el-button><el-button type="success" icon="el-icon-user-solid" size="mini" @click="emailLogin">登录</el-button></el-form-item></el-form></el-col><el-col :span="8">&nbsp;</el-col></el-row></el-main></el-container>
</template><script>export default {name:"login",data(){return{userInfo:{email:'',code:''},// 设置发送验证码禁用时间num:60,// 发送验证码禁用按钮isDis:false}},methods:{sendCode(){var self = this;//发送http://local:8080/user/emailLogin 请求,将userInfo对象传递给后端  {params:必须为key}var http = this.$http.get("/user/sendCode",{params:this.userInfo});//后端返回的rshttp.then(function(rs){if(rs.data.success){//邮件发送成功后,就不能再点击this.isDis = true;var time = setInterval(function(){//计时self.num--;if(self.num == 0){self.isDis = false;clearInterval(time);}},1000);}})},emailLogin(){var self = this;//发送http://local:8080/user/emailLogin 请求,将userInfo对象传递给后端var http = this.$http.get("/user/emailLogin",{params:this.userInfo});http.then(function(rs){//rs.data是固有写法,与后端的data无关self.$alert(rs.data.info);})}}}
</script>
<style  >html,body{margin: 0px;height: 100%;}.login-one{background-color:#1c77ac;/* 静态资源 图片的相对路径 ../ 表示当前目录的上一级 */background-image:url(../../assets/light.png);background-repeat:no-repeat;overflow:hidden;height: 100%;}
</style>

vue-cli和Element-UI搭配web前端相关推荐

  1. 基于 Vue JS、Element UI、Nuxt JS的项目PC端前端手册

    基于 Vue JS.Element UI.Nuxt JS的项目PC端前端手册 前言:笔记写于2020年5月左右,刚开始做前端时整理的笔记 1.环境搭建 1.安装nodeJs ​ 官网下载地址:http ...

  2. npm创建Vue工程【element UI】

    npm创建Vue工程[element UI] 步骤 # 初始化一个名为 hello-vue 的Vue工程 vue init webpack hello-vue# 进入 hello-vue 工程 cd ...

  3. 模糊搜索——Vue单页面-Element UI

    模糊搜索--Vue单页面-Element UI <!DOCTYPE html> <html><head><meta charset="UTF-8&q ...

  4. Element ui全部数据前端排序

    Element ui全部数据前端排序 1.首先给el-table绑定sort-change监听 <el-table ref="filterTable" :data=" ...

  5. Vue React Angular之三国杀,web前端入坑第六篇 上

    「 懒癌引发血案 」 目前前端技术栈发生了翻天覆地的变化,上篇刚写了只会jquery 要失业,再不学新的你就要被淘汰,虽然有点危言耸听,不过现实情况确实是这样. vue.react.angular对比 ...

  6. Vue 篇 解决ELement UI 中表单验证(多层Object嵌套)

    项目场景: 提示:主要是在 Vue 框架中: 用 Element UI 提供的规则进行表单验证 问题描述 因为我 data 里面嵌套了多层 Object, 所以 Element UI 提供的表单验证没 ...

  7. Vue引入第三方Element UI 组件

    Element UI 官网地址: 各种基于Vue.js的各种UI组件 https://element.eleme.cn/#/zh-CN/component/quickstart https://ele ...

  8. 【2】Vue项目引用Element UI(饿了么框架)菜单导航条初期配置

    首先要理解Vue项目加载顺序: index.html → main.js → App.vue → nav.json→ routes.js → page1.vue index.html建议加入样式 &l ...

  9. vue 使用 cdn element ui 失效 问题解决

    原写法 (失效) 正确写法 注意顺序!!! element 用cdn导入,组件使用无效 element用cdn导入前面要加一个vue的cdn,这个大家都知道,但问题是如果你npm里面有vue的话,他会 ...

最新文章

  1. gis中的擦除_擦除—帮助 | ArcGIS for Desktop
  2. 图像偏色检测算法,速度快,效果好,共享给大家。
  3. 比较顺利 - Python基础2
  4. input子系统分析(转)
  5. 学python用什么系统好-学Python用什么系统?
  6. Envy-便当的显卡驱动布置剧本
  7. python安装轮子_如何安装这个轮子?
  8. Mysql系列:高可用(HA)-keeplived
  9. 【掩耳盗铃】[转载]北京铁路局:“北京站37号窗口售票员内部大量出票”是为分区售票...
  10. FreeMarker语言【页面静态】
  11. Linux开发_反编译开发_破解简单登录程序外加缓冲区溢出攻击
  12. autotools工具介绍
  13. 树莓派4B WIFI 物理网口设置固定IP方法
  14. 查询按键控制数码管的显示
  15. 怎么把图片转PDF格式?转换方法分享
  16. mysql 命令行修改密码
  17. 离散数学-集合-笛卡尔积-07
  18. 电子科技大学计算机初试分数,电子科技大学计算机,我的分数出来了,考研感受!...
  19. 波束形成:最小方差无畸变响应波束形成器(MVDR)
  20. Windows 安全中心空白无选项解决办法

热门文章

  1. 用不了chatgpt,试试Claude-Claude注册教程
  2. 【组合数学】指数生成函数 ( 指数生成函数概念 | 排列数指数生成函数 = 组合数普通生成函数 | 指数生成函数示例 )
  3. 快捷方式 ABP——切换MySQL数据库
  4. 使用Nacos实现Spring Cloud Zuul的动态路由
  5. fiddler安卓模拟器与ios手机抓包
  6. 计算机自带的科学计算器代码,[置顶] 科学计算器(简化版:基于MFC对话框)
  7. 基于spring boot的婚纱摄影约拍系统
  8. 用LINQ结合CAML查询 Sharepoint 数据库内容
  9. 开启超高清时代 联诚发5G+8K大屏点亮智慧展厅及银行业
  10. 【毕业设计】大数据大众点评评论文本分析 - python 数据挖掘