失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 动态生成能够局部刷新的验证码【AJAX技术】---看了不懂赔你钱

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

时间:2021-12-13 01:25:46

相关推荐

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

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

一、涉及技术

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

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

二、各个页面及代码

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

[html]view plain copy print?<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><title>验证码测试</title></head><body><scriptstyle="javascript">varxmlHttp;//异步刷新验证码functionreload(){//针对不同浏览器,不同的方式生成xmlHttp对象try{xmlHttp=newXMLHttpRequest();}catch(e){try{xmlHttp=newActiveXObject("Msxml2.XMLHttp");}catch(e){try{xmlHttp=newActiveXObject("Microsoft.XMLHttp");}catch(e){alert("你的浏览器不支持AJAX");returnfalse;}}}varurl="ValidateCodeServlet";xmlHttp.onreadystatechange=deal;//该属性为一个函数xmlHttp.open("GET",url,true);//初始化xmlHttpxmlHttp.send(null);//发送}functiondeal(){if(xmlHttp.readyState==4){//当状态值为4时,接收到服务器传输的信息//重新从servlet获得图片资源,并且防止浏览器缓存,加了时间document.getElementById("validate_code").src="ValidateCodeServlet?"+newDate().getTime();}}</script><formmethod="post"action="check.jsp"><inputtype="text"name="input_code"/><imgsrc="ValidateCodeServlet"id="validate_code"/><ahref="#"onclick="reload()">看不清楚,换一个</a><inputtype="submit"/></form></body></html>

<!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);//初始化xmlHttpxmlHttp.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="#" οnclick="reload()">看不清楚,换一个</a><input type="submit"/></form></body></html>

2.check.jsp,用来判断用户表单提交的验证码是否正确,也是较为简单的Java代码。[html]view plain copy print?<%@pagecontentType="text/html;charset=UTF-8"pageEncoding="UTF-8"language="java"%><%@tagliburi="/jsp/jstl/core"prefix="c"%><html><head><title>检验验证码</title></head><body><%Stringcode=(String)session.getAttribute("code");Stringinput_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("验证码错误");}}%><ahref="index.html">返回填写页面</a></body></html>

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %><%@ taglib uri="/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>

3.ValidateCodeServlet,生成验证码图片的文件,代码中有详细的注释。[java]view plain copy print?packagecom.yykj.servlet;importjavax.imageio.ImageIO;importjavax.servlet.ServletException;importjavax.servlet.http.*;importjava.awt.*;importjava.awt.image.BufferedImage;importjava.io.IOException;importjava.util.Random;publicclassValidateCodeServletextendsHttpServlet{privateRandomrandom=newRandom();privateString[]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"};@OverrideprotectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{resp.setHeader("Pragma","No-cache");resp.setHeader("Cache-Control","No-cache");resp.setDateHeader("Expires",0);//禁止客户端缓存页面resp.setContentType("image/jpg");//设置响应正文类型为图片intheight=20;intwidth=60;BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);Graphicsg=image.getGraphics();//获取处理图片的画笔g.setColor(getRandomColor(200,250));//设置背景色g.fillRect(0,0,width,height);//画一个矩形g.setFont(newFont("TimesNewRoman",Font.PLAIN,18));//设置字体g.setColor(getRandomColor(160,200));//设置干扰线的颜色for(inti=0;i<100;i++){//画一百条干扰线intx=random.nextInt(width);inty=random.nextInt(height);intx1=random.nextInt(10);inty1=random.nextInt(10);g.drawLine(x,y,x1,y1);//干扰线的两个顶点坐标}StringstrCode="";for(inti=0;i<4;i++){//生成四个随机字符StringstrNumber=allCodes[random.nextInt(36)];strCode+=strNumber;g.setColor(getRandomColor(20,120));g.drawString(strNumber,13*i+3,16);}req.getSession(true).setAttribute("code",strCode);//将生成的验证码存入sessiong.dispose();//释放图像的上下文资源ImageIO.write(image,"JPEG",resp.getOutputStream());//输出JPEG格式图像resp.getOutputStream().flush();//刷新输出流resp.getOutputStream().close();//关闭输出流}@OverrideprotectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{doGet(req,resp);}//生成随机RGB颜色privateColorgetRandomColor(intmin,intmax){intr=min+random.nextInt(max-min);intb=min+random.nextInt(max-min);intg=min+random.nextInt(max-min);returnnewColor(r,b,g);}}

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"};@Overrideprotected 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);//将生成的验证码存入sessiong.dispose();//释放图像的上下文资源ImageIO.write(image, "JPEG", resp.getOutputStream());//输出JPEG格式图像resp.getOutputStream().flush();//刷新输出流resp.getOutputStream().close();//关闭输出流}@Overrideprotected 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中配置,配置代码如下:

[html]view plain copy print?<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>

<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>

如果觉得《动态生成能够局部刷新的验证码【AJAX技术】---看了不懂赔你钱》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。