1. 1.引入kaptcha所需要的jar包
  2. <dependency>
  3. <groupId>com.github.penggle</groupId>
  4. <artifactId>kaptcha</artifactId>
  5. <version>2.3.2</version>
  6. </dependency>
  7. 2.配置kapcha
  8. @Configuration
  9. public class CaptchaConfig {
  10. @Bean(name="captchaProducer")
  11. public DefaultKaptcha getKaptchaBean(){
  12. DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
  13. Properties properties=new Properties();
  14. properties.setProperty("kaptcha.border""yes");
  15. properties.setProperty("kaptcha.border.color""105,179,90");
  16. properties.setProperty("kaptcha.textproducer.font.color""blue");
  17. properties.setProperty("kaptcha.image.width""125");
  18. properties.setProperty("kaptcha.image.height""45");
  19. properties.setProperty("kaptcha.session.key""code");
  20. properties.setProperty("kaptcha.textproducer.char.length""4");
  21. properties.setProperty("kaptcha.textproducer.font.names""宋体,楷体,微软雅黑");
  22. Config config=new Config(properties);
  23. defaultKaptcha.setConfig(config);
  24. return defaultKaptcha;
  25. }
  26. }
  27. 3.Controller中这样使用
  28. @RequestMapping(value = "/captcha-image")
  29. public ModelAndView getKaptchaImage(HttpServletRequest request,
  30. HttpServletResponse response) throws Exception {
  31. response.setDateHeader("Expires"0);
  32. response.setHeader("Cache-Control",
  33. "no-store, no-cache, must-revalidate");
  34. response.addHeader("Cache-Control""post-check=0, pre-check=0");
  35. response.setHeader("Pragma""no-cache");
  36. response.setContentType("image/jpeg");
  37. String capText = captchaProducer.createText();
  38. System.out.println("capText: " + capText);
  39. try {
  40. String uuid=UUIDUtils.getUUID32().trim().toString();
  41. redisTemplate.opsForValue().set(uuid, capText,60*5,TimeUnit.SECONDS);
  42. Cookie cookie = new Cookie("captchaCode",uuid);
  43. response.addCookie(cookie);
  44. catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. BufferedImage bi = captchaProducer.createImage(capText);
  48. ServletOutputStream out = response.getOutputStream();
  49. ImageIO.write(bi, "jpg", out);
  50. try {
  51. out.flush();
  52. finally {
  53. out.close();
  54. }
  55. return null;
  56. }
  57. 4.前台这样用
  58. <img style="height:22px;" id="codeImg" alt="点击更换"     title="点击更换" src="code/captcha-image" />