Kaptcha(卡普查)来完成验证码的生成。 Kaptcha是一个非常实用的验证码生成工具
<dependency>
? ?<groupId>com.github.penggle</groupId>
? ?<artifactId>kaptcha</artifactId>
? ?<version>2.3.2</version>
</dependency>
编写获取图形验证码的方法
private final DefaultKaptcha kaptcha;
/**
* 获取图片验证码
* @param httpServletRequest
* @param httpServletResponse
*/
@GetMapping("/imageCode/{clientToken}")
public void getImageCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,@PathVariable String clientToken) throws IOException {
? ?ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
? ?String createText = kaptcha.createText();
? ?BufferedImage challenge = kaptcha.createImage(createText);
? ?ImageIO.write(challenge, "jpg", jpegOutputStream);
? ?byte[] captchaChallengeAsJpeg ?= jpegOutputStream.toByteArray();
? ?httpServletResponse.setContentType("image/jpeg");
? ?ServletOutputStream responseOutputStream =
? ? ? ? ? ?httpServletResponse.getOutputStream();
? ?responseOutputStream.write(captchaChallengeAsJpeg);
? ?responseOutputStream.flush();
? ?responseOutputStream.close();
? ?//将验证码存入redis 2分钟超时
? ?redisTemplate.boundValueOps(clientToken).set(createText,120, TimeUnit.SECONDS);
}
?访问接口返回