博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

苦丁茶

tomcent.cublog.cn
JSP图片验证码

<%@page contentType ="text/html; charset=GBK" %>
<%@ page import="java.awt.*"%>
<%@ page import="java.awt.image.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.imageio.*"%>
<%
    //在内存中创建图象

    int iWidth = 70, iHeight = 18;
    BufferedImage image = new BufferedImage(iWidth, iHeight,BufferedImage.TYPE_INT_RGB);
    //获取图形上下文

    Graphics g = image.getGraphics();
    //设定背景色

    g.setColor(Color.white);
    g.fillRect(0, 0, iWidth, iHeight);
    //画边框

    g.setColor(Color.black);
    g.drawRect(0, 0, iWidth - 1, iHeight - 1);
    //取随机产生的认证码(4位数字)

    //Math.random()方法来产生一个随机数,这个产生的随机数是0-1之间的一个double,我们可以把他乘以一定的数,比如说乘以100,他就是个100以内的随机

    Random random = new Random();
    String rand = String.valueOf(Math.random()*10000);
    String randChar = "y0p9s1k5vb4NB6KH7GFDA8E";
    String temp="" ;
    
    for(int i=0;i<4;i++)
    {
       temp =temp+randChar.charAt(random.nextInt(23));
    }
      
    //将认证码存入SESSION

    session.setAttribute("Rand", temp.toLowerCase());
    //将认证码显示到图象中

    g.setColor(Color.black);
    
    g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    g.drawString(temp, 10, 15);
    //随机产生88个干扰点,使图象中的认证码不易被其它程序探测到

    
    for (int iIndex = 0; iIndex < 88; iIndex++) {
        int x = random.nextInt(iWidth);
        int y = random.nextInt(iHeight);
        g.drawLine(x, y, x, y);
        
    }
    
    //图象生效

    g.dispose();
    //输出图象到页面

    
    ImageIO.write(image, "JPEG", response.getOutputStream());
    
    //验证部分

    //String Rand=request.getParameter("Rand");

    //String strRand=(String)session.getAttribute("Rand");

   //if(!strRand.equals(Rand))

    //{

      //未通过;

    //}

    
    
    
%>


Image.jsp 文件 产生随机码

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>image.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
  <script>
  function im(id){
      var id = document.getElementById("test");
      id.src = './image.jsp?'+ Math.random();
  }
  </script>
   <img id="test" border=0 src='./image.jsp' onclick="im(this.id)">
   <br>输认证码:<input name="Rand" maxlength=4 size="10"><br>


  </body>
</html>

 

Image.html使用

发表于: 2008-01-06,修改于: 2008-01-06 23:46,已浏览222次,有评论1条 推荐 投诉
网友: 本站网友 时间:2008-02-21 13:38:04 IP地址:221.7.131.★
错了<%@page contentType ="text/html; charset=GBK" %> 
 


给我留言
版权所有 ChinaUnix.net 页面生成时间:1.76215