若依自帶的驗證碼樣式比較單一,所以想改用EasyCaptcha驗證碼,另外EasyCaptcha算術驗證碼可能會有負數,輸入時需要寫負號,比較麻煩,所以使用一個簡單的方法過濾掉負數結果
原本的驗證碼依賴和代碼可刪可不刪,注釋掉即可
-
在父模塊添加依賴
<properties><captcha.version>1.6.2</captcha.version> </properties><dependencyManagement><dependencies> <!-- EasyCaptcha驗證碼依賴 --><dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId><version>${captcha.version}</version></dependency></dependencies> </dependencyManagement>
-
ruoyi-admin模塊中添加依賴
<!-- 驗證碼 --> <dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId> </dependency>
-
找到
CaptchaController,java
,修改getCode
方法public AjaxResult getCode(HttpServletResponse response) throws IOException, FontFormatException {AjaxResult ajax = AjaxResult.success();boolean captchaEnabled = configService.selectCaptchaEnabled();ajax.put("captchaEnabled", captchaEnabled);if (!captchaEnabled){return ajax;}// 保存驗證碼信息String uuid = IdUtils.simpleUUID();String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;//新驗證碼//圖形驗證碼//SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);//算術驗證碼ArithmeticCaptcha captcha;String code;captcha = new ArithmeticCaptcha(130, 48);//得到驗證碼的值code = captcha.text();//若為負數則重新生成int i = Integer.parseInt(code);while (i < 0){System.out.println("code = " + code + ",負數,重新生成!!!!!!!!");captcha = new ArithmeticCaptcha(130, 48);code = captcha.text();i = Integer.parseInt(code);System.out.println("i = " + i + ",新值!!!");}// 設置內置字體captcha.setFont(Captcha.FONT_1);//captcha.setLen(2); // 幾位數運算,默認是兩位//captcha.getArithmeticString(); // 獲取運算的公式//存入redisredisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);//舊驗證碼//String capStr = null, code = null;//BufferedImage image = null;// 生成驗證碼//String captchaType = RuoYiConfig.getCaptchaType();//if ("math".equals(captchaType))//{// String capText = captchaProducerMath.createText();// capStr = capText.substring(0, capText.lastIndexOf("@"));// code = capText.substring(capText.lastIndexOf("@") + 1);// image = captchaProducerMath.createImage(capStr);//}//else if ("char".equals(captchaType))//{// capStr = code = captchaProducer.createText();// image = captchaProducer.createImage(capStr);//}////redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); 轉換流信息寫出//FastByteArrayOutputStream os = new FastByteArrayOutputStream();//try//{// ImageIO.write(image, "jpg", os);//}//catch (IOException e)//{// return AjaxResult.error(e.getMessage());//}ajax.put("uuid", uuid);ajax.put("img", captcha.toBase64());return ajax;}
另外,歡迎大家來我的博客——火柴人兒的小站來玩~