使用Google工具生成随机验证码

很多网站都有验证码认证的功能。生成随机数,需要用户自己填写,之后进行认证。这是为了防止非法使用者利用工具工具网站。

以前有人自己写个工具类将生成的数字输出成byte[]类型,之后再输出到前台页面。

这几天看到了Google Code有个开源项目kaptcha,用来生成随机验证码。十分好用。分享给大家

首先从google下载组件(http://code.google.com/p/kaptcha/downloads/detail?name=kaptcha-2.3.2.zip

解压缩后将kaptcha-X.jar包加入到自己项目的classpath中。

 

初始化该类代码如下

static DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

static {
    defaultKaptcha.setConfig(new Config(new Properties()));
}

 加载默认配置

使用如下

BufferedImage bufferedImage = defaultKaptcha.createImage(随机数);

ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
    ImageIO.write(bufferedImage, "jpg", out);
} catch (IOException e) {
    e.printStackTrace();
}
File file = new File("c:/1.jpg");
try {
    FileOutputStream fileOut = new FileOutputStream(file);
    fileOut.write(out.toByteArray());
} catch (FileNotFoundException e) {

} catch (IOException e) {

}

 

 运行后生成文件如下

 

byte[]输出到页面核心代码如下

<%
response.reset();
response.setContentType("image/jpeg ");

//不缓存
response.addHeader("pragma", "NO-cache");
response.addHeader("Cache-Control", "no-cache");

bytesum += byteread;
response.getOutputStream().write(buffer, 0, byteread);
		
response.getOutputStream().flush();
out.clear();
out = pageContext.pushBody();

//response.getOutputStream().close();
System.out.println("调用输出图片流");

%>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值