Java 生成图片验证码

£神魔★判官ぃ 2023-10-13 16:13 140阅读 0赞

图片验证码使用场景

  • 登录注册:可以区分机器和人类的一种手段,其最大的作用是为了防止机器人程序暴力登录或攻击
  • 短信发送:可以有效避免客户网站或APP遭到恶意攻击、预防资金损失

实现方式

1.添加Maven依赖

  1. <dependency>
  2. <groupId>com.github.whvcse</groupId>
  3. <artifactId>easy-captcha</artifactId>
  4. <version>1.6.2</version>
  5. </dependency>

2.添加获取图片验证码接口

  1. @ApiOperation("获取图片验证码")
  2. @GetMapping("/captcha")
  3. public void captcha(HttpServletRequest request, HttpServletResponse response) {
  4. commService.create(request, response);
  5. }

注意:获取图片验证码时需要再请求地址后面加个参数key,key需保持唯一

3.实现方法

  1. @Override
  2. public void create(HttpServletRequest request, HttpServletResponse response) {
  3. String key = request.getParameter("key");
  4. if (StringUtils.isBlank(key)) {
  5. throw new NingException(500,"请输入key码");
  6. }
  7. ValidateCodeProperties code = new ValidateCodeProperties();
  8. setHeader(response, code.getType());
  9. Captcha captcha = createCaptcha(code);
  10. // 把验证码存进缓存中
  11. dataCache.setCacheImageValidCode(key, StringUtils.lowerCase(captcha.text()));
  12. try {
  13. captcha.out(response.getOutputStream());
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. throw new NingException(500,"图形验证码生成失败,请稍后再试!");
  17. }
  18. }
  19. private Captcha createCaptcha(ValidateCodeProperties code) {
  20. Captcha captcha = null;
  21. if (StringUtils.equalsIgnoreCase(code.getType(), "gif")) {
  22. captcha = new GifCaptcha(code.getWidth(), code.getHeight(), code.getLength());
  23. } else {
  24. captcha = new SpecCaptcha(code.getWidth(), code.getHeight(), code.getLength());
  25. }
  26. captcha.setCharType(code.getCharType());
  27. return captcha;
  28. }
  29. private void setHeader(HttpServletResponse response, String type) {
  30. if (StringUtils.equalsIgnoreCase(type, "gif")) {
  31. response.setContentType(MediaType.IMAGE_GIF_VALUE);
  32. } else {
  33. response.setContentType(MediaType.IMAGE_PNG_VALUE);
  34. }
  35. response.setHeader(HttpHeaders.PRAGMA, "No-cache");
  36. response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
  37. response.setDateHeader(HttpHeaders.EXPIRES, 0L);
  38. }

3.图片验证码配置类

  1. @Data
  2. public class ValidateCodeProperties {
  3. /**
  4. * 验证码有效时间,单位秒
  5. */
  6. private Long time = 120L;
  7. /**
  8. * 验证码类型,可选值 png和 gif
  9. */
  10. private String type = "png";
  11. /**
  12. * 图片宽度,px
  13. */
  14. private Integer width = 130;
  15. /**
  16. * 图片高度,px
  17. */
  18. private Integer height = 48;
  19. /**
  20. * 验证码位数
  21. */
  22. private Integer length = 4;
  23. /**
  24. * 验证码值的类型
  25. * 1. 数字加字母
  26. * 2. 纯数字
  27. * 3. 纯字母
  28. */
  29. private Integer charType = 2;
  30. }

5.OK,齐活~,上效果

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,140人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java生成图片验证

    功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。 VerifyCodeUtils类,生成图片流,然后不同框

    相关 生成图片验证

    问题描述 在项目中遇到有人恶意拉取图片资源,无限刷资源,导致阿里图片服务器流量暴涨(钱遭不住),使得带宽一直处于上限,正常用户不能好的访问。 解决办法 这个功能设