动态生成能够局部刷新的验证码【AJAX技术】---看了不懂赔你钱
在开发JavaWeb应用时,动态生成能够局部刷新的验证码是一项必须的功能,在这里我们将会详细的讲解如何实现这一功能。
一、涉及技术
该功能需要用到AJAX异步传输技术,这样能保证在点击“看不清,重新获取验证码”按钮时,能够不刷新页面其它内容而局部刷新验证码图片内容。
还需要用到Servlet技术,这里会在Servlet的GET方法中通过Java内置的画图工具绘制一个验证码图片,可以在HTML的<img/>标签中的src属性获取缓存图片资源。
二、各个页面及代码
1.index.html,是一个简单的表单,上面仅有简单几项内容,AJAX异步传输技术也在上面体现,代码中有详细注释。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8"/>
- <title>验证码测试</title>
- </head>
- <body>
- <script style="javascript">
- var xmlHttp;
- //异步刷新验证码
- function reload() {
- //针对不同浏览器,不同的方式生成xmlHttp对象
- try{
- xmlHttp=new XMLHttpRequest();
- }catch(e){
- try{
- xmlHttp=new ActiveXObject("Msxml2.XMLHttp");
- }catch(e){
- try{
- xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
- }catch(e){
- alert("你的浏览器不支持AJAX") ;
- return false;
- }
- }
- }
- var url="ValidateCodeServlet";
- xmlHttp.onreadystatechange = deal;//该属性为一个函数
- xmlHttp.open("GET", url, true);//初始化xmlHttp
- xmlHttp.send(null);//发送
- }
- function deal(){
- if(xmlHttp.readyState==4){//当状态值为4时,接收到服务器传输的信息
- //重新从servlet获得图片资源,并且防止浏览器缓存,加了时间
- document.getElementById("validate_code").src = "ValidateCodeServlet?" + new Date().getTime();
- }
- }
- </script>
- <form method="post" action="check.jsp">
- <input type="text" name="input_code"/>
- <img src="ValidateCodeServlet" id="validate_code"/>
- <a href="#" onclick="reload()">看不清楚,换一个</a>
- <input type="submit"/>
- </form>
- </body>
- </html>
- <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <html>
- <head>
- <title>检验验证码</title>
- </head>
- <body>
- <%
- String code = (String) session.getAttribute("code");
- String input_code = request.getParameter("input_code");
- if (code != null && input_code != null) {
- input_code = input_code.toUpperCase();
- if (code.equals(input_code)) {
- out.print("验证码正确");
- } else {
- out.print("验证码错误");
- }
- }
- %>
- <a href="index.html">返回填写页面</a>
- </body>
- </html>
- package com.yykj.servlet;
- import javax.imageio.ImageIO;
- import javax.servlet.ServletException;
- import javax.servlet.http.;
- import java.awt.;
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import java.util.Random;
- public class ValidateCodeServlet extends HttpServlet {
- private Random random = new Random();
- private String[] allCodes = {
- "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
- "A", "B", "C", "D", "E", "F", "G", "H", "I",
- "J", "K", "L", "M", "N", "O", "P", "Q", "R",
- "S", "T", "U", "V", "W", "X", "Y", "Z"
- };
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- resp.setHeader("Pragma", "No-cache");
- resp.setHeader("Cache-Control", "No-cache");
- resp.setDateHeader("Expires", 0);//禁止客户端缓存页面
- resp.setContentType("image/jpg");//设置响应正文类型为图片
- int height = 20;
- int width = 60;
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- Graphics g = image.getGraphics();//获取处理图片的画笔
- g.setColor(getRandomColor(200, 250));//设置背景色
- g.fillRect(0, 0, width, height);//画一个矩形
- g.setFont(new Font("Times New Roman", Font.PLAIN, 18));//设置字体
- g.setColor(getRandomColor(160, 200));//设置干扰线的颜色
- for (int i = 0; i < 100; i++){//画一百条干扰线
- int x = random.nextInt(width);
- int y = random.nextInt(height);
- int x1 = random.nextInt(10);
- int y1 = random.nextInt(10);
- g.drawLine(x, y, x1, y1);//干扰线的两个顶点坐标
- }
- String strCode = "";
- for (int i = 0; i < 4; i++){//生成四个随机字符
- String strNumber = allCodes[random.nextInt(36)];
- strCode += strNumber;
- g.setColor(getRandomColor(20, 120));
- g.drawString(strNumber , 13 * i + 3, 16);
- }
- req.getSession(true).setAttribute("code", strCode);//将生成的验证码存入session
- g.dispose();//释放图像的上下文资源
- ImageIO.write(image, "JPEG", resp.getOutputStream());//输出JPEG格式图像
- resp.getOutputStream().flush();//刷新输出流
- resp.getOutputStream().close();//关闭输出流
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- //生成随机RGB颜色
- private Color getRandomColor(int min, int max){
- int r = min + random.nextInt(max - min);
- int b = min + random.nextInt(max - min);
- int g = min + random.nextInt(max - min);
- return new Color(r, b, g);
- }
- }
注意:ValidateCodeServlet要在web.xml中配置,配置代码如下:
- <servlet>
- <servlet-name>ValidateCodeServlet</servlet-name>
- <servlet-class>com.yykj.servlet.ValidateCodeServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ValidateCodeServlet</servlet-name>
- <url-pattern>/ValidateCodeServlet</url-pattern>
- </servlet-mapping>