SysCaptchaController.java 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package com.ruoyi.web.controller.system;
  2. import java.awt.image.BufferedImage;
  3. import java.io.IOException;
  4. import javax.annotation.Resource;
  5. import javax.imageio.ImageIO;
  6. import javax.servlet.ServletOutputStream;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import javax.servlet.http.HttpSession;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.servlet.ModelAndView;
  14. import com.google.code.kaptcha.Constants;
  15. import com.google.code.kaptcha.Producer;
  16. import com.ruoyi.common.core.controller.BaseController;
  17. /**
  18. * 图片验证码(支持算术形式)
  19. *
  20. * @author ruoyi
  21. */
  22. @Controller
  23. @RequestMapping("/captcha")
  24. public class SysCaptchaController extends BaseController
  25. {
  26. @Resource(name = "captchaProducer")
  27. private Producer captchaProducer;
  28. @Resource(name = "captchaProducerMath")
  29. private Producer captchaProducerMath;
  30. /**
  31. * 验证码生成
  32. */
  33. @GetMapping(value = "/captchaImage")
  34. public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response)
  35. {
  36. ServletOutputStream out = null;
  37. try
  38. {
  39. HttpSession session = request.getSession();
  40. response.setDateHeader("Expires", 0);
  41. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  42. response.addHeader("Cache-Control", "post-check=0, pre-check=0");
  43. response.setHeader("Pragma", "no-cache");
  44. response.setContentType("image/jpeg");
  45. String type = request.getParameter("type");
  46. String capStr = null;
  47. String code = null;
  48. BufferedImage bi = null;
  49. if ("math".equals(type))
  50. {
  51. String capText = captchaProducerMath.createText();
  52. capStr = capText.substring(0, capText.lastIndexOf("@"));
  53. code = capText.substring(capText.lastIndexOf("@") + 1);
  54. bi = captchaProducerMath.createImage(capStr);
  55. }
  56. else if ("char".equals(type))
  57. {
  58. capStr = code = captchaProducer.createText();
  59. bi = captchaProducer.createImage(capStr);
  60. }
  61. session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
  62. out = response.getOutputStream();
  63. ImageIO.write(bi, "jpg", out);
  64. out.flush();
  65. }
  66. catch (Exception e)
  67. {
  68. e.printStackTrace();
  69. }
  70. finally
  71. {
  72. try
  73. {
  74. if (out != null)
  75. {
  76. out.close();
  77. }
  78. }
  79. catch (IOException e)
  80. {
  81. e.printStackTrace();
  82. }
  83. }
  84. return null;
  85. }
  86. }