打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java生产验证码各种工具类

文章目录

  • 一、生成数字加减验证码
  • 二、糊涂工具类生产验证码
  • 三、Happy-captcha生产验证码
  • 四、easy-captcha生成验证码
  • 五、Kcaptcha生成验证码

一、生成数字加减验证码

1、工具类:

/**
 * @Author: Mr.ZJW
 * @Date: 2022-04-20 8:59
 * @Description: 验证码工具类
 */
@Data
public class ImageCode {

    //图形内容
    public String code;
    //图片
    public ByteArrayInputStream image;
    //宽
    private int wight = 400;
    //高
    private int height = 100;

    public static ImageCode getInstance() {
        return new ImageCode();
    }

    public ImageCode() {
        //图形缓冲区
        BufferedImage image = new BufferedImage(wight, height, BufferedImage.TYPE_3BYTE_BGR);
        //画笔
        Graphics graphics = image.getGraphics();
        //设置颜色
        graphics.setColor(new Color(46, 173, 144));
        //画矩形
        graphics.fillRect(0, 0, wight, height);
        //设置字体
        graphics.setFont(new Font("宋体", Font.PLAIN, 30));
        //设置随机数
        Random random = new Random();
        //算数验证码
        int num1 = random.nextInt(20);
        int num2 = random.nextInt(20);
        //设置颜色
        graphics.setColor(new Color(2, 0, 0));
        //画图
        int Y = 60;
        graphics.drawString(String.valueOf(num1), wight / 6 * 0 + 50, Y);
        graphics.drawString("+", wight / 6 * 1 + 50, Y);
        graphics.drawString(String.valueOf(num2), wight / 6 * 2 + 50, Y);
        graphics.drawString("=", wight / 6 * 3 + 50, Y);
        graphics.drawString("?", wight / 6 * 4 + 50, Y);
        //计算值
        int result = num1 + num2;
        this.code = result+"";
        //收笔
        graphics.dispose();

        ByteArrayInputStream inputStream = null;
        ByteOutputStream outputStream = new ByteOutputStream();

        //赋值给ByteArrayInputStream
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
            ImageIO.write(image, "jpg", imageOutputStream);

            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //生成图片
        this.image = inputStream;
    }


}

2、controller:
这里存放到redis中了,redis配置自行配。
也可以存放到session中,改为session就行。

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @Author: Mr.ZJW
     * @Description: 生成加减验证码
     * @Date: 2022/4/20 8:53
     * @param response*/
    @GetMapping("/generatorCode")
    public void generatorCode(HttpServletResponse response) {
        ImageCode imageCode = ImageCode.getInstance();
        //获取验证码内容
        String code = imageCode.getCode();
        //存放到Redis
        redisTemplate.opsForValue().set("Code",code);
        //获取图片
        ByteArrayInputStream image = imageCode.getImage();
        //设置内容类型
        response.setContentType("image/jpg");
        byte[] bytes = new byte[1024];
        try (ServletOutputStream outputStream = response.getOutputStream()){
            while (image.read(bytes) != -1){
                outputStream.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * @author: Mr.ZJW
     * @date: 2022/4/21 15:50
     * @description: 校验验证码
     */
    @GetMapping("/verifyCode")
    public String verifyCode(String code){
        //获取验证码结果
        String result = redisTemplate.opsForValue().get("Code");
        if (code.equals(result)) {
            return "success";
        }
        return "error";
    }

3、测试效果:

先请求生产验证码:这里答案是12


在请求校验接口看是否正确

二、糊涂工具类生产验证码

1、引入依赖

            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                 <version>5.7.21</version>
            </dependency>

2、生产验证码
这里是生成吧验证码生成一张图片,渲染到页面,前端直接拿就行

    /**
     * @author: Mr.ZJW
     * @date: 2022/4/21 11:51
     * @description: 生成验证码
     */
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,5);
        //存放到Redis
        redisTemplate.opsForValue().set("Code",lineCaptcha.getCode());
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            //验证码写到页面上
            lineCaptcha.write(outputStream);
            //关闭
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3、测试效果


校验跟同上,自行校验

三、Happy-captcha生产验证码

官网https://gitee.com/ramostear/Happy-Captcha?_from=gitee_search
1、导入依赖:

            <!--验证码工具类-->
            <dependency>
                <groupId>com.ramostear</groupId>
                <artifactId>Happy-Captcha</artifactId>
                <version>1.0.1</version>
            </dependency>

2、生产验证码:

    /**
     * @author: Mr.ZJW
     * @date: 2022/4/21 16:59
     * @description: Happy-Captcha工具类生成验证码
     */
    @GetMapping("/generateCode")
    public void generateCode(HttpServletResponse response, HttpServletRequest request){
        HappyCaptcha.require(request, response)
                .style(CaptchaStyle.ANIM)   //设置样式
                .build()
                .finish();
    }

	/**
     * @author: Mr.ZJW
     * @date: 2022/4/21 15:50
     * @description: 校验Happy-Captcha工具类生成的验证码
     */
    @GetMapping("/verifyHappyCaptcha")
    public String verifyHappyCaptcha(String code,HttpServletRequest request){
        boolean verification = HappyCaptcha.verification(request, code, true);
        if (verification) {
            //如果通过清楚当前验证码验证
            HappyCaptcha.remove(request);
            return "success";
        }
        return "error";
    }

3、测试:

四、easy-captcha生成验证码

依赖:

            <dependency>
                <groupId>com.github.whvcse</groupId>
                <artifactId>easy-captcha</artifactId>
                <version>1.6.2</version>
            </dependency>

1、生成验证码:

    /**
     * @author: Mr.ZJW
     * @date: 2022/4/21 15:50
     * @description: easyGenerateCode工具类生成的验证码
     */
    @GetMapping("/easyGenerateCode")
    public void easyGenerateCode(HttpServletResponse response, HttpServletRequest request) {
//        //生成普通验证码
//        SpecCaptcha specCaptcha = new SpecCaptcha();
        //生成算数验证码
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha();
        //设置2为算数
        arithmeticCaptcha.setLen(2);
        //验证码结果
        String content = arithmeticCaptcha.text();
        //存放到Redis中
        redisTemplate.opsForValue().set("code", content);
        try {
            com.wf.captcha.utils.CaptchaUtil.out(arithmeticCaptcha, request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2、效果:
普通验证码:


算数验证码:

五、Kcaptcha生成验证码

官网:https://gitee.com/

1、引入maven依赖:

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>kaptcha-spring-boot-starter</artifactId>
  <version>1.0.0</version>
</dependency>

2、在Controller使用Kaptcha:

@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

  @Autowired
  private Kaptcha kaptcha;

  //生成验证码
  @GetMapping("/render")
  public void render() {
    kaptcha.render();
  }

  //校验验证码
  @PostMapping("/valid")
  public void validDefaultTime(@RequestParam String code) {
    //default timeout 900 seconds
    kaptcha.validate(code);
  }

  //过期时间
  @PostMapping("/validTime")
  public void validWithTime(@RequestParam String code) {
    kaptcha.validate(code, 60);
  }

}

3、测试效果:

还有很多的样式以及格式自行测试

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Spring Boot + Redis 实现各种操作,写得太好了吧!
SpringBoot项目整合jasypt
springboot系列(一):初次使用与登录验证实现
maven和gradle的比较与使用
cas5开启Restful接口验证
利用gson将map转为json示例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服