SpringBoot使用kaptcha验证码

  1. 1.引入kaptcha所需要的jar包

  2. com.github.penggle

  3. kaptcha

  4. 2.3.2

  5. 2.配置kapcha

  6. @Configuration

  7. public class CaptchaConfig {

  8. @Bean(name="captchaProducer")

  9. public DefaultKaptcha getKaptchaBean(){

  10. DefaultKaptcha defaultKaptcha=new DefaultKaptcha();

  11. Properties properties=new Properties();

  12. properties.setProperty("kaptcha.border", "yes");

  13. properties.setProperty("kaptcha.border.color", "105,179,90");

  14. properties.setProperty("kaptcha.textproducer.font.color", "blue");

  15. properties.setProperty("kaptcha.image.width", "125");

  16. properties.setProperty("kaptcha.image.height", "45");

  17. properties.setProperty("kaptcha.session.key", "code");

  18. properties.setProperty("kaptcha.textproducer.char.length", "4");

  19. properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");

  20. Config config=new Config(properties);

  21. defaultKaptcha.setConfig(config);

  22. return defaultKaptcha;

  23. }

  24. }

  25. 3.Controller中这样使用

  26. @RequestMapping(value = "/captcha-image")

  27. public ModelAndView getKaptchaImage(HttpServletRequest request,

  28. HttpServletResponse response) throws Exception {

  29. response.setDateHeader("Expires", 0);

  30. response.setHeader("Cache-Control",

  31. "no-store, no-cache, must-revalidate");

  32. response.addHeader("Cache-Control", "post-check=0, pre-check=0");

  33. response.setHeader("Pragma", "no-cache");

  34. response.setContentType("image/jpeg");

  35. String capText = captchaProducer.createText();

  36. System.out.println("capText: " + capText);

  37. try {

  38. String uuid=UUIDUtils.getUUID32().trim().toString();

  39. redisTemplate.opsForValue().set(uuid, capText,60*5,TimeUnit.SECONDS);

  40. Cookie cookie = new Cookie("captchaCode",uuid);

  41. response.addCookie(cookie);

  42. } catch (Exception e) {

  43. e.printStackTrace();

  44. }

  45. BufferedImage bi = captchaProducer.createImage(capText);

  46. ServletOutputStream out = response.getOutputStream();

  47. ImageIO.write(bi, "jpg", out);

  48. try {

  49. out.flush();

  50. } finally {

  51. out.close();

  52. }

  53. return null;

  54. }

  55. 4.前台这样用

  56. 点击更换

【喜欢这类文章可以关注我,我会继续发布类似文章,谢谢】

SpringBoot使用kaptcha验证码


分享到:


相關文章: