springboot + redis 实现验证码验证

在这里插入图片描述

一滴水只有放进大海里才永远不会干涸,一个人只有当他把自己和集体事业融合在一起的时候才能最有力量。
——雷锋

一. redis和postman的安装

redis和postman自行在网上安装即可
redis官网地址:https://redis.io/download
postman官网地址:https://www.postman.com
建议将redis客户端也一起安装

二. Springboot项目的创建

使用idea编程软件,创建springboot,勾选web模块

三. 代码编写

1.目录结构

我用的springboot版本是2.6.3
在这里插入图片描述

2.引入需要的依赖

        <!--redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!--图形验证码依赖-->
        <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

        <!--阿里巴巴fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>

3.核心实现

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setFont(Captcha.FONT_1);
        String id = UUID.randomUUID().toString();
        response.setHeader("id", id);
        CaptchaUtil.out(specCaptcha, request, response);
        String verCode = specCaptcha.text().toLowerCase();
        //不设置过期
        redisClient.set(id, verCode);
        //设置一分钟过期
        //redisClient.set(id,verCode,60);
    }

    @PostMapping(value = "/check")
    public boolean check(@RequestBody String info) {
        JSONObject jsonObject = JSON.parseObject(info);
        //获取传过来的id 和 code
        String id = jsonObject.getString("id");
        String code = jsonObject.getString("code");
        String s = "";
        //获取redis里面存的code
        Object obj = redisClient.get(id);
        if(obj != null){
            s = obj.toString();
        }
        //比较输入的code和redis的code
        boolean flag = code.equalsIgnoreCase(s);
        //匹配成功就删除redis存储
        if(flag){
            redisClient.delete(id);
        }
        return flag;
    }

4.测试(记得先启动redis)

生成验证码
在这里插入图片描述
在redis中查看生成的key和验证码(code)

在这里插入图片描述
验证生成的验证码

在这里插入图片描述

源码已上传至github,地址:https://github.com/conciseL/java-/tree/master

如若可以,请帮忙点个star

每天进步一点点,开心也多一点点

  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

white_poland

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值