CaptchaHelp.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package com.qxgmat.help;
  2. import com.google.code.kaptcha.impl.DefaultKaptcha;
  3. import com.google.code.kaptcha.util.Config;
  4. import com.qxgmat.data.constants.SessionKey;
  5. import org.springframework.stereotype.Service;
  6. import javax.servlet.http.HttpSession;
  7. import java.awt.image.BufferedImage;
  8. import java.util.Properties;
  9. /**
  10. * Created by GaoJie on 2017/11/3.
  11. */
  12. @Service
  13. public class CaptchaHelp {
  14. private static DefaultKaptcha kaptcha;
  15. static {
  16. kaptcha = new DefaultKaptcha();
  17. Properties properties = new Properties();
  18. properties.setProperty("kaptcha.image.width", "100");
  19. properties.setProperty("kaptcha.image.height", "50");
  20. properties.setProperty("kaptcha.textproducer.char.length", "4");
  21. kaptcha.setConfig(new Config(properties));
  22. }
  23. public boolean verify(String captcha, HttpSession session){
  24. String code = (String) session.getAttribute(SessionKey.CAPTCHA_KEY);
  25. session.removeAttribute(SessionKey.CAPTCHA_KEY);
  26. return code.equalsIgnoreCase(captcha);
  27. }
  28. public BufferedImage createImage(HttpSession session) {
  29. return kaptcha.createImage(create(session));
  30. }
  31. private String create(HttpSession session){
  32. String code = kaptcha.createText();
  33. session.setAttribute(SessionKey.CAPTCHA_KEY, code);
  34. return code;
  35. }
  36. }