当前位置: 代码迷 >> Web前端 >> 验证码代码的编写有关问题
  详细解决方案

验证码代码的编写有关问题

热度:367   发布时间:2012-11-05 09:35:12.0
验证码代码的编写问题
可以通过三个jsp页面来实现验证码的填写与验证
第一个jsp页面用来生成随机的字符,我们将它命名为code.jsp,代码如下:

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"
     import="java.io.*,
          java.util.*,
          com.sun.image.codec.jpeg.*,
          java.awt.*,
          java.awt.image.*"%>


<%
  String s = "";

        int intCount = 0;
        /**
      * 验证码宽度
      */
      int width=100;
     /**
      * 验证码高度
      */
      int height=25;
        /**
      * 验证码字符集
      */
      char[] code=new char[]{
      'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
      'a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z',
       '2','3','4','5','6','7','8','9'};
    
        /**
         *  创建一个随机数生成器类
         */
        Random random = new Random(); 

      
       // 随机产生codeCount数字的验证码。  
        for (int i = 0; i < 4; i++) {  
            // 得到随机产生的验证码数字。  
            String strRand = String.valueOf(code[random.nextInt(code.length)]);  
       
            // 将产生的四个随机数组合在一起。  
            s=s+strRand;  
        }

        // 保存入session,用于与用户的输入进行比较.
        // 注意比较完之后清除session.

        session.setAttribute("validateCode", s);

        response.setContentType("image/gif");
       

   // 定义图像buffer  
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D gra = image.createGraphics();
      // 将图像填充为白色  
        gra.setColor(Color.WHITE);  
        gra.fillRect(0, 0, width, height);  
 
        // 创建字体,字体的大小应该根据图片的高度来定。 
      
       //字体对象构造方法public Font(String familyName,int style,int size)
       // familyName字体名;字体名可以分成两大类:中文字体:宋体、楷体、黑体等;英文字体:Arial、Times New Roman等等;
       // style风格。PLAIN普通字体,BOLD(加粗),ITALIC(斜体),Font.BOLD+ Font.ITALIC(粗斜体)
       //size 大小

      
        Font font = new Font("宋体", Font.BOLD+Font.ITALIC, height-1);//
 
      
        // 设置字体。  
        gra.setFont(font);  
 
 
        // 画边框。  
        gra.setColor(getColor());  
        gra.drawRect(0, 0, width - 1, height - 1);
  
 
        // 随机产生干扰线,使图象中的认证码不易被其它程序探测到。  
        gra.setColor(Color.BLACK);  
        for (int i = 0; i < 50; i++) {  
            int x = random.nextInt(width);  
            int y = random.nextInt(height);  
            int xl = random.nextInt(5);  
            int yl = random.nextInt(5); 
            gra.setColor(getColor());
            gra.drawLine(x, y, x + xl, y + yl);  
        }  
     
        // 输出数字
        char c;

        for (int i = 0; i < 4; i++) {

            c = s.charAt(i);

            gra.drawString(c + "", i * 25 + 4, 20); // 25为宽度,11为上下高度位置

        }

  OutputStream toClient = response.getOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(toClient);
        encoder.encode(image);

  toClient.close();

        out.clear();

  out = pageContext.pushBody();
%>
<%!
private Color getColor()
{
Random random = new Random();
int red = 0, green = 0, blue = 0;  
// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。  
     red = random.nextInt(255);  
     green = random.nextInt(255);  
     blue = random.nextInt(255); 
     return new Color(red,green,blue);
}

%>

接着,我们创建第二个jsp页面,主要用于显示生成的验证码,代码为:
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<img src="code.jsp" />
<form method="post" action="code1.jsp">
<input name="提交" type="submit" value="看不清楚,换一张"/>
</form>
<form action="compare.jsp" method="post">验证码
  <input type="text" name="code1" /><br />
   
    <input type="submit" name="mysubmit" value="提交" />
</form>
</td>
</body>
</html>

第三个jsp页面是用于对用户输入的验证码以及系统产生的验证码进行对照,判断输入是否正确,我们在这里将其命名为check.jsp,代码如下:
<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>验证页面</title>
</head>
<body>
<%
String serverCode = (String)session.getAttribute("validateCode");
/* String userCode  =new String(request.getParameter("code").getBytes("ISO-8859-1"));
*/
String userCode  =request.getParameter("code1");
session.removeAttribute("validateCode");
%>
<br/>
<div align="center">
<%
if(userCode.equals(serverCode)){
%>
     <font color=green>输入相同,认证成功!</font>
    <%
      } else {
    %>
    <font color=red>输入不同,认证失败!</font>
   
    <form name="check" method="post" action="code1.jsp">
    <input type="submit" value="return to rewrite"/>
    </form>
    <%
      }
    %>
</div>
</body>
</html>


如果你正在为验证码的问题烦恼,那么不妨试一下上述代码,希望能够对大家有用O(∩_∩)O~
  相关解决方案