Java 隨機生成驗證碼(支撐年夜小寫字母、數字、隨機字體)的實例。本站提示廣大學習愛好者:(Java 隨機生成驗證碼(支撐年夜小寫字母、數字、隨機字體)的實例)文章只能為提供參考,不一定能成為您想要的結果。以下是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>