验证码应用在各种 场合中,十分广泛,在多种 多样的
系统或软件中的新用户帐户注册,用户 登录,网站统一
登陆或者用户在网站发布信息模块发布文章或内容都添加的随机码功能,对用 户操作过程进行一种 验证,使用验证码的目的就是为了避免
网络中的自动
注册程序或者自动 发布程序的滥用. 验证码的原理其实就是随机选择一些字符码以将字符码以图片的形式展现 在
软件验证界面或验证页面上,当用户在进行提交操作的同时需要将图片上的验证码输入并 同时提交,如果提交的字符验证码与服务器 session 保存的字符码相同,则认为提交信息有 效,否则拒绝提交.在使用验证码过程中,为了避免自动分析
程序解析图片并获得验证信息, 通常需要在图片上随机生成一些干扰线或者将复 杂的字符对图片进行扭曲模糊,从而增加了 自动识别程序分析验证图片的难度. JSP 验证码源码大全将分别用几个篇幅的内容来介绍在 JSP 中几种 验证码的实现源码以及 使用. 生数字验证码 验证码源 一,JSP 中产生数字验证码源码 数字验证码是一种 最
常用的验证字符码形式,以下为数字实现的
JSP 源码:
Num.jsp <%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*, java.util.*,javax.imageio.*" %> <%! Color getRandColor(int cc,int bb) { Random random = new Random(); if(fc>255) cc=255; if(bc>255) bb=255; int r=cc+random.nextInt(bb-cc); int g=cc+random.nextInt(bb-cc); int b=cc+random.nextInt(bb-cc); returnnew Color(r,g,b); } //获取随机颜色
%> <% response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0);
int width=80; //定义验证码图片的长度 int height=30; //定义验证码图片的宽度
BufferedImage image = new BufferedImage(width,height,BufferedImage. TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200,250)); g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
//定义字体形式
g.setColor(getRandColor(160,200)); for (int i=0;i<155;i++) { int i_x = random.nextInt(width); int i_y = random.nextInt(height); int i_xl = random.nextInt(12); int i_yl = random.nextInt(12); g.drawLine(i_x,i_y,i_x+i_xl,i_y+i_yl); }
//用线条画背景
String s_Rand=""; for (int i=0;i<4;i++) { String rand=String.valueOf(random.nextInt(10)); s_Rand+=rand;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(1 10),20+random.nextInt(110))); g.drawString(rand,13*i+6,16);
}
//产生 4 位随机码
session.setAttribute("rand",s_Rand);
//将验证码存入 Session 中
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
//输出验证图片
out.clear(); out = pageContext.pushBody();
%>
接下来文章将介绍 JSP 中的中文验证码,其他 JAVA 验证码的实现以及对 JSP 中
对验证码的 调用和使用的有关 内容,下一篇文章将介绍有关 JSP 中文验证码的源码实现.