springboot+vue实现验证码

图片效果展示

 一.导入生成验证码工具类

package com.systop.tanzhen.vo;


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

public class VerifyCode {
    //宽和高
    private int w = 85;
    private int h = 40;

    private Random r = new Random();
    // 定义有那些字体
    private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
    // 定义有那些验证码的随机字符
    private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
    // 生成背景色
    private Color bgColor = new Color(0, 255, 255);
    // 用于gettext 方法 获得生成的验证码文本
    private String text;

    // 生成随机颜色
    private Color randomColor() {
        int red = r.nextInt(255);
        int green = r.nextInt(255);
        int blue = r.nextInt(255);
        return new Color(red, green, blue);
    }

    // 生成随机字体
    private Font randomFont() {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];
        int style = r.nextInt(4);
        int size = r.nextInt(5) + 24;

        return new Font(fontName, style, size);
    }

    // 画干扰线
    private void drawLine(BufferedImage image) {
        int num = 3;
        Graphics2D g2 = (Graphics2D) image.getGraphics();

        for (int i = 0; i < num; i++) {
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));// 不知道
            g2.setColor(Color.white);
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    // 得到codes的长度内的随机数 并使用charAt 取得随机数位置上的codes中的字符
    private char randomChar() {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }

    // 创建一张验证码的图片
    public BufferedImage createImage() {
        BufferedImage image = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        StringBuilder sb = new StringBuilder();
        // 向图中画四个字符
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";
            sb.append(s);
            float x = i * 1.0F * w / 4;
            g2.setFont(randomFont());
            g2.setColor(randomColor());
            g2.drawString(s, x, h - 5);

        }
        this.text = sb.toString();
        drawLine(image);


        // 返回图片
        return image;

    }

    // 得到验证码的文本 后面是用来和用户输入的验证码 检测用
    public String getText() {
        return text;
    }

    // 定义输出的对象和输出的方向
    public static void output(BufferedImage bi, OutputStream fos)
            throws FileNotFoundException, IOException {
        ImageIO.write(bi, "JPEG", fos);
    }

}

二.编写Controller生成验证码的接口

package com.systop.tanzhen.controller;

import com.systop.tanzhen.vo.VerifyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Api(tags  = "验证码")
@RestController
@CrossOrigin
@RequestMapping("/code")
public class VerifyController {

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "验证码生成")
    @GetMapping("/verify")
    public void Verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        VerifyCode code = new VerifyCode();
        BufferedImage image = code.createImage();

        //验证码
        System.err.println(code.getText());
        //保存验证码到Redis,一分钟有效期
        redisTemplate.opsForValue().set("code",code.getText(),1L, TimeUnit.MINUTES);


        //验证码图片格式
        ImageIO.write(image,"jpg",response.getOutputStream());
    }


}

vue前端代码

      <el-form-item
        label="验证码"
        label-width="70px"
        prop="code"
        :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]"
      >
        <div class="code">
          <el-input
            style="width: 190px"
            v-model="dynamicValidateForm.code"
            class="code1"
          ></el-input>
          <img
            :src="captchaImage"
            alt="图片无法加载"
            style=""
            @click="changeVerify()"
          />
        </div>
      </el-form-item>
    changeVerify() {
      axios
        .get("http://localhost:8888/code/verify", {
          responseType: "arraybuffer",
        })
        .then((response) => {
          console.log(response);
          const imageBase64 = btoa(
            new Uint8Array(response.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
          this.captchaImage = `data:image/jpeg;base64,${imageBase64}`;
        })
        .catch((error) => {
          console.error(error);
        });
    },

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
前端代码: ```vue <template> <div> <el-form :model="form" label-width="100px" ref="form"> <el-form-item label="手机号码" prop="phone"> <el-input v-model="form.phone" placeholder="请输入手机号码"></el-input> </el-form-item> <el-form-item label="验证码" prop="captcha"> <el-input v-model="form.captcha" placeholder="请输入验证码" style="width: 200px"></el-input> <el-button type="primary" @click="sendCaptcha" :disabled="isSending">{{ captchaText }}</el-button> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </div> </template> <script> import { getCaptcha, login } from '@/api/user' export default { data() { return { form: { phone: '', captcha: '' }, captchaText: '获取验证码', isSending: false } }, methods: { sendCaptcha() { if (!this.form.phone) { this.$message.error('请输入手机号码') return } if (this.isSending) { return } this.isSending = true let count = 60 const interval = setInterval(() => { count-- if (count <= 0) { clearInterval(interval) this.captchaText = '重新获取' this.isSending = false } else { this.captchaText = `${count}s后重新获取` } }, 1000) getCaptcha(this.form.phone).then(() => { this.$message.success('验证码已发送') }).catch(() => { clearInterval(interval) this.captchaText = '重新获取' this.isSending = false }) }, submitForm() { this.$refs.form.validate(valid => { if (valid) { login(this.form.phone, this.form.captcha).then(() => { this.$router.push('/') }).catch(error => { this.$message.error(error.message) }) } }) } } } </script> ``` 后端代码: ```java @RestController @RequestMapping("/api/user") public class UserController { @Autowired private RedisUtil redisUtil; @PostMapping("/captcha") public ResponseEntity<Object> getCaptcha(@RequestParam String phone) { // 生成4位随机验证码 String captcha = String.valueOf(new Random().nextInt(8999) + 1000); // 将验证码保存到redis中,有效期5分钟 redisUtil.set(phone, captcha, 5 * 60); // TODO 发送短信验证码 return ResponseEntity.ok().build(); } @PostMapping("/login") public ResponseEntity<Object> login(@RequestParam String phone, @RequestParam String captcha) { // 从redis中获取验证码 String redisCaptcha = (String) redisUtil.get(phone); if (StringUtils.isBlank(redisCaptcha)) { throw new BusinessException("验证码已失效,请重新获取"); } if (!StringUtils.equals(redisCaptcha, captcha)) { throw new BusinessException("验证码错误"); } // TODO 验证手机号码是否已注册 // TODO 如果未注册,则自动注册 // TODO 生成token返回给前端 return ResponseEntity.ok().build(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值