日期:2014-05-18  浏览次数:20628 次

这样的验证码怎样实现?
偶看到一个网站上的验证码在图片上显示的中文,但在实际输入时,不需要输入中文,而是输入它对应的数字就可以了,难道还需要再做一个对应表?
可能我的描述不是很清楚,大家可以看一下他的验证码,在http://www.vpnlife.com,他的图片就是中文的。
我在网上也搜索了一下,关于做中文验证码的文章倒是不少,但都是需要输入中文的,我也想弄一个象他那样,显示中文,实际不需要输入中文的。

------解决方案--------------------
我的想法很简单,放入session的验证码其实就是数字,但是在显示验证码的时候,根据相对的数字换成对应的汉字就是了.
例如1234是我生成的验证码,但是我在write图片的时候把它显示成一二三四..


------解决方案--------------------
Java code
import java.util.Random;

public class Test01 {   
    
    public static void main(String[] args) {
        VerifyCode code = new VerifyCode(5);
        
        char[] chns = code.getNumName();
        char[] chs = code.getRanNums();
        
        System.out.println(chs);
        System.out.println(chns);
        
        code.reset();
        chs = code.getRanNums();
        chns = code.getNumName();
        
        System.out.println(chs);
        System.out.println(chns);
    }
}


class VerifyCode {
    private int digit = 0;
    private char[] chs = null;
    private char[] chns = null;
    
    private final static char[] CHN_NAMES = {
            '洞', '幺', '两', '叁', '肆',
            '伍', '陆', '拐', '捌', '勾'
        };
    
    public VerifyCode(int digit) {
        this.digit = digit;
    }
    
    public char[] getRanNums() {        
        init();        
        return chs;
    }

    public char[] getNumName() {
        if(chns == null) {
            init();
            chns = new char[chs.length];
            for(int i = 0; i < chs.length; i++) {
                chns[i] = CHN_NAMES[chs[i] - '0'];
            }
        }            
        return chns;
    }
    
    public void reset() {
        chs = null;
        chns = null;        
    }
    
    private void init() {
        if(chs != null) {
            return;
        }
        chs = new char[digit];
        Random ran = new Random();
        for(int i = 0; i < chs.length; i++) {
            chs[i] = (char)(ran.nextInt(10) + '0');
        }
    }
}