Springboot图片验证码

1、依赖引入

//图片验证码依赖
<dependency>
  <groupId>com.baomidougroupId>
  <artifactId>kissoartifactId>
  <version>3.8.1version>
dependency>

//安装 EasyCaptcha 依賴
<dependency>
  <groupId>com.github.whvcsegroupId>
  <artifactId>easy-captchaartifactId>
  <version>1.6.2version>
dependency>

2、配置类

@Bean
public ImageCaptcha imageCaptcha() {
    ImageCaptcha imageCaptcha = ImageCaptcha.getInstance();
    // 干扰量 1
    imageCaptcha.setInterfere(1);
    // 验证码内容长度 4 位
    imageCaptcha.setLength(4);
    // Gif 验证码
    // imageCaptcha.setGif(true);
    // 验证码存储处理类,默认存在在 session 实现类 CaptchaStoreSession 仅适用单机
    // 分布式可以采用 Redis 处理,例如 RedisCaptchaStore 实现 ICaptchaStore 接口
    // imageCaptcha.setCaptchaStore(new CaptchaStoreRedis());
    return imageCaptcha;
}

3、图片验证码生成验证

@RestController
@RequestMapping("/v1/captcha")
public class CaptchaController {
    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;
    @Resource
    private ICaptcha captcha;

    // 生成验证,例如:http://localhost:8088/v1/captcha/image?ticket=123456
    @GetMapping("/image")
    public void image(String ticket) {
        try {
            // 验证码信息存放在缓存中,key = ticket 、 value = 验证码文本内容
            captcha.generate(request, response.getOutputStream(), ticket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 校验图片验证码
    @PostMapping("/verification")
    public boolean verification(String ticket, String code) {
        // ticket 为生成验证码的票据, code 为图片验证码文本内容
        return captcha.verification(request, ticket, code);
    }
}

4、效果:
Springboot图片验证码_第1张图片
具体步骤连接:http://aizuda.com/

你可能感兴趣的:(java,kafka,zookeeper)