CaptchaController.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package com.ruoyi.web.controller.common;
  2. import java.awt.image.BufferedImage;
  3. import java.io.IOException;
  4. import java.util.concurrent.TimeUnit;
  5. import javax.annotation.Resource;
  6. import javax.imageio.ImageIO;
  7. import javax.servlet.http.HttpServletResponse;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.util.FastByteArrayOutputStream;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import com.google.code.kaptcha.Producer;
  14. import com.ruoyi.common.constant.Constants;
  15. import com.ruoyi.common.core.domain.AjaxResult;
  16. import com.ruoyi.common.core.redis.RedisCache;
  17. import com.ruoyi.common.utils.sign.Base64;
  18. import com.ruoyi.common.utils.uuid.IdUtils;
  19. /**
  20. * 验证码操作处理
  21. *
  22. * @author ruoyi
  23. */
  24. @RestController
  25. public class CaptchaController
  26. {
  27. @Resource(name = "captchaProducer")
  28. private Producer captchaProducer;
  29. @Resource(name = "captchaProducerMath")
  30. private Producer captchaProducerMath;
  31. @Autowired
  32. private RedisCache redisCache;
  33. // 验证码类型
  34. @Value("${ruoyi.captchaType}")
  35. private String captchaType;
  36. /**
  37. * 生成验证码
  38. */
  39. @GetMapping("/captchaImage")
  40. public AjaxResult getCode(HttpServletResponse response) throws IOException
  41. {
  42. // 保存验证码信息
  43. String uuid = IdUtils.simpleUUID();
  44. String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
  45. String capStr = null, code = null;
  46. BufferedImage image = null;
  47. // 生成验证码
  48. if ("math".equals(captchaType))
  49. {
  50. String capText = captchaProducerMath.createText();
  51. capStr = capText.substring(0, capText.lastIndexOf("@"));
  52. code = capText.substring(capText.lastIndexOf("@") + 1);
  53. image = captchaProducerMath.createImage(capStr);
  54. }
  55. else if ("char".equals(captchaType))
  56. {
  57. capStr = code = captchaProducer.createText();
  58. image = captchaProducer.createImage(capStr);
  59. }
  60. redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
  61. // 转换流信息写出
  62. FastByteArrayOutputStream os = new FastByteArrayOutputStream();
  63. try
  64. {
  65. ImageIO.write(image, "jpg", os);
  66. }
  67. catch (IOException e)
  68. {
  69. return AjaxResult.error(e.getMessage());
  70. }
  71. AjaxResult ajax = AjaxResult.success();
  72. ajax.put("uuid", uuid);
  73. ajax.put("img", Base64.encode(os.toByteArray()));
  74. return ajax;
  75. }
  76. }