驗證碼的功能大多數人可能不都理解,但幾乎每個安全網站都會有。驗證碼是用來防止非人為因素操作的行為,例如一個黑客要黑一個網站,怎麼弄呢?最簡單的思路當然是造成其網路擁堵直至系統癱瘓掉。如果沒有驗證碼,那麼我就可以在注冊頁面,寫一個程序,只有注冊表單,不斷更換主鍵或不可重復的內容,不停的提交。那這樣每秒可以注冊幾萬次都有可能,這樣服務器就大量負載,很容易就癱瘓並死掉。而達到這樣的目的並不困難。 增加驗證碼之後,就不是機器人能識別的了,必須是人在操作系統,由於是圖片形式的,而且歪歪斜斜亂七八糟,而現階段圖形模式識別技術還沒做到能夠識別驗證碼的程度,所以加上驗證碼就相對安全了很多。在軟件開發中難免會遇到這樣的情況,客戶壓根不知道驗證碼用來干什麼的,但一定要加不可。為什麼要加?因為大家都有。沒法子總要加上才顯得自己專業,其實這個東西很容易加,就是用數字或字母做模板用swing的圖形API,畫出一個圖片出來。完整的邏輯和代碼如下: [html] <img id="validateCodeId" src="validateCodeServlet" onclick="flushValidateCode(this);" title='看不清,點擊刷新' style="cursor: pointer;" /> [javascript] //刷新驗證碼 flushValidateCode = function(obj) { obj.src ='validateCodeServlet?d='+new Date(); } 請求的URL是validateCodeServlet,後面參數d=new Date()是保證每次點擊刷新的時候URL都不一樣,否則會不刷新。別的地方也使用Math.rand();這樣的辦法取得一個隨機數,這樣也是可以的。 web.xml這樣來配置servlet的映射信息。 [html] <servlet> <servlet-name>validateCode</servlet-name> <servlet-class>com.xzfy.mainpage.web.action.ValidateCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>validateCode</servlet-name> <url-pattern>/validateCodeServlet</url-pattern> </servlet-mapping> ValidateCodeServlet [java] package com.xzfy.mainpage.web.action; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.io.output.ByteArrayOutputStream; public class ValidateCodeServlet extends HttpServlet { /** * Constructor of the object. */ public ValidateCodeServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); HttpSession session = request.getSession(); int width = 60, height = 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } String sRand = ""; for (int i = 0; i < 4; i++) { String rand = String.valueOf(random.nextInt(10)); sRand += rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110)));// 調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成 g.drawString(rand, 13 * i + 6, 16); } session.setAttribute("rand", sRand); g.dispose(); ServletOutputStream responseOutputStream = response.getOutputStream(); ImageIO.write(image, "JPEG", responseOutputStream); responseOutputStream.flush(); responseOutputStream.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } www.2cto.com Color getRandColor(int fc, int bc) {// 給定范圍獲得隨機顏色 Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } } 效果如下: