验证码应用在各种场合中,十分广泛,在多种多样的系统或软件中的新用户帐户注册、用户登录、网站统一登陆或者用户在网站发布信息模块发布文章或内容都添加的随机码功能,对用户操作过程进行一种验证,使用验证码的目的就是为了避免网络中的自动注册程序或者自动发布程序的滥用。 验证码的原理其实就是随机选择一些字符码以将字符码以图片的形式展现在软件验证界面或验证页面上,当用户在进行提交操作的同时需要将图片上的验证码输入并同时提交,如果提交的字符验证码与服务器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(110),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中文验证码的源码实现。
【JSP验证码大全之数字验证码】相关文章:
