zoukankan      html  css  js  c++  java
  • kaptcha谷歌验证码工具的使用

    基于前后端分离或者非前后端分离都可以使用的java验证码实现方法

    第一步:引入依赖

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

    第二步:增加验证码生成的配置类,颜色,字体,干扰线等配置都在这里修改
    参数参考地址:https://www.cnblogs.com/louis80/p/5230507.html

    package com.zp.springbootdemo.util;
    
    import com.google.code.kaptcha.impl.DefaultKaptcha;
    import com.google.code.kaptcha.util.Config;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.Properties;
    
    /**
     * @Author zp
     * @Description 验证码生成的配置类
     * @Date 21:24 2020/5/7
     * @Param 
     * @return 
     **/
    @Configuration
    public class KaptchaConfig {
        @Bean
        public DefaultKaptcha producer(){
            DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
            Properties properties=new Properties();
            properties.setProperty("kaptcha.border", "no");
            properties.setProperty("kaptcha.border.color", "white");
            properties.setProperty("kaptcha.textproducer.font.color", "255,192,55");
            properties.setProperty("kaptcha.image.width", "125");
            properties.setProperty("kaptcha.image.height", "45");
            properties.setProperty("kaptcha.session.key", "code");
            properties.setProperty("kaptcha.textproducer.font.size", "38");
            properties.setProperty("kaptcha.noise.color","21,113,171");
            properties.setProperty("kaptcha.background.clear.from","0,154,255");
            properties.setProperty("kaptcha.background.clear.to","0,202,255");
            properties.setProperty("kaptcha.textproducer.char.length", "4");
            properties.setProperty("kaptcha.textproducer.font.names", "Arial");
            Config config=new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
    }

    第三步:验证码的生成

    通过DefaultKaptcha 类的createText()方法可生成文字验证码,文字验证码生成之后再生成图片验证码。返回给前端时可返回base64编码的图片验证码字符串,前端进行处理。也可直接返回图片。

    1.方式一,获取图片验证码,返回一个base64编码的图片字符串

        @Autowired
        private DefaultKaptcha producer;
    
    
        /**
         * @Author zp
         * @Description //获取图片验证码,返回一个base64编码的图片字符串
         * @Date 22:48 2020/5/7
         * @Param []
         * @return java.lang.String
         **/
        @GetMapping(value = "/default")
        public String generateVerificationCode() throws Exception {
            // 生成文字验证码,为了进行校验,可将文字验证码存入redis中
            String text = producer.createText();
            // 生成图片验证码
            ByteArrayOutputStream outputStream = null;
            BufferedImage image = producer.createImage(text);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
    
            BASE64Encoder encoder = new BASE64Encoder();
            String imageStr=encoder.encode(outputStream.toByteArray());
            //利用在线工具测试返回的base64编码的图片验证码字符串是否可以解析http://www.vgot.net/test/image2base64.php
            return imageStr;
        }

    2.方式二 ,获取图片验证码,图片验证码直接渲染到页面上

        /**
         * @Author zp
         * @Description //获取图片验证码,图片验证码直接渲染到页面上
         * @Date 23:30 2020/5/7
         * @Param [httpServletRequest, httpServletResponse]
         * @return void
         **/
        @GetMapping("/getCode")
        public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
            byte[] captchaChallengeAsJpeg = null;
            ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
            try {
                //生成文字验证码,为了进行校验,可将文字验证码存入redis中
                String createText = producer.createText();
    
                //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
                BufferedImage challenge = producer.createImage(createText);
                ImageIO.write(challenge, "jpg", jpegOutputStream);
            } catch (IllegalArgumentException e) {
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
            captchaChallengeAsJpeg = jpegOutputStream.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(captchaChallengeAsJpeg);
            responseOutputStream.flush();
            responseOutputStream.close();
        }

    第四步:验证码的校验

    验证码的校验时,前端需要将生成的验证码传到后端,后端进行比较。在生成验证码时,可将生成的文字验证码存入redis或session中,进行比较时需要从redis或session中获取,然后进行比较。代码省略。。。

  • 相关阅读:
    CSS3—— 2D转换 3D转换 过渡 动画
    CSS3——边框 圆角 背景 渐变 文本效果
    CSS3——表单 计数器 网页布局 应用实例
    CSS3——提示工具 图片廓 图像透明 图像拼接技术 媒体类型 属性选择器
    CSS3——对齐 组合选择符 伪类 伪元素 导航栏 下拉菜单
    CSS3——分组和嵌套 尺寸 display显示 position定位 overflow float浮动
    CSS3——盒子模型 border(边框) 轮廓(outline)属性 margin外边距 padding填充
    Eclipse连接数据库报错Local variable passwd defined in an enclosing scope must be final or effectively final
    数据库——单表查询
    数据库——添加,修改,删除
  • 原文地址:https://www.cnblogs.com/zhangpeng8888/p/12846682.html
Copyright © 2011-2022 走看看