首先在maven项目中导入相关的jar包
1. <!-- 验证码生成--> 2. <dependency> 3. <groupId>com.github.penggle</groupId> 4. <artifactId>kaptcha</artifactId> 5. <version>2.3.2</version> 6. </dependency>
编写配置类,对生成图像的大小,字体颜色,字体大小等进行配置
1. @Configuration 2. public class KaptchaConfig { 3. 4. @Bean 5. public Producer kaptchaProducer() { 6. Properties properties = new Properties(); 7. properties.setProperty("kaptcha.image.width", "100"); 8. properties.setProperty("kaptcha.image.height", "40"); 9. properties.setProperty("kaptcha.textproducer.font.size", "32"); 10. properties.setProperty("kaptcha.textproducer.font.color", "0,0,0"); 11. properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ"); 12. properties.setProperty("kaptcha.textproducer.char.length", "4"); 13. properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); 14. 15. DefaultKaptcha kaptcha = new DefaultKaptcha(); 16. Config config = new Config(properties); 17. kaptcha.setConfig(config); 18. return kaptcha; 19. } 20. 21. }
实现验证码接口,并将验证码id存入cookie和redis
1. @RequestMapping(path = "/kaptcha", method = RequestMethod.GET) 2. public void getKaptcha(HttpServletResponse response/*, HttpSession session*/) { 3. // 生成验证码 4. String text = kaptchaProducer.createText(); 5. BufferedImage image = kaptchaProducer.createImage(text); 6. 7. // 将验证码存入session 8. // session.setAttribute("kaptcha", text); 9. 10. // 验证码的归属 11. String kaptchaOwner = CommunityUtil.generateUUID(); 12. Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner); 13. cookie.setMaxAge(60); 14. cookie.setPath(contextPath); 15. response.addCookie(cookie); 16. // 将验证码存入Redis 17. String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner); 18. redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS); 19. 20. // 将突图片输出给浏览器 21. response.setContentType("image/png"); 22. try { 23. OutputStream os = response.getOutputStream(); 24. ImageIO.write(image, "png", os); 25. } catch (IOException e) { 26. logger.error("响应验证码失败:" + e.getMessage()); 27. } 28. }
测试:
源代码