Kaptcha验证码的简单使用

2 篇文章 0 订阅
2 篇文章 0 订阅

Kaptcha验证码的简单使用

作用

防止不法分子在短时间内使用机器人进行批量的重读操作。如果设置了验证码,可以减轻上述操作对系统的危害。

springboot集成Kaptcha

  • 添加依赖

    <dependency>
           <groupId>com.github.penggle</groupId>
           <artifactId>kaptcha</artifactId>
           <version>2.3.2</version>
    </dependency>
    
  • 配置

    在spring项目的config包中新建对应的配置类

    @Component
    public class KaptchaConfig {
        @Bean
        public DefaultKaptcha getDefaultKaptcha(){
            com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
            Properties properties = new Properties();
            // 图片边框
            properties.put("kaptcha.border", "no");
            // 字体颜色
            properties.put("kaptcha.textproducer.font.color", "black");
            // 图片宽
            properties.put("kaptcha.image.width", "160");
            // 图片高
            properties.put("kaptcha.image.height", "40");
            // 字体大小
            properties.put("kaptcha.textproducer.font.size", "30");
            // 验证码长度
            properties.put("kaptcha.textproducer.char.space", "5");
            // 字体
            properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
    }
    

生成与显示

通过一个session记录相关的验证码信息,并且通过一个response对象返回验证码图片给前端

![验证码](C:\Users\oroch\Pictures\mds\springboot\其他类\验证码.png)@Controller
public class KaptchaController {

    @Autowired
    private DefaultKaptcha captchaProducer;

    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = captchaProducer.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            BufferedImage challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码显示</title>
</head>
<body>
<img src="/kaptcha"
     onclick="this.src='/kaptcha?d='+new Date()*1">
</body>
</html>

在谷歌浏览器中可以看出每次点击都会生成一个新的验证码

在这里插入图片描述

使用

编写一个带请求参数的controller,将该参数与session中的验证码字符串进行比较

 @GetMapping("/verify")
    @ResponseBody
    public String verify(@RequestParam("code") String code, HttpSession session) {
        if (StringUtils.isEmpty(code)) {
            return "验证码不能为空";
        }
        String kaptchaCode = session.getAttribute("verifyCode") + "";
        if (StringUtils.isEmpty(kaptchaCode) || !code.equals(kaptchaCode)) {
            return "验证码错误";
        }
        return "验证成功";
    }

单单一个验证码部分,我们可以使用异步的AJAX

按下提交按钮后,js方法会获取键入的值来进行AJAX请求

<script type="text/javascript">
    $(function () {
        $("#verify").click(function () {
            var code = $("#code").val();
            $.ajax({
                type: 'GET',//方法类型
                url: '/verify?code=' + code,
                success: function (result) {
                    alert(result);
                },
                error: function () {
                    alert("请求失败");
                }
            });
        })
    });
</script>

最后,大功告成!!

        error: function () {
                alert("请求失败");
            }
        });
    })
});
~~~

最后,大功告成!!

在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值