百度空间 | 百度首页 
 
查看文章
 
jsp验证码刷新
2007-05-29 11:21

今天弄了一下JSP   验证码的问题   外加刷新。   把原代码共享一下:

image.jsp(生成图片页面)

<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
Color getRandColor(int fc,int bc){//给定范围获得随机颜色
         Random random = new Random();
         if(fc>255) fc=255;
         if(bc>255) bc=255;
         int r=fc+random.nextInt(bc-fc);
         int g=fc+random.nextInt(bc-fc);
         int b=fc+random.nextInt(bc-fc);
         return new Color(r,g,b);
         }
%>
<%
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

// 在内存中创建图象
int width=60, height=20;
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(new Color());
//g.drawRect(0,0,width-1,height-1);


// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
         int x = random.nextInt(width);
         int y = random.nextInt(height);
         int xl = random.nextInt(12);
         int yl = random.nextInt(12);
         g.drawLine(x,y,x+xl,y+yl);
}

// 取随机产生的认证码(4位数字)
String sRand="";
for (int i=0;i<4;i++){
     String rand=String.valueOf(random.nextInt(10));
     sRand+=rand;
     // 将认证码显示到图象中
     g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
     g.drawString(rand,13*i+6,16);
}

// 将认证码存入SESSION
session.setAttribute("rand",sRand);


// 图象生效
g.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());


%>

check.jsp(检测是否正确   ,并且可以刷新)

//检测是否正确

String Certification = request.getParameter("Certification");
    String rand = (String) session.getAttribute("rand");

if (Certification.equals(rand)) {
<a href="hi.baidu.com/mahaibao" >连接</a>

}

else

{

out
     .println("<script language='javascript'>alert('你的验证码错误,请重试!');javascript:history.go(-1);</script>");

}

//实现刷新

<script>

function reloadImage(url)
{
document.form1.img1.src = url;
}
</script>

<img name="img1" src="image.jsp" width="50"><a href="JavaScript:reloadImage('image.jsp');">看不清楚</a>


类别:Jsp | 添加到搜藏 | 浏览() | 评论 (1)
最近读者:
 
网友评论:
2
2008-08-13 11:28 | 回复
1
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     
 
精彩相册
   
     

©2009 Baidu