ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

easy_captcha生成算术公式只要“十”和“X”和自定义公式替换

2021-11-13 11:34:43  阅读:205  来源: 互联网

标签:String 自定义 公式 chars arithmeticCaptcha captcha CaptchaUtils 计算公式 public


验证码格式不想要减法
之前在做项目的时候发现想要替换一下验证码的计算公式时总是会失败,不成功,在翻看ArithmeticCaptcha实现代码时发现自己的arithmeticCaptcha.setArithmeticString(obj) 方法只是修改了表层的数据,没有真正的修改为正确的数据当getArithmeticString()时还是原来的计算公式。因为在计算的时候他会去访问下面块代码,这里的意思是判断chars 是否为空。

.....
protected String chars = null;
.....
public void checkAlpha() {
        if (this.chars == null) {
            this.alphas();
        }
}

这里可以看到chars 是为空的。所以他会调用生成公式的方法alphas();为了避免这种发生。我呢做了以下操作:

1、首先需要自定义一个工具类
工具类需要继承ArithmeticCaptcha 这里我取名为CaptchaUtils

public class CaptchaUtils extends ArithmeticCaptcha {

    public CaptchaUtils() {
        super();
    }

    public CaptchaUtils(int width, int height) {
        super(width, height);
    }

    public void setChars(String chars) {
        super.chars = chars;
    }
}

2、使用main方法进行测试
最后的计算方式是我自己习惯性的调用的方法,如果您有更好的方式可以留言一起讨论下

 public static void main(String[] args) {
 	try{
	 	//使用我们自己写的工具类
	 	CaptchaUtils arithmeticCaptcha = new CaptchaUtils(140, 30);
	    // 几位数运算,默认是两位
	    arithmeticCaptcha.setLen(3);  
	    //原来生成的计算公式
	    System.out.println(arithmeticCaptcha.getArithmeticString()); 
	    //现在将公式中的“-”替换为“+”  
	    //这里的verifyCode可以换成自己想要的计算公式但是要符合原来生成的算法公式 如 9+2+8=?
	    String verifyCode=arithmeticCaptcha.getArithmeticString().replaceAll("-", "+"); 
	    //这个时候将新生成的公式放入
	    arithmeticCaptcha.setChars(verifyCode);
	    //将已有的公式替换掉
	    arithmeticCaptcha.setArithmeticString(verifyCode);
	    //输出计算公式
	    System.out.println(arithmeticCaptcha.getArithmeticString());
	    //公式进行计算
	    System.out.println(arithmeticCaptcha.text()); //这时候算出来的结果是不对的还是原来的计算公式
		//计算结果调用的方法   这里你有更好的计算方式也可以留言一起讨论
        String verifyCodes = verifyCode.replaceAll("x", "*");
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        String str =jse.eval(verifyCodes.substring(0, verifyCodes.length() - 2)).toString();
        System.out.println(str);//输出的正确答案
	} catch (Exception e) {
            System.out.println(e.getMessage());
        }
 }

标签:String,自定义,公式,chars,arithmeticCaptcha,captcha,CaptchaUtils,计算公式,public
来源: https://blog.csdn.net/weixin_42828203/article/details/121301188

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有