vue+element实现登录界面(图片验证码、记住密码)

用户名+密码+验证码登录
验证码:前端绑定后端生成得验证码图片,前端提交表单信息到后端进行验证,后端验证码存入session
记住我:将用户名密码存入cookies

1、login.vue代码

<template>
  <div class="login-wrap">
    <div class="ms-title">'音酷'-后台管理系统</div>
    <div class="ms-login">
      <!-- ruleForm:数据表单;rules:提示;ref:使用这个form的名字 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="form">
        <el-form-item prop="username">
          <!-- v-model:双向绑定,placeholder:不输入内容之前提示 -->
          <el-input
            prefix-icon="el-icon-user"
            v-model="ruleForm.username"
            placeholder="用户名"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <!-- type:密码显示* -->
          <!-- <el-input prefix-icon="el-icon-unlock" type="password" v-model="ruleForm.password" placeholder="密码" auto-complete="false"></el-input> -->
          <el-input
            prefix-icon="el-icon-unlock"
            :type="passwordVisible"
            v-model="ruleForm.password"
            placeholder="密码"
            auto-complete="new-password"
          >
            <i slot="suffix" :class="icon" @click="showPass"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            prefix-icon="el-icon-mobile-phone"
            type="text"
            placeholder="点击图片更换验证码"
            v-model="ruleForm.code"
            class="vertify_code"
            auto-complete="false"
          ></el-input>
          <!-- <span class="code">验证码</span> -->
          <img :src="imgUrl" @click="resetImg" class="vertify_img" />
        </el-form-item>
        <el-checkbox v-model="checked" class="remeberMe">记住我</el-checkbox>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mixin } from "../mixins/index";
import { getLoginStatus } from "../api/index";
export default {
  mixins: [mixin],
  data: function () {
    return {
      checked: false,
      passwordVisible: "password",
      icon: "el-icon-view",
      imgUrl: "http://localhost:8888/verifyCode?time=" + new Date(),
      ruleForm: {
        username: "",
        password: "",
        code: "",
      },
      rules: {
        username: [
          // required:规则,trigger:失去焦点触发
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.account(); //获取cookie的方法
  },
  methods: {
    account() {
      console.log(this.getCookie("username"));
      this.ruleForm.username = this.getCookie("username");
      this.ruleForm.password = this.getCookie("password");
    },
    setCookie(c_name, c_pwd, exdate) {
      //账号,密码 ,过期的天数
      var exdate = new Date();
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdate); //保存的天数
      document.cookie =
        "username=" + c_name + ";path=/;expires=" + exdate.toLocaleString();
      document.cookie =
        "password=" + c_pwd + ";path=/;expires=" + exdate.toLocaleString();
    },
    getCookie(name) {
      var arr = document.cookie.split(";");
      for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split("=");
        if (arr2[0].trim() == name) {
          return arr2[1];
        }
      }
    },
    clearCookie() {
      this.setCookie("", "", -1); //清除cookie
    },

    // 方法
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //取参数
          let params = new URLSearchParams();
          params.append("name", this.ruleForm.username);
          params.append("password", this.ruleForm.password);
          params.append("code", this.ruleForm.code);
          if (this.checked == true) {
            //存入cookie
            this.setCookie(this.ruleForm.username, this.ruleForm.password, 7); //保存7天
          } else {
            this.clearCookie();
          }

          //调用方法提交
          getLoginStatus(params).then((res) => {
            if (res.code == 1) {
              localStorage.setItem("userName", this.ruleForm.username);
              this.$router.push("/Info");
              this.notify("登录成功", "success");
            }
            if (res.code == 0) {
              this.notify("验证码错误", "error");
            }
            if (res.code == 2) {
              this.notify("用户名或密码错误", "error");
            }
          });
        } else {
          return false;
        }
      });
    },
    //点击图片更换验证码
    resetImg() {
      this.imgUrl = "http://localhost:8888/verifyCode?time=" + new Date();
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    showPass() {
      if (this.passwordVisible === "text") {
        this.passwordVisible = "password";
        //更换图标
        this.icon = "el-icon-view";
      } else {
        this.passwordVisible = "text";
        this.icon = "el-icon-lock";
      }
    },
  },
};
</script>

<style scoped>
.login-wrap {
  position: relative;
  background: url("../assets/img/background1.jpg");
  background-attachment: fixed;
  background-position: center;
  background-size: cover;
  width: 100%;
  height: 100%;
}
.ms-title {
  position: absolute;
  top: 50%;
  width: 100%;
  margin-top: -230px;
  text-align: center;
  font-size: 30px;
  font-weight: 600;
  color: #fff;
}
.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 300px;
  height: 260px;
  margin-left: -190px;
  margin-top: -150px;
  padding: 40px;
  border-radius: 5px;
  /* 调整透明度 */
  opacity: 0.9;
  filter: alpha(opacity=90);
  background: #fff;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  /* width: 100%; */
  height: 36px;
}

.form {
  position: relative;
}

.remeberMe {
  text-align: left;
  margin: 0 0 15px 0;
}

.vertify_code {
  width: 180px;
}
.vertify_img {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 110px;
}
</style>

2、验证码生成工具

package com.javaclimb.music.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;


public class VerificationCode {
    private int width = 100;// 生成验证码图片的宽度
    private int height = 30;// 生成验证码图片的高度
    private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
    private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
    private Random random = new Random();
    private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private String text;// 记录随机字符串

    /**
     * 获取一个随意颜色
     *
     * @return
     */
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 获取一个随机字体
     *
     * @return
     */
    private Font randomFont() {
        String name = fontNames[random.nextInt(fontNames.length)];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(name, style, size);
    }

    /**
     * 获取一个随机字符
     *
     * @return
     */
    private char randomChar() {
        return codes.charAt(random.nextInt(codes.length()));
    }

    /**
     * 创建一个空白的BufferedImage对象
     *
     * @return
     */
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(bgColor);// 设置验证码图片的背景颜色
        g2.fillRect(0, 0, width, height);
        return image;
    }

    public BufferedImage getImage() {
        BufferedImage image = createImage();
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";
            sb.append(s);
            g2.setColor(randomColor());
            g2.setFont(randomFont());
            float x = i * width * 1.0f / 4;
            g2.drawString(s, x, height - 8);
        }
        this.text = sb.toString();
        drawLine(image);
        return image;
    }

    /**
     * 绘制干扰线
     *
     * @param image
     */
    private void drawLine(BufferedImage image) {
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        int num = 5;
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2.setColor(randomColor());
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    public String getText() {
        return text;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }

}

3、后端 controller层

package com.javaclimb.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.javaclimb.music.service.AdminService;
import com.javaclimb.music.utils.Consts;
import com.javaclimb.music.utils.VerificationCode;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;


    //    判断是否登录成功
    @RequestMapping(value = "/admin/login/status", method = RequestMethod.POST)
    public Object loginStatus(HttpServletRequest request, HttpSession session) {
        Object verifyCode = request.getSession().getAttribute("verify_code");//获取session里的验证码
        JSONObject jsonObject = new JSONObject();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        //判断结果
        if (verifyCode.toString().equals(code)) {
            boolean flag = adminService.verifyPassword(name, password);
            if (flag) {
                jsonObject.put(Consts.CODE, 1);
                jsonObject.put(Consts.MSG, "登录成功");
                session.setAttribute(Consts.NAME, name);
                return jsonObject;
            } else {
                jsonObject.put(Consts.CODE, 2);
                jsonObject.put(Consts.MSG, "用户名或密码错误");
                return jsonObject;

            }
        } else {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "验证码错误");
            return jsonObject;
        }
    }

    //生成验证码图片返回给前端图片地址
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        HttpSession session = request.getSession(true);
        session.setAttribute("verify_code", text);
        VerificationCode.output(image,resp.getOutputStream());
    }

}





  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
非常感谢您的提问!关于vue element实现登录注册页面,您可以参考以下步骤: 1. 安装vueelement-ui: ``` npm install vue npm install element-ui ``` 2. 在入口文件(如main.js)中引入相关组件: ```javascript import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import App from './App.vue' Vue.use(ElementUI) new Vue({ render: h => h(App), }).$mount('#app') ``` 3. 创建模板文件(如App.vue),在模板中添加表单和按钮组件: ```html <template> <div class="login-form"> <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="demo-ruleForm"> <el-form-item label="用户名" prop="username"> <el-input v-model="form.username"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="form.password"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm('form')">登录</el-button> <el-button type="primary" @click="submitForm('form')">注册</el-button> </el-form-item> </el-form> </div> </template> ``` 4. 在data中定义表单数据和验证规则: ```javascript data() { return { form: { username: '', password: '' }, rules: { username: [ { required: true, message: '请输入用户名', trigger: 'blur' } ], password: [ { required: true, message: '请输入密码', trigger: 'blur' } ] } }; }, ``` 5. 在methods中添加表单验证和提交表单的函数: ```javascript methods: { submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { // 表单验证通过,提交表单 console.log('submit!'); } else { console.log('error submit!!'); return false; } }); } } ``` 上述代码只是一个示例,具体的实现方式可能因项目需求而异。但无论如何,开发登录注册页面都需要严格控制用户信息的安全,所以在实现过程中需要格外小心。 私人信息泄漏可不是儿戏!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值