EasyCaptcha是一个基于Java开发的图形验证码工具,项目地址为: https://github.com/pig-mesh/easy-captcha

1. 引入依赖

  1. <dependency>
  2. <groupId>com.pig4cloud.plugin</groupId>
  3. <artifactId>captcha-spring-boot-starter</artifactId>
  4. <version>2.2.0</version>
  5. </dependency>

使用教程在项目地址中已经有了,这里直接贴出demo代码。

后端

  1. @RestController
  2. @RequestMapping("/captcha")
  3. @CrossOrigin
  4. public class CaptchaController {
  5. private RedisUtils redisUtils;
  6. @GetMapping("/get")
  7. public ResultVO getCaptcha() {
  8. // 新建一个算数验证码,并且指定了宽和高(验证码图片的尺寸)
  9. Captcha captcha = new ArithmeticCaptcha(111, 36);
  10. // 设置算数验证的长度。2表示2位数运算
  11. captcha.setLen(2);
  12. // 验证码的结果值
  13. String captchaValue = captcha.text();
  14. // 验证码的图片url
  15. String codeUrl = captcha.toBase64();
  16. // 将结果封装到map中返回给前端
  17. HashMap<String, String> map = new HashMap<>();
  18. map.put("captchaValue", captchaValue);
  19. map.put("codeUrl", codeUrl);
  20. return new ResultVO(10000, map);
  21. }
  22. }

一般来说验证码为保证时效性,是要存储进redis的,这里为了测试方便,没有存进redis,直接返回给前端了。

前端

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>easy-captcha测试</title>
  6. <script type="application/javascript" src="js/axios.min.js"></script>
  7. <script type="application/javascript" src="js/vue.js"></script>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <div>
  12. <img :src="captchaImgSrc" @click="changeCaptcha" height="36px" width="111px" border="1px;" /><br />
  13. <input type="text" v-model="inputValue" /><button type="button" @click="pressOk">确认</button>
  14. </div>
  15. </div>
  16. <script type="application/javascript">
  17. var vm = new Vue({
  18. el: "#app",
  19. data: {
  20. captchaImgSrc: "",
  21. captchaValue: "",
  22. inputValue: ""
  23. },
  24. // 钩子函数,在页面加载,data初始化之后执行,向后端发送请求,获取验证码信息
  25. created() {
  26. axios.get("http://localhost:8080/captcha/get").then(res => {
  27. var vo = res.data;
  28. vm.captchaImgSrc = vo.data.codeUrl;
  29. vm.captchaValue = vo.data.captchaValue;
  30. });
  31. },
  32. methods: {
  33. // 提交验证码后判断对错
  34. pressOk: function() {
  35. if (this.captchaValue === this.inputValue) {
  36. alert("验证码输入正确!");
  37. } else {
  38. alert("验证码输入错误!");
  39. }
  40. },
  41. // 点击验证码刷新
  42. changeCaptcha: function() {
  43. axios.get("http://localhost:8080/captcha/get").then(res => {
  44. var vo = res.data;
  45. vm.captchaImgSrc = vo.data.codeUrl;
  46. vm.captchaValue = vo.data.captchaValue;
  47. });
  48. }
  49. }
  50. })
  51. </script>
  52. </body>
  53. </html>