软件编程
位置:首页>> 软件编程>> java编程>> Springboot通过谷歌Kaptcha 组件生成图形验证码功能

Springboot通过谷歌Kaptcha 组件生成图形验证码功能

作者:算死草  发布时间:2021-07-24 23:42:47 

标签:Springboot,Kaptcha,图形,验证码

图形验证码属于老生常谈了,具体细节这里就不说了。生成图形验证码的办法非常多,今天讲解一种通过Kaptcha组件快速生成图形验证码的方法。
Kaptcha是谷歌开源的一款简单实用的图形验证码组件。我个人推荐它的最大原因是容易上手,采用约定大于配置的方式,快速契合到项目中。
话不多说,我们看看该如何使用它:
一、首先我们在springboot中引入以下maven组件:

<dependency>
    <groupId>com.google.code.kaptcha</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3</version>
</dependency>

如果上述组件你一直无法拉取下来的话,也可以用如下配置:

<dependency>
     <groupId>com.github.penggle</groupId>
     <artifactId>kaptcha</artifactId>
     <version>2.3.2</version>
 </dependency>

二、接着我们在springboot项目中加入对应的config配置类,(防盗连接:本文首发自http://www.cnblogs.com/jilodream/ )这一步也可以配合配置中心来完成。它的作用是自动生成我们所需的config bean。

其中的配置项我们都可以选填,这里是只是一个参考,具体内容可见下文表

@Component
public class KaptchaConfig {
   @Bean
   public DefaultKaptcha getDefaultKaptcha(){
       com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
       Properties properties = new Properties();
       properties.put("kaptcha.border", "no");
       properties.put("kaptcha.textproducer.font.color", "red");
       properties.put("kaptcha.image.width", "213");
       properties.put("kaptcha.image.height", "88");
       properties.put("kaptcha.textproducer.font.size", "45");
       properties.put("kaptcha.session.key", "verifyCode");
       properties.put("kaptcha.textproducer.char.space", "6");
       properties.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
      // properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
       properties.put("kaptcha.background.clear.from", "yellow");
       properties.put("kaptcha.background.clear.to", "green");
       Config config = new Config(properties);
       defaultKaptcha.setConfig(config);
       return defaultKaptcha;
   }
}

配置表

配置名配置作用默认值
kaptcha.border图片边框,合法值:yes , noyes
kaptcha.border.color边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.black
kaptcha.image.width图片宽200
kaptcha.image.height图片高50
kaptcha.producer.impl图片实现类com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl文本实现类com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string文本集合,验证码值从此集合中获取abcde2345678gfynmnpwx
kaptcha.textproducer.char.length验证码长度5
kaptcha.textproducer.font.names字体Arial, Courier
kaptcha.textproducer.font.size字体大小40px.
kaptcha.textproducer.font.color字体颜色,合法值: r,g,b 或者 white,black,blue.black
kaptcha.textproducer.char.space文字间隔2
kaptcha.noise.impl干扰实现类com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color干扰 颜色,合法值: r,g,b 或者 white,black,blue.black
kaptcha.obscurificator.impl

图片样式:<br />水纹 com.google.code.kaptcha.impl.WaterRipple <br />

鱼眼 com.google.code.kaptcha.impl.FishEyeGimpy <br />

阴影 com.google.code.kaptcha.impl.ShadowGimpy

com.google.code.kaptcha.impl.WaterRipple
kaptcha.background.impl背景实现类com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from背景颜色渐变,开始颜色light grey
kaptcha.background.clear.to背景颜色渐变, 结束颜色white
kaptcha.word.impl文字渲染器com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.keysession keyKAPTCHA_SESSION_KEY
kaptcha.session.datesession dateKAPTCHA_SESSION_DATE

三、创建好config bean之后,我们就可以创建接口来生成验证码了controller类,新增接口:

@GetMapping("/login/getVerifyCode")
   public void getVerifyCode(String loginKey,
                             HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse) {
       try {
           log.warn("query verify Code" + loginKey);
           loadService.getVerifyCode(loginKey, httpServletRequest, httpServletResponse);
       } catch (Exception e) {
           log.error("get verify Code failed :", e);
       }
   }

service类,新增逻辑:

public void getVerifyCode(String loginKey, HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse) throws IOException {
       ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
       try {
           //生产验证码字符串并保存到session中
           String verifyCode = captchaProducer.createText();
           // httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);  // 写入会话
           //redisCache.setVerifyInfo(loginKey, verifyCode);   //写入redis
           captchaMap.put(loginKey, verifyCode);//写入内存
           log.warn("reset verify code key {}, code {}", loginKey, verifyCode);
           BufferedImage challenge = captchaProducer.createImage(verifyCode);
           ImageIO.write(challenge, "jpg", imgOutputStream);
       } catch (IllegalArgumentException | IOException e) {
           httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
           return;
       }
       byte[] captchaOutputStream = imgOutputStream.toByteArray();
       httpServletResponse.setHeader("Cache-Control", "no-store");
       httpServletResponse.setHeader("Pragma", "no-cache");
       httpServletResponse.setDateHeader("Expires", 0);
       httpServletResponse.setContentType("image/jpeg");
       try (ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream()) {
           responseOutputStream.write(captchaOutputStream);
           responseOutputStream.flush();
       } catch (IOException ex) {
           log.error("find ex in create a new verify Code", ex);
       }
   }

相关代码全部开发完毕后,我们调用接口查看效果:

Springboot通过谷歌Kaptcha 组件生成图形验证码功能

这里我发现一个在本地环境使用ok,(防盗连接:本文首发自http://www.cnblogs.com/jilodream/ )但是在使用docker部署微服务时却存在的一个异常:

java.lang.NullPointerException: null
        at sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264)
        at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:219)
        at sun.awt.FontConfiguration.init(FontConfiguration.java:107)
.....

网上查了下,大致原因是由于我们本地使用的是oraclejdk,但是在docker中jdk的版本则采用的是openjdk。openjdk有些字体的支撑不是很友好,这里需要在制作docker镜像时添加如下语句解决:

RUN apk add --update font-adobe-100dpi ttf-dejavu fontconfig 

来源:https://www.cnblogs.com/jilodream/p/17402275.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com