动态生成能够局部刷新的验证码【AJAX技术】---看了不懂赔你钱

在开发JavaWeb应用时,动态生成能够局部刷新的验证码是一项必须的功能,在这里我们将会详细的讲解如何实现这一功能。

一、涉及技术

该功能需要用到AJAX异步传输技术,这样能保证在点击“看不清,重新获取验证码”按钮时,能够不刷新页面其它内容而局部刷新验证码图片内容。

还需要用到Servlet技术,这里会在Servlet的GET方法中通过Java内置的画图工具绘制一个验证码图片,可以在HTML的<img/>标签中的src属性获取缓存图片资源。

二、各个页面及代码

1.index.html,是一个简单的表单,上面仅有简单几项内容,AJAX异步传输技术也在上面体现,代码中有详细注释。

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>验证码测试</title>  
  6.   
  7. </head>  
  8. <body>  
  9.   
  10. <script style="javascript">  
  11.     var xmlHttp;  
  12.     //异步刷新验证码  
  13.     function reload() {  
  14.         //针对不同浏览器,不同的方式生成xmlHttp对象  
  15.         try{  
  16.             xmlHttp=new XMLHttpRequest();  
  17.         }catch(e){  
  18.             try{  
  19.                 xmlHttp=new ActiveXObject("Msxml2.XMLHttp");  
  20.             }catch(e){  
  21.                 try{  
  22.                     xmlHttp=new ActiveXObject("Microsoft.XMLHttp");  
  23.                 }catch(e){  
  24.                     alert("你的浏览器不支持AJAX")   ;  
  25.                     return false;  
  26.                 }  
  27.             }  
  28.         }  
  29.         var url="ValidateCodeServlet";  
  30.         xmlHttp.onreadystatechange = deal;//该属性为一个函数  
  31.         xmlHttp.open("GET", url, true);//初始化xmlHttp  
  32.         xmlHttp.send(null);//发送  
  33.     }  
  34.     function deal(){  
  35.         if(xmlHttp.readyState==4){//当状态值为4时,接收到服务器传输的信息  
  36.             //重新从servlet获得图片资源,并且防止浏览器缓存,加了时间  
  37.             document.getElementById("validate_code").src = "ValidateCodeServlet?" + new Date().getTime();  
  38.         }  
  39.     }  
  40. </script>  
  41. <form method="post" action="check.jsp">  
  42.     <input type="text" name="input_code"/>  
  43.     <img  src="ValidateCodeServlet" id="validate_code"/>  
  44.     <a href="#" onclick="reload()">看不清楚,换一个</a>  
  45.     <input type="submit"/>  
  46. </form>  
  47. </body>  
  48. </html>  
2.check.jsp,用来判断用户表单提交的验证码是否正确,也是较为简单的Java代码。
  1. <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>  
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  3. <html>  
  4. <head>  
  5.     <title>检验验证码</title>  
  6. </head>  
  7. <body>  
  8. <%  
  9.     String code = (String) session.getAttribute("code");  
  10.     String input_code = request.getParameter("input_code");  
  11.   
  12.     if (code != null && input_code != null) {  
  13.         input_code = input_code.toUpperCase();  
  14.         if (code.equals(input_code)) {  
  15.             out.print("验证码正确");  
  16.         } else {  
  17.             out.print("验证码错误");  
  18.         }  
  19.     }  
  20. %>  
  21. <a href="index.html">返回填写页面</a>  
  22. </body>  
  23. </html>  
3.ValidateCodeServlet,生成验证码图片的文件,代码中有详细的注释。
  1. package com.yykj.servlet;  
  2.   
  3. import javax.imageio.ImageIO;  
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.;  
  6. import java.awt.;  
  7. import java.awt.image.BufferedImage;  
  8. import java.io.IOException;  
  9. import java.util.Random;  
  10.   
  11. public class ValidateCodeServlet extends HttpServlet {  
  12.   
  13.     private Random random = new Random();  
  14.     private String[] allCodes = {  
  15.         "0""1""2""3""4""5""6""7""8""9",  
  16.             "A""B""C""D""E""F""G""H""I",  
  17.             "J""K""L""M""N""O""P""Q""R",  
  18.             "S""T""U""V""W""X""Y""Z"  
  19.     };  
  20.     @Override  
  21.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
  22.         resp.setHeader("Pragma""No-cache");  
  23.         resp.setHeader("Cache-Control""No-cache");  
  24.         resp.setDateHeader("Expires"0);//禁止客户端缓存页面  
  25.         resp.setContentType("image/jpg");//设置响应正文类型为图片  
  26.   
  27.         int height = 20;  
  28.         int width = 60;  
  29.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  30.         Graphics g = image.getGraphics();//获取处理图片的画笔  
  31.         g.setColor(getRandomColor(200250));//设置背景色  
  32.         g.fillRect(00, width, height);//画一个矩形  
  33.         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));//设置字体  
  34.         g.setColor(getRandomColor(160200));//设置干扰线的颜色  
  35.         for (int i = 0; i < 100; i++){//画一百条干扰线  
  36.             int x = random.nextInt(width);  
  37.             int y = random.nextInt(height);  
  38.             int x1 = random.nextInt(10);  
  39.             int y1 = random.nextInt(10);  
  40.             g.drawLine(x, y, x1, y1);//干扰线的两个顶点坐标  
  41.         }  
  42.   
  43.         String strCode = "";  
  44.         for (int i = 0; i < 4; i++){//生成四个随机字符  
  45.             String strNumber = allCodes[random.nextInt(36)];  
  46.             strCode += strNumber;  
  47.             g.setColor(getRandomColor(20120));  
  48.             g.drawString(strNumber , 13 * i + 316);  
  49.         }  
  50.         req.getSession(true).setAttribute("code", strCode);//将生成的验证码存入session  
  51.         g.dispose();//释放图像的上下文资源  
  52.         ImageIO.write(image, "JPEG", resp.getOutputStream());//输出JPEG格式图像  
  53.         resp.getOutputStream().flush();//刷新输出流  
  54.         resp.getOutputStream().close();//关闭输出流  
  55.     }  
  56.   
  57.     @Override  
  58.     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
  59.         doGet(req, resp);  
  60.     }  
  61.     //生成随机RGB颜色  
  62.     private Color getRandomColor(int min, int max){  
  63.         int r = min + random.nextInt(max - min);  
  64.         int b = min + random.nextInt(max - min);  
  65.         int g = min + random.nextInt(max - min);  
  66.         return new Color(r, b, g);  
  67.     }  
  68. }  

注意:ValidateCodeServlet要在web.xml中配置,配置代码如下:

  1. <servlet>  
  2.   <servlet-name>ValidateCodeServlet</servlet-name>  
  3.   <servlet-class>com.yykj.servlet.ValidateCodeServlet</servlet-class>  
  4. </servlet>  
  5.   
  6. <servlet-mapping>  
  7.   <servlet-name>ValidateCodeServlet</servlet-name>  
  8.   <url-pattern>/ValidateCodeServlet</url-pattern>  
  9. </servlet-mapping>  


原文地址:https://www.cnblogs.com/jpfss/p/8444773.html