驗證碼是一種區分用戶是計算機和人的公共全自動程序。可以防止:惡意破解密碼、刷票、論壇灌水,有效防止某個黑客對某一個特定注冊用戶用特定程序暴力破解方式進行不斷的登陸嘗試,實際上是用驗證碼是現在很多網站通行的方式(比如招商銀行的網上個人銀行,百度社區),我們利用比較簡易的方式實現了這個功能。今天我們就用Java實現一個簡單的驗證碼程序。
生成驗證碼的步驟:
驗證碼校驗的步驟:
我們創建一個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,有興趣的可以關注一下。