验证码(easy-captcha)

该博客展示了如何在Java后端集成EasyCaptcha库生成数学和字符验证码,并通过HTTP响应发送到前端。前端使用JavaScript获取验证码图片,并提供了登录功能的简单实现。在后端,验证码存储在Redis缓存中并设置过期时间,前端通过校验验证码来验证用户输入。
摘要由CSDN通过智能技术生成

依赖

 <!--验证码依赖-->
        <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>
package com.jm.sso.server.util;

import cn.hutool.core.util.StrUtil;
import com.jm.sso.base.controller.BaseController;
import com.jm.sso.base.result.BaseResponse;
import com.jm.sso.base.util.IpUtils;
import com.jm.sso.base.util.RedisCache;
import com.jm.sso.server.constant.RedisCons;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class CaptchaUtil extends BaseController {


    @Autowired
    private RedisCache redisCache;


    public void mathCaptcha( HttpServletResponse response)  {
        //设置请求头为输出图片的类型
        response.setContentType("image/jpg");
        response.setHeader("Pargam", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //生成验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
        redisCache.setCacheObject(StrUtil.format(RedisCons.CAPTCHA_CODE, IpUtils.getIpAddr()), captcha.text(), 180, TimeUnit.SECONDS);
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public BaseResponse captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = StrUtil.format(RedisCons.CAPTCHA_CODE, IpUtils.getIpAddr());
        // 存入redis并设置过期时间为30分钟
        redisCache.setCacheObject(key, verCode, 30,TimeUnit.SECONDS);
        // 将key和base64返回给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("key", key);
        map.put("image", specCaptcha.toBase64());
        return setResultSuccess(map);

    }


    public BaseResponse verifyCode( String code)  {
        String key = StrUtil.format(RedisCons.CAPTCHA_CODE, IpUtils.getIpAddr());
        String captcha = redisCache.getCacheObject(key);
        if(StrUtil.isBlank(captcha)){
            return setResultError("验证码失效");
        }
        if(StrUtil.equals(captcha,code)){
            redisCache.deleteObject(key);
            return setResultSuccess();
        }
        return setResultError("验证码校验失败");
    }

}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
        }
        body {
            height: 100%;
        }
        .container {
            height: 100%;
            background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
        }
        .login-wrapper {
            background-color: #fff;
            width: 358px;
            height: 588px;
            border-radius: 15px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
        .header {
            font-size: 38px;
            font-weight: bold;
            text-align: center;
            line-height: 200px;
        }
        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
        }
        .input-item:placeholder {
            text-transform: uppercase;
        }
        .btn {
            text-align: center;
            padding: 10px;
            width: 100%;
            margin-top: 40px;
            background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
            color: #fff;
        }
        .msg {
            text-align: center;
            line-height: 88px;
        }
        a {
            text-decoration-line: none;
            color: #abc1ee;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="login-wrapper">
        <div class="header">Login</div>
        <div class="form-wrapper">
            <input id="username" type="text" name="username" placeholder="username" class="input-item">
            <input id="passowrd" type="password" name="password" placeholder="password" class="input-item">
            <img id="captcha" ref="vcImg" onclick="getCaptcha()">
            <div class="btn"onclick="doLogin()">Login</div>
        </div>
        <div class="msg">
            Don't have account?
            <a href="#">Sign up</a>
        </div>
    </div>
</div>
</body>
<!--<script type="text/javascript" src="/js/axios.js"></script>-->
<!--<script type="text/javascript" src="/js/jquery.min.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.js"></script>

<script>
    getCaptcha();

    // function getCaptcha(){
    //     axios.get("http://127.0.0.1:7000/mathCaptcha").then(res=>{
    //         debugger;
    //         console.log(res.data.img)
    //         document.getElementById("captcha").src =res.data
    //     })
    //
    // }

    function getCaptcha() {
        $("#captcha").attr("src", "/mathCaptcha?"  + "&time=" + new Date());

        console.log("请求准备发送");
        // $.ajax({
        //     url: "/mathCaptcha?"+Math.random(),      //请求接口的地址
        //     type: "GET",                                   //请求的方法GET/POST
        //     // data: {                                        //需要传递的参数
        //     //     name: 'sl',
        //     //     password: '123456',
        //     // },
        //     success: function (res) {
        //         debugger;//请求成功后的操作
        //         console.log(res);
        //         document.getElementById("captcha").src =res
        //     },
        //     error: function (err) {                       //请求失败后的操作
        //         console.log(22);                          //请求失败在控制台输出22
        //     }
        // })
    }

    function doLogin(){
        var username = document.getElementById("username").value;
        var passowrd = document.getElementById("passowrd").value;
        alert(username);
        alert(passowrd);
    }
</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值