Java 隨機產生驗證碼,支援大小寫字母、數字;隨機字型

來源:互聯網
上載者:User

java隨機產生驗證碼,可以隨機產生數字、大寫字母、小寫字母。還可以隨機產生文字字型、及大小。在圖片上面可能字型都不不同、大小不等。 

package com.hoo.util; 

import java.awt.Color; 
import java.awt.Font; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.util.Random; 

import javax.imageio.ImageIO; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
/**
* <b>function:</b> 驗證碼產生工具類
* @project NetWorkService
* @package com.hoo.util 
* @fileName ValidCodeUtils.java
* @createDate 2010-8-3 下午03:05:50
* @author hoojo
*/ 
@SuppressWarnings("unused") 
public class ValidCodeUtils { 
/*********************************************************************
 * 驗證碼寬度
 */ 
public static int WIDTH = 60; 
/***
 * 驗證碼高度
 */ 
public static int HEIGHT = 20; 
 
/**********************************************************************
 * 驗證碼背景顏色COLOR_FC_BG 應當小於COLOR_BC_BG
 */ 
public static int COLOR_FC_BG = 200; 
/***
 * 驗證碼背景顏色COLOR_FC_BG 應當小於COLOR_BC_BG
 */ 
public static int COLOR_BC_BG = 250; 
 
/**********************************************************************
 * 驗證碼背景幹擾線顏色COLOR_FC_LINE 應當小於COLOR_BC_LINE
 */ 
public static int COLOR_FC_LINE = 160; 
/***
 * 驗證碼背景幹擾線顏色COLOR_FC_LINE 應當小於COLOR_BC_LINE
 */ 
public static int COLOR_BC_LINE = 200; 
 
/***************************************************************************
 * 驗證碼顏色COLOR_FC_CODE 應當小於COLOR_BC_CODE
 */ 
public static int COLOR_FC_CODE = 20; 
/***
 * 驗證碼顏色COLOR_FC_CODE 應當小於COLOR_BC_CODE
 */ 
public static int COLOR_BC_CODE = 170; 
 
/***************************************************************************
 * 產生在指定範圍內的顏色
 * @param fc 範圍fc color值 小於255
 * @param bc 範圍bc color值 小於255
 * @return Color
 */ 
private static Color getRandColor(int fc, int bc) { 
    Random random = new Random(); 
    if (fc < 0) 
 fc = 0; 
    if (bc < 0) 
 bc = 1; 
    if (fc > 255) 
 fc = 255; 
    if (bc > 255) 
 bc = 255; 
    if (bc == fc)  
 bc += 10; 
    int temp = 0; 
    if (bc < fc) { 
 temp = bc; 
 bc = fc; 
 fc = temp; 
    } 
    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); 

/**
 * <b>function:</b> 產生圖片方法
 * @createDate 2010-8-3 下午03:06:22
 * @author hoojo
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return boolean
 * @throws Exception
 */ 
public static boolean getImage(HttpServletRequest request, HttpServletResponse response) throws Exception{ 
    response.reset(); 
    response.setContentType("image/jpeg"); 
    // 設定頁面不緩衝 
    response.setHeader("Pragma", "No-cache"); 
    response.setHeader("Cache-Control", "no-cache"); 
    response.setDateHeader("Expires", 0); 
    // 在記憶體中建立圖象      
    BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 

    // 擷取圖形上下文 
    Graphics img = image.getGraphics(); 
    // 產生隨機類 
    Random random = new Random(); 

    // 設定背景色 
    img.setColor(getRandColor(COLOR_FC_BG, COLOR_BC_BG)); 
    img.fillRect(0, 0, WIDTH, HEIGHT); 

    // 設定字型 
    img.setFont(new Font("Times New Roman", Font.PLAIN, 18)); 

    // 畫邊框 
    // g.setColor(new Color()); 
    // g.drawRect(0,0,width-1,height-1); 

    // 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程式探測到 
    img.setColor(getRandColor(COLOR_FC_LINE, COLOR_BC_LINE)); 
    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); 
 img.drawLine(x, y, x + xl, y + yl); 
    } 

    // 取隨機產生的認證碼(4位元字) 
    String codeValue = ""; 
    for (int i = 0; i < 4; i++) { 
 //String rand = String.valueOf(random.nextInt(10)); 
 String rand = getRandomChar(); 
 codeValue = codeValue.concat(rand); 
 img.setFont(getRandomFont());//隨機字型 
 // 將認證碼顯示到圖象中 
 img.setColor(getRandColor(COLOR_FC_CODE, COLOR_BC_CODE)); 
 img.drawString(rand, 13 * i + 6, 16); 
    } 
    request.getSession().setAttribute("codeValue", codeValue); 
    // 圖象生效 
    img.dispose(); 
    // 輸出圖象到頁面 
    return ImageIO.write(image, "JPEG", response.getOutputStream()); 

 
/**
 * 隨機產生字元,含大寫、小寫、數字
 * <b>function:</b> 功能
 * @createDate 2010-8-23 上午10:33:55
 * @author hoojo
 * @return
 */ 
public static String getRandomChar() { 
    int index = (int) Math.round(Math.random() * 2); 
    String randChar = ""; 
    switch (index) { 
    case 0://大寫字元 
 randChar = String.valueOf((char)Math.round(Math.random() * 25 + 65)); 
 break; 
    case 1://小寫字元 
 randChar = String.valueOf((char)Math.round(Math.random() * 25 + 97)); 
 break; 
    default://數字 
 randChar = String.valueOf(Math.round(Math.random() * 9)); 
 break; 
    } 
    return randChar; 

 
/**
 * <b>function:</b> 隨機產生字型、文字大小
 * @createDate 2010-8-23 上午10:44:22
 * @author hoojo
 * @return
 */ 
public static Font getRandomFont() { 
    String[] fonts = {"Georgia", "Verdana", "Arial", "Tahoma", "Time News Roman", "Courier New", "Arial Black", "Quantzite"}; 
    int fontIndex = (int)Math.round(Math.random() * (fonts.length - 1)); 
    int fontSize = (int) Math.round(Math.random() * 4 + 16); 
    return new Font(fonts[fontIndex], Font.PLAIN, fontSize); 

其中驗證碼的值是儲存在session中:request.getSession().setAttribute("codeValue", codeValue);
比較使用者輸入的值和session中的codeValue是否相等即可;

下面是jsp頁面調用servlet:ValidCodeServlet.java

ValidCodeServlet中調用了上面的ValidCodeUtils 驗證碼產生工具類

package com.hoo.servlet; 

import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import com.hoo.util.ValidCodeUtils; 

@SuppressWarnings("serial") 
public class ValidCodeServlet extends HttpServlet { 
 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
 throws ServletException, IOException { 
    try { 
 ValidCodeUtils.getImage(request, response); 
    } catch (Exception e) { 
 e.printStackTrace(); 
    } 

public void doPost(HttpServletRequest request, HttpServletResponse response) 
 throws ServletException, IOException { 
    doGet(request, response); 

 

jsp頁面調用servlet方法即可

 

js:reloadValidCode方法 

function reloadValidCode(o) { 
o.src = "${pageContext.request.contextPath }/validCodeServlet?timed=" + new Date().getMilliseconds(); 

這裡的"timed=" + new Date().getMilliseconds();是需要防止IE緩衝用的 

html標籤: 
<img src="${pageContext.request.contextPath }/validCodeServlet" title="看不清,點擊重新整理" onclick="reloadValidCode(this)"/> 
直接跟Servlet名稱配置的url即可,和web.xml配置對應。主要調用路徑${pageContext.request.contextPath }/validCodeServlet這樣會帶上根目錄,比較保險。 

web.xml中validCodeServlet配置 
<servlet> 
<servlet-name>validCodeServlet</servlet-name> 
<servlet-class>com.hoo.servlet.ValidCodeServlet</servlet-class> 
</servlet> 

<servlet-mapping> 
<servlet-name>validCodeServlet</servlet-name> 
<url-pattern>/validCodeServlet</url-pattern> 
</servlet-mapping> 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.