ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

kaptcha谷歌验证码工具的使用

2020-05-07 23:58:03  阅读:293  来源: 互联网

标签:kaptcha 谷歌 httpServletResponse 验证码 setProperty properties 图片


基于前后端分离或者非前后端分离都可以使用的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中获取,然后进行比较。代码省略。。。

标签:kaptcha,谷歌,httpServletResponse,验证码,setProperty,properties,图片
来源: https://www.cnblogs.com/zhangpeng8888/p/12846682.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有