SpringBoot+Vue开发之Login校验规则、实现登录和重置事件
一、Login校验规则
1、校验规则写法可参考Element-ui官网文档
https://element.eleme.cn/#/zh-CN/component/form
2、Login.vue页面
<template> <div class="login_container"> <!-- 登录块 --> <div class="login_box"> <!-- 头像 --> <div class="acator_box"> <img src="../assets/logo.png" /> </div> <!-- 表单区域 --> <el-form ref="loginFormRef" :rules="loginRules" :model="loginForm" class="login_form" label-width="0"> <!-- 用户名 --> <el-form-item prop="username"> <el-input v-model="loginForm.username" prefix-icon="iconfont icon-denglu"> </el-input> </el-form-item> <!-- 密码 --> <el-form-item prop="password"> <el-input v-model="loginForm.password" prefix-icon="iconfont icon-mima"> </el-input> </el-form-item> <!-- 按钮 --> <el-form-item class="btns"> <el-button type="primary">提交</el-button> <el-button type="info">重置</el-button> </el-form-item> </el-form> </div> </div> </template> <script> export default { data() { return { // 表单数据对象 loginForm: { username: "username", password: "password" }, // 验证对象 loginRules: { //用户名 username:[ //必填项验证,required意思为必须的,trigger意思为触发机制,blur意思为失去焦点 { required: true, message: '请输入用户名称', trigger: 'blur' }, //长度验证 { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' } ], //密码 password:[ //必填项验证,required意思为必须的,trigger意思为触发机制,blur意思为失去焦点 { required: true, message: '请输入用户密码', trigger: 'blur' }, //长度验证 { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' } ] } }; }, }; </script> <style lang="less" scoped> // 根节点样式 .login_container { background-color: #2b4b6b; height: 100%; } .login_box { width: 450px; height: 300px; background-color: #ffffff; border-radius: 3px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); .acator_box { width: 130px; height: 130px; border: 1px solid #eeeeee; border-radius: 50%; padding: 10px; box-shadow: 0 0 10px #dddddd; position: absolute; left: 50%; transform: translate(-50%, -50%); background-color: #00eeee; img { width: 100%; height: 100%; border-radius: 50%; background-color: #eeeeee; } } } .btns { display: flex; justify-content: flex-end; } .login_form { position: absolute; bottom: 0%; width: 100%; padding: 0 10px; box-sizing: border-box; } </style>
3、运行结果
思考:
Element UI作为一个CSS框架,竟然能够进行表单验证,我想这肯定内部封装了JS;
二、实现登录和重置事件
1、在main.js中导入axios
import Vue from 'vue' import App from './App.vue' import router from './router' import './plugins/element.js' //导入全局样式 import './assets/css/global.css' //引入图标 import './assets/font/iconfont.css' //导入axios import axios from 'axios' //挂载 Vue.prototype.$http = axios //设置访问根路径 axios.defaults.baseURL = "http://localhost:9000" Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
2、在Login页面编写对应方法
(注意登录方法和重置方法的绑定和在下面的编写)
<template> <div class="login_container"> <!-- 登录块 --> <div class="login_box"> <!-- 头像 --> <div class="acator_box"> <img src="../assets/logo.png" /> </div> <!-- 表单区域 --> <el-form ref="loginFormRef" :rules="loginRules" :model="loginForm" class="login_form" label-width="0"> <!-- 用户名 --> <el-form-item prop="username"> <el-input v-model="loginForm.username" prefix-icon="iconfont icon-denglu"> </el-input> </el-form-item> <!-- 密码 --> <el-form-item prop="password"> <el-input v-model="loginForm.password" prefix-icon="iconfont icon-mima" type="password"> </el-input> </el-form-item> <!-- 按钮 --> <el-form-item class="btns"> <el-button type="primary" @click="login()">提交</el-button> <el-button type="info" @click="resetLoginForm()">重置</el-button> </el-form-item> </el-form> </div> </div> </template> <script> export default { data() { return { // 表单数据对象 loginForm: { username: "admin", password: "123456" }, // 验证对象 loginRules: { //用户名 username:[ //必填项验证,required意思为必须的,trigger意思为触发机制,blur意思为失去焦点 { required: true, message: '请输入用户名称', trigger: 'blur' }, //长度验证 { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' } ], //密码 password:[ //必填项验证,required意思为必须的,trigger意思为触发机制,blur意思为失去焦点 { required: true, message: '请输入用户密码', trigger: 'blur' }, //长度验证 { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' } ] } }; }, methods:{ //重置表单内容 resetLoginForm(){ this.$refs.loginFormRef.resetField(); }, //登录 login(){ //表单验证 this.$refs.loginFormRef.validate(async valid =>{ if(!valid){ return; } const {data:res} = await this.$http.post("login",this.loginForm);//访问后台 console.log(res.flag); if(res.flag == "ok"){ this.$message.success("操作成功!"); // up主是这么写的,this.$router.push({"/home"}}); this.$router.push("/home");//页面路由跳转 console.log(res.user); window.sessionStorage.setItem("user",res.user); }else{ this.$message.success("操作失败!"); } }); } } }; </script> <style lang="less" scoped> // 根节点样式 .login_container { background-color: #2b4b6b; height: 100%; } .login_box { width: 450px; height: 300px; background-color: #ffffff; border-radius: 3px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); .acator_box { width: 130px; height: 130px; border: 1px solid #eeeeee; border-radius: 50%; padding: 10px; box-shadow: 0 0 10px #dddddd; position: absolute; left: 50%; transform: translate(-50%, -50%); background-color: #00eeee; img { width: 100%; height: 100%; border-radius: 50%; background-color: #eeeeee; } } } .btns { display: flex; justify-content: flex-end; } .login_form { position: absolute; bottom: 0%; width: 100%; padding: 0 10px; box-sizing: border-box; } </style>
3、创建Home.vue页面
(这里我们把安全退出也写进去了,安全退出是将自己登录之后的账户信息也清除掉了,安全退出之前还有一些工作要做,因为这些东西改动的地方多而杂,搬来就不想继续做笔记了,但是想想,确实里面也有很多新的知识点,还是硬着头皮来吧)
<template> <div> Home 首页! <el-button class="info" @click="logout()"> 安全退出! </el-button> </div> </template> <script> export default { methods:{ logout(){ window.sessionStorage.clear(); this.$router.push("/login"); } } } </script> <style> </style>
4、在index.js中引入home组件,并配置路由
(创建的.vue页面被称为组件,创建之后引入才能用,再配置路由进行页面的分发;关于路由,我本来并不懂这个概念,但当我知道了他的写法和功能再加上对WiFi路由器的联想,意思也许就是负责页面分发吧,暂时就不去细查了)
import Vue from 'vue' import VueRouter from 'vue-router' //引入login组件 import Login from '../components/Login.vue' //引入home组件 import Home from '../components/Home.vue' Vue.use(VueRouter) const routes = [ { path:"/", //将首页“/”重定向到“/login” redirect:"/login" },{ //将上面引入的Login与“/login”访问路径进行绑定 path:"/login", component:Login },{ //将上面引入的Home与“/home”访问路径进行绑定 path:"/home", component:Home } ] const router = new VueRouter({ routes }) export default router
5、登录方法详述(注释说明)
//登录 login(){ //表单验证 this.$refs.loginFormRef.validate(async valid =>{ if(!valid){ return; } //这里我们发起post请求,传入表单数据,将服务器返回值传给res对象 const {data:res} = await this.$http.post("login",this.loginForm);//访问后台 console.log(res.flag); //如果res的flag是一个ok的话,就说明我们请求成功,并通过了用户验证! if(res.flag == "ok"){ this.$message.success("操作成功!"); // up主是这么写的,this.$router.push({"/home"}}); this.$router.push("/home");//页面路由跳转 console.log(res.user); //这个是将user数据传递给全局变量,方便在其他地方获取 window.sessionStorage.setItem("user",res.user); }else{ this.$message.success("操作失败!"); } }); }
6、在后台(spring boot项目)创建user对象
(我使用了lombok,第一次用了之后就离不开了)
package com.zibo.sport.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class User { private int id; private String username; private String password; private String email; private String role; private boolean state; }
7、编写UserDao
package com.zibo.sport.dao; import com.zibo.sport.bean.User; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Repository public interface UserDao { User getUserByMessage(@Param("username") String username, @Param("password") String password); }
8、编写UserDao.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zibo.sport.dao.UserDao"> <select id="getUserByMessage" parameterType="String" resultType="user"> select * from user where username=#{username} and password=#{password} and state=1; </select> </mapper>
9、编写LoginController
(这里需要说明一下,我们使用JSON工具将map对象转换成了JOSN字符串,具体坐标见下面的pom.xml)
package com.zibo.sport.controller; import com.alibaba.fastjson.JSON; import com.zibo.sport.bean.User; import com.zibo.sport.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class LoginController { @Autowired UserDao userDao; @RequestMapping("/login") public String login(@RequestBody User user){ String flag = "error"; System.out.println("user:" + user); User user1 = userDao.getUserByMessage(user.getUsername(), user.getPassword()); System.out.println("user1:" + user1); if(user1!=null){ flag = "ok"; } Map<String,Object> map = new HashMap<>(); map.put("flag",flag); map.put("user",user1); return JSON.toJSONString(map); } }
10、修改启动类SportApplication,使其能够扫描dao
package com.zibo.sport; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.zibo.sport.dao")//扫描dao @SpringBootApplication public class SportApplication { public static void main(String[] args) { SpringApplication.run(SportApplication.class, args); } }
11、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zibo</groupId> <artifactId>sport</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sport</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.74</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
12、数据库中的数据
创建表:
CREATE TABLE `zb`.`user` ( `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键', `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `role` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `state` tinyint(0) NOT NULL DEFAULT 0, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
插入数据:
INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (1, 'admin', '123456', '123@qq.com', '超级管理员', 1); INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (2, 'naughty', '888888', '456@qq.com', '普通管理员', 0); INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (3, 'flysky01', '987654', 'qwe@qq.com', '普通用户', 1); INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (4, 'anglybirds', '321654', 'aaaa@163.com', '普通用户', 0); INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (7, 'admin003', 'q123456', 'c@qq.com', '普通用户', 1); INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (8, 'admin005', '123456', 'cxz@qq.com', '普通用户', 0); INSERT INTO `user`(`id`, `username`, `password`, `email`, `role`, `state`) VALUES (9, 'admin007', '123456', 'rty@qq.com', '普通用户', 0);
表展示:
13、演示
(前后端项目要同时启动,因为我们已经绑定了http://localhost:9000,是向后台获取数据)
登录之前:
点击“提交”按钮之后:
安全退出:
(重置事件太简单了,是vue实现的,只需调用一个方法即可,见代码!)
(我们暂时就演示到这里!)
到此这篇关于SpringBoot+Vue开发之Login校验规则、实现登录和重置事件的文章就介绍到这了,更多相关spring boot vue实现登录和重置事件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
解决Echarts2竖直datazoom滑动后显示数据不全的问题
这篇文章主要介绍了解决Echarts2竖直datazoom滑动后显示数据不全的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-07-07
最新评论