验证码是一种区分用户是计算机和人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上是用验证码是现在很多网站通行的方式(比如招商银行的网上个人银行,百度社区),我们利用比较简易的方式实现了这个功能。今天我们就用Java实现一个简单的验证码程序。
用Java实现的验证码程序
生成验证码的步骤:
- 定义BufferedImage对象: new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
- 获得Graphics对象: bufferedImage.getGraphics();
- 通过Random产生随机验证码信息
- 使用Graphics绘制图片
- 记录验证码信息到session中
- 使用ImageIO输出图片
验证码校验的步骤:
- 获取页面验证码
- 获取session保存的验证码
- 比较验证码
- 返回校验结果
我们创建一个Java的Web项目,目结构如下:
一、 定义一个index.jsp,用于刷新验证码、校验验证码不能为空和以及提交验证码:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> <script type="text/javascript"> function reload() { var time = new Date().getTime(); document.getElementById("image").src = "<%=request.getContextPath() %>/servlet/ImageServlet?id=" + time; }; function doIt() { var code = document.getElementById("code").value; if (code == null || code == "") { alert("验证码不能为空!"); return false; } else { return true; } }; </script> </head> <body> <form action="servlet/LoginServlet" method="get" onsubmit="return doIt();"> 验证码:<input type="text" name="codeCheck" id="code"> <img id="image" alt="输入验证码" src="<%=request.getContextPath() %>/servlet/ImageServlet" /> <a href="javascript: reload();">看不清</a><br> <input type="submit" value="submit"> </form> </body> </html>
二、 ImageServlet.java,用于生成验证码图片并保存验证码到session中:
package com.huhx.servlet; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author huhx */ @WebServlet("/servlet/ImageServlet") public class ImageServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage bufferedImage = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB); Graphics graphics = bufferedImage.getGraphics(); Color color = new Color(225, 230, 246); graphics.setColor(color); graphics.fillRect(0, 0, 68, 22); char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); Random random = new Random(); int length = chars.length; StringBuffer buffer = new StringBuffer(); int index; for (int i = 0; i < 4; i++) { index = random.nextInt(length); graphics.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255))); graphics.drawString(chars[index] + "", (i * 15) + 3, 18); buffer.append(chars[index]); } request.getSession().setAttribute("code", buffer.toString()); ImageIO.write(bufferedImage, "JPG", response.getOutputStream()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
三、 LoginServlet.java,用于接收用户的验证码提交并验证:
package com.huhx.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author huhx */ @WebServlet("/servlet/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String codeCheck = request.getParameter("codeCheck"); String raelCode = (String) request.getSession().getAttribute("code"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); if (codeCheck.toUpperCase().equals(raelCode.toUpperCase())) { out.println("验证码成功!"); } else { out.println("验证码失败!"); } out.flush(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
注意:eclipse用的是@WebServlet注解的方式,如果是其他的方式,则servlet需要在web.xml中定义映射关系。
四、 运行结果如下:
其他的验证码框架:kaptcha, jcaptcha,有兴趣的可以关注一下。
时间: 2024-09-28 21:43:53