Welcome

首页 / 网页编程 / JSP / JSP验证码大全之中文验证码

JSP验证码大全之中文验证码2011-08-06即兴的灵感在上一篇内容中介绍了有关JSP中产生数字验证码图片的过程,本文将继续介绍有关JSP中的另一种验 证码的实现,即中文验证码在JSP中的实现,使用中文验证码的好处是能提高验证的有效性,提高验证的 安全度,因为中文相对于英文或数字笔画结构相对比较复杂,从而增加了分析程序解析验证码图片并读取 验证信息的难度。在文中并分析中文验证的实现过程。

二、JSP中实现中文验证码源码如下:

ChineseVal.jsp
<%@ page pageEncoding = "gb2312" contentType="image/jpeg" import = "javax.imageio.*,java.util.*,java.awt.image.*,java.awt.*" %>
<%!
//在此处 获取并生成随机颜色
Color getRandColor(Random random, int ff, int cc) {
if (ff > 255)
ff = 255;
if (cc > 255)
cc = 255;
int r = ff + random.nextInt(cc - ff);
int g = ff + random.nextInt(cc - ff);
int b = ff + random.nextInt(cc - ff);
return new Color(r, g, b);
} %>
<%
//在此处 设置JSP页面无缓存
response.setHeader( "Pragma" , "No-cache" );
response.setHeader( "Cache-Control" , "no-cache" );
response.setDateHeader( "Expires" , 0);
// 设置图片的长宽
int width = 130;
intheight = 30;
//设定被随机选取的中文字,此处中文字内容过多,不一一列出,只是举例说明下。
String base = "u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03 u5973u4efbu4ef6u611fu51c6u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u538bu6162 u53d4u80ccu7ec6...省略文字。。。" ;
//设 置 备选随机汉字的个数
int length = base.length();
// 创建缓存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图像
Graphics g = image.getGraphics();
// 创建随机函数的实例
Random random = new Random(); //此处 设定图像背景色
g.setColor(getRandColor(random, 188, 235));
g.fillRect(0, 0, width, height);
//设置随机 备选的字体类型
String[] fontTypes = { "u5b8bu4f53" , "u65b0u5b8bu4f53" ,
"u9ed1u4f53" , "u6977u4f53" , "u96b6u4e66" };
int fontTypesLength = fontTypes.length;
// 在图片背景上增加噪点,增加图片分析难度
g.setColor(getRandColor(random, 180, 199));
g.setFont( new Font( "Times New Roman" , Font.PLAIN, 14));
for ( int i = 0; i < 4; i++) {
g.drawString( "@*@*@*@*@*@*@*" ,
0, 5 * (i + 2));
}
// 取随机产生的验证码 (4 个汉字 )
// 保存生成的汉字字符串
String sRand = "" ;
for ( int i = 0; i < 4; i++) {
int start = random.nextInt(length);
String rand = base.substring(start, start + 1);
sRand += rand;
// 设置图片上字体的颜色
g.setColor(getRandColor(random, 10, 150));
// 设置字体格式
g.setFont( new Font(fontTypes[random.nextInt(fontTypesLength)],
Font.BOLD, 18 + random.nextInt(6)));
// 将此汉字画到验证图片上面
g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);
} // 将验证码存入S ession中
session.setAttribute( "rand" , sRand);
g.dispose();
//将 图象输出到JSP页面中
ImageIO.write(image, "JPEG" , response.getOutputStream());
//关闭流
out.clear();
out=pageContext.pushBody();
%>

以上就是JSP中产生中文验证码过程的源码分析,由中文作为验证码存在于JSP页面中,将会存在JSP中 文乱码的现象,接下来文章将介绍如何调用JSP验证码和使用的方法,以及如何解决JSP中文验证码乱码问 题和其他JAVA验证码的实现。

下文将介绍有关JSP中文验证码的乱码问题解决方法以及JSP中调用以上两种验证码的方法。