• jsp中验证码的实现


     [java] view plaincopy
    1. package com.guang.servlet;  
    2. import java.awt.Color;    
    3. import java.awt.Font;    
    4. import java.awt.Graphics2D;    
    5. import java.awt.image.BufferedImage;    
    6. import java.util.Random;    
    7.     
    8. import javax.imageio.ImageIO;    
    9. import javax.servlet.ServletException;    
    10. import javax.servlet.ServletOutputStream;    
    11. import javax.servlet.http.HttpServlet;    
    12. import javax.servlet.http.HttpServletRequest;    
    13. import javax.servlet.http.HttpServletResponse;    
    14. import javax.servlet.http.HttpSession;    
    15.     
    16. public class VerifyCodeServlet extends HttpServlet {    
    17.     
    18.     // 验证码图片的宽度。    
    19.     private int width = 90;    
    20.     
    21.     // 验证码图片的高度。    
    22.     private int height = 30;    
    23.     
    24.     // 验证码字符个数    
    25.     private int codeCount = 4;    
    26.     
    27.     private int x = 0;    
    28.     
    29.     // 字体高度    
    30.     private int fontHeight;    
    31.     
    32.     private int codeY;    
    33.     
    34.     char[] codeSequence = { 'A''B''C''D''E''F''G''H''I''J',    
    35.             'K''L''M''N''O''P''Q''R''S''T''U''V''W',    
    36.             'X''Y''Z''0''1''2''3''4''5''6''7''8''9' };    
    37.     
    38.     /**  
    39.      * 初始化验证图片属性  
    40.      */    
    41.     public void init() throws ServletException {    
    42.         // 从web.xml中获取初始信息    
    43.         // 宽度    
    44.         String strWidth = this.getInitParameter("width");    
    45.         // 高度    
    46.         String strHeight = this.getInitParameter("height");    
    47.         // 字符个数    
    48.         String strCodeCount = this.getInitParameter("codeCount");    
    49.     
    50.         // 将配置的信息转换成数值    
    51.         try {    
    52.             if (strWidth != null && strWidth.length() != 0) {    
    53.                 width = Integer.parseInt(strWidth);    
    54.             }    
    55.             if (strHeight != null && strHeight.length() != 0) {    
    56.                 height = Integer.parseInt(strHeight);    
    57.             }    
    58.             if (strCodeCount != null && strCodeCount.length() != 0) {    
    59.                 codeCount = Integer.parseInt(strCodeCount);    
    60.             }    
    61.         } catch (NumberFormatException e) {    
    62.         }    
    63.     
    64.         x = width / (codeCount + 1);    
    65.         fontHeight = height - 2;    
    66.         codeY = height - 4;    
    67.     
    68.     }    
    69.     
    70.     protected void service(HttpServletRequest req, HttpServletResponse resp)    
    71.             throws ServletException, java.io.IOException {    
    72.     
    73.         // 定义图像buffer    
    74.         BufferedImage buffImg = new BufferedImage(width, height,    
    75.                 BufferedImage.TYPE_INT_RGB);    
    76.         Graphics2D g = buffImg.createGraphics();    
    77.     
    78.         // 创建一个随机数生成器类    
    79.         Random random = new Random();    
    80.     
    81.         // 将图像填充为白色    
    82.         g.setColor(Color.WHITE);    
    83.         g.fillRect(00, width, height);    
    84.     
    85.         // 创建字体,字体的大小应该根据图片的高度来定。    
    86.         Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);    
    87.         // 设置字体。    
    88.         g.setFont(font);    
    89.     
    90.         // 画边框。    
    91.         g.setColor(Color.BLACK);    
    92.         g.drawRect(00, width - 1, height - 1);    
    93.     
    94.         // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。    
    95.         g.setColor(Color.BLACK);    
    96.         for (int i = 0; i < 16; i++) {    
    97.             int x = random.nextInt(width);    
    98.             int y = random.nextInt(height);    
    99.             int xl = random.nextInt(12);    
    100.             int yl = random.nextInt(12);    
    101.             g.drawLine(x, y, x + xl, y + yl);    
    102.         }    
    103.     
    104.         // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。    
    105.         StringBuffer randomCode = new StringBuffer();    
    106.         int red = 0, green = 0, blue = 0;    
    107.     
    108.         // 随机产生codeCount数字的验证码。    
    109.         for (int i = 0; i < codeCount; i++) {    
    110.             // 得到随机产生的验证码数字。    
    111.             String strRand = String.valueOf(codeSequence[random.nextInt(36)]);    
    112.             // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。    
    113.             red = random.nextInt(255);    
    114.             green = random.nextInt(255);    
    115.             blue = random.nextInt(255);    
    116.     
    117.             // 用随机产生的颜色将验证码绘制到图像中。    
    118.             g.setColor(new Color(red, green, blue));    
    119.             g.drawString(strRand, (i + 1) * x, codeY);    
    120.     
    121.             // 将产生的四个随机数组合在一起。    
    122.             randomCode.append(strRand);    
    123.         }    
    124.         // 将四位数字的验证码保存到Session中。    
    125.         HttpSession session = req.getSession();    
    126.         session.setAttribute("validateCode", randomCode.toString());    
    127.     
    128.         // 禁止图像缓存。    
    129.         resp.setHeader("Pragma""no-cache");    
    130.         resp.setHeader("Cache-Control""no-cache");    
    131.         resp.setDateHeader("Expires"0);    
    132.     
    133.         resp.setContentType("image/jpeg");    
    134.     
    135.         // 将图像输出到Servlet输出流中。    
    136.         ServletOutputStream sos = resp.getOutputStream();    
    137.         ImageIO.write(buffImg, "jpeg", sos);    
    138.         sos.close();    
    139.     }    
    140.     
    141. }   
    上面是生成验证码的servlet,随便放在任意的package下。但是要注意WEB-INF下的-web.xml之中的配置,我这里是这样配置的:
    [html] view plaincopy
    1.   <servlet>  
    2.     <description>Thank you!</description>  
    3.     <display-name>HelloServlet</display-name>  
    4.     <servlet-name>VerifyCodeServlet</servlet-name>  
    5.     <servlet-class>com.guang.servlet.VerifyCodeServlet</servlet-class>  
    6.   </servlet>  
    7.     
    8.   <servlet-mapping>  
    9.     <servlet-name>VerifyCodeServlet</servlet-name>  
    10.     <url-pattern>/VerifyCodeServlet</url-pattern>  
    11.   </servlet-mapping>  
    注意上面的url的,这个在后面要用到的。

    现在验证码生成了。在jsp中显示吧。下面是jsp页面

    [java] view plaincopy
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"    
    2.     pageEncoding="UTF-8"%>    
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
    4. <html>    
    5.     <head>    
    6.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
    7.     <script type="text/javascript" src="js/verifyCode.js"></script>    
    8.         <script type="text/javascript" src="js/jquery.js"></script>  <span style="color:#ff0000;"></span>  
    9.         <title>test verify code</title>    
    10.     </head>    
    11.     <body>    
    12.         <input id="veryCode" name="veryCode" type="text"/>    
    13.         <img id="imgObj" alt="" <span style="color:#ff0000;"></span>src="VerifyCodeServlet"/>   
    14.         <a href="#" onclick="changeImg()">换一张</a>    
    15.         <input type="button" value="验证" onclick="isRightCode()"/>    
    16.         <div id="info"></div>    
    17.     </body>    
    18. </html>  

    接下来就是验证了,在js文件夹下新建verifyCode.js。

    [javascript] view plaincopy
    1. function changeImg(){    
    2.     var imgSrc = $("#imgObj");    
    3.     var src = imgSrc.attr("src");    
    4.     imgSrc.attr("src",chgUrl(src));    
    5. }    
    6. //时间戳    
    7. //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳    
    8. function chgUrl(url){    
    9.     var timestamp = (new Date()).valueOf();    
    10.     url = url.substring(0,17);    
    11.     if((url.indexOf("&")>=0)){    
    12.         url = url + "×tamp=" + timestamp;    
    13.     }else{    
    14.         url = url + "?timestamp=" + timestamp;    
    15.     }    
    16.     return url;    
    17. }    
    18.     
    19. function isRightCode(){    
    20.     var code = $("#veryCode").attr("value");    
    21.     //alert();  
    22.     code = "c=" + code;    
    23.     $.ajax({    
    24.         type:"POST",    
    25.      <span style="white-space:pre">    </span>url:"ResultServlet",    
    26.         data:code,    
    27.         success:callback    
    28.     });    
    29. }    
    30.   
    31.   
    32. function callback(data){    
    33.     $("#info").html(data);    
    34. }   

    注意上面url那一段。这个是验证servlet,ajax讲客户端的值传回这里进行的验证。

    下面是ResultServlet。


    [java] view plaincopy
    1. import java.io.IOException;    
    2. import java.io.PrintWriter;    
    3.     
    4. import javax.servlet.ServletException;    
    5. import javax.servlet.http.HttpServlet;    
    6. import javax.servlet.http.HttpServletRequest;    
    7. import javax.servlet.http.HttpServletResponse;    
    8.     
    9. public class ResultServlet extends HttpServlet {    
    10.     private static final long serialVersionUID = 1L;  
    11.   
    12.     public void doGet(HttpServletRequest request, HttpServletResponse response)    
    13.             throws ServletException, IOException {    
    14.     
    15.         doPost(request, response);    
    16.     }    
    17.     public void doPost(HttpServletRequest request, HttpServletResponse response)    
    18.             throws ServletException, IOException {    
    19.     
    20.         response.setContentType("text/html;charset=utf-8");    
    21.         String validateC = (String) request.getSession().getAttribute("validateCode");    
    22.         String veryCode = request.getParameter("c");    
    23.         PrintWriter out = response.getWriter();    
    24.         if(veryCode==null||"".equals(veryCode)){    
    25.             out.println("<script type='text/javascript'>alert('验证码为空!');return false;</script>");  
    26.         }else{    
    27.             if(validateC.equals(veryCode)){    
    28.             }else{    
    29.                 out.println("<script type='text/javascript'>alert('验证码错误!');return false;</script>");   
    30.             }    
    31.         }    
    32.         out.flush();    
    33.         out.close();    
    34.     }    
    35.     
    36. }  

  • 相关阅读:
    用OLEDB操作Excel时出现Selected collating sequence not supported by the operating system错误,附解决方法
    CLR via C#学习笔记:C#操作符重载学习( 基于.NET3.5 )
    CLR via C#学习笔记:C#转换操作符号学习
    解决ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.
    .NET中用SMTP发邮件的两中方法总结
    ADO.NET嵌套SQL事务一例
    SQL数据字典:查一个表的主Key是什么?(用于SQL 2000和2005)
    [转]什么是软件架构师?
    玩转SQL中的ANSI_NULLS
    SQL Server 2005发邮件的代码
  • 原文地址:https://www.cnblogs.com/tgxblue/p/4217388.html
Copyright © 2020-2023  润新知