很多网站都有验证码认证的功能。生成随机数,需要用户自己填写,之后进行认证。这是为了防止非法使用者利用工具工具网站。
以前有人自己写个工具类将生成的数字输出成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("调用输出图片流");
%>