栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【springboot系列】springboot实现图片验证码captcha

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【springboot系列】springboot实现图片验证码captcha

使用 1、导入依赖

在maven仓库中查找,发现只有这个依赖,所以直接复制这个即可


        
            com.github.whvcse
            easy-captcha
            1.6.2
        
2、使用

总共有这么多种验证类型

3、测试
package com.walker.third.easyCaptcha;

import com.wf.captcha.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class CaptchaController {


    
    @GetMapping("/arithmeticCaptcha")
    public void captcha(HttpServletResponse response) throws IOException {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(138, 54);
        captcha.setLen(3);
        String arithmeticString = captcha.getArithmeticString();
        //获取算数过程的字符串
        System.out.println(arithmeticString);
        //获取算数结果
        System.out.println(captcha.text());

        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        captcha.out(response.getOutputStream());
    }


    
    @GetMapping("chineseCaptcha")
    public void chineseCaptcha(HttpServletResponse response) throws IOException {

        ChineseCaptcha chineseCaptcha = new ChineseCaptcha();
        chineseCaptcha.setLen(5);

        chineseCaptcha.out(response.getOutputStream());
    }

    
    @GetMapping("gifCaptcha")
    public void gifCaptcha(HttpServletResponse response) throws IOException {
        GifCaptcha gifCaptcha = new GifCaptcha();
        gifCaptcha.out(response.getOutputStream());
    }

    
    @GetMapping("chineseGifCaptcha")
    public void chineseGifCaptcha(HttpServletResponse response) throws IOException {
        ChineseGifCaptcha chineseGifCaptcha = new ChineseGifCaptcha();
        chineseGifCaptcha.out(response.getOutputStream());
    }


    
    @GetMapping("specCaptcha")
    public void spec(HttpServletResponse response) throws IOException {
        SpecCaptcha specCaptcha = new SpecCaptcha();
        specCaptcha.out(response.getOutputStream());

    }
}

具体结果如下:
算数ArithmeticCaptcha:

中文ChineseCaptcha:

GifCaptcha
不断闪烁

SpecCaptcha:英文字母

中文gif:中文不断闪烁

4、最佳实践

可以将其与uuid和验证码结果保存在缓存中,如果是本地,可以保存在guava中,也可以保存在redis中,或者mysql数据库也可以(在数据量相对较小的情况下)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936872.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号