(博客内容来自:jsp使用servlet实现验证码,以下内容只是不才对原博客的摘抄以便以后翻阅使用)
一.原理:
验证码作为一个图片,在页面中为“画”出来的,它是如何画出来的呢?
<生成图片>
{
生成图片的类:
1.BufferedImage图像数据缓冲区
2.Graphics绘制图片
3.color获取颜色
4.Random获取随机数
5.ImageIO输出图片
}
二.servlet后台:
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; @WebServlet("/AptchaGenerate") public class AptchaGenerate extends HttpServlet { private static final long serialVersionUID = 1L; public AptchaGenerate() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage bufferedImage = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);//创建图像缓冲区 Graphics g = bufferedImage.getGraphics(); //通过缓冲区创建一个画布 /*根据背景画了一个矩形框 */ Color c = new Color(232, 232, 232); //创建颜色 g.setColor(c);//为画布创建背景颜色 g.fillRect(0, 0, 68, 22); //fillRect:填充指定的矩形 // X和Y用于指定矩形左上角也就是相对于原点的位置,width和height用于指定矩形的宽和高。 char[] charList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组 StringBuilder aptcha = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 4; i++) { int index = r.nextInt(charList.length); //产生随机数字,随机选取字母或数字 g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255))); //随机设置颜色 g.drawString(""+charList[index], i*15+5, 15); //画数字以及数字的位置 aptcha.append(charList[index]); //将选中的字母加入到验证码当中 } ImageIO.write(bufferedImage, "JPG", response.getOutputStream()); //在客户端上画图 request.getSession().setAttribute("aptcha", aptcha.toString()); //将验证码保留在session中,便于后续的使用 } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
三.前台:
1.HTML标签:
<div><h3>验证码:</h3></div> <img alt="验证码" id="aptchaImage" src="${pageContext.request.contextPath}/AptchaGenerate"/> <a href="javascript:void(0);" onclick="reloadAptcha()">看不清楚</a><br> <input type="text" id="aptcha" autofocus="autofocus" autocomplete="off" maxlength="4" placeholder="请输入验证码">
2.javascript实现“看不清楚,下一张”:
function reloadAptcha(){ var time = new Date().getTime(); $("#aptchaImage").attr("src", "${pageContext.request.contextPath}/AptchaGenerate?d=" + time); }
3.效果如下: