視圖調(diào)用:
<li>
<lable>驗證碼:</lable>
<input type="text" name="yzm">
<img alt="" src="/yzm" onclick="refreshCode(this);">
<script type="text/javascript">
//刷新驗證碼
function refreshCode(obj){
obj.src = "/yzm?time=" + new Date().getTime();
}
</script>
</li>Servlet頁面
package yzm;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet(name = "CaptchaCodeServlet", value="/yzm")
public class CaptchaCodeServlet extends HttpServlet {
//繪制字符的X軸坐標
private int x = 0;
// 設(shè)置驗證碼圖片中顯示的字體高度
private int fontHeight;
//繪制字符的Y軸坐標
private int codeY;
// 在這里定義了驗證碼圖片的寬度
private int width = 100;
// 定義驗證碼圖片的高度。
private int height = 30;
// 定義驗證碼字符個數(shù),此處設(shè)置為4位
private int codeNum = 4;
Color getRandColor(int ff, int cc){
//給定范圍獲得隨機顏色
Random random = new Random();
if(ff>255) ff=255;
if(cc>255) cc=255;
int r=ff+random.nextInt(cc-ff);
int g=ff+random.nextInt(cc-ff);
int b=ff+random.nextInt(cc-ff);
return new Color(r,g,b);
}
char[] codes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', };
/**
* 對驗證圖片屬性進行初始化
*/
public void init() throws ServletException {
// 從部署文件web.xml中獲取程序初始化信息,圖片寬度跟高度,字符個數(shù)信息
// 獲取初始化字符個數(shù)
String strCodeNums = this.getInitParameter("codeNum");
// 獲取驗證碼圖片寬度參數(shù)
String strW = this.getInitParameter("width");
// 獲取驗證碼圖片高度參數(shù)
String strH = this.getInitParameter("height");
// 將配置的字符串信息轉(zhuǎn)換成數(shù)值類型數(shù)字
try {
if (strH != null && strH.length() != 0) {
height = Integer.parseInt(strH);
}
if (strW != null && strW.length() != 0) {
width = Integer.parseInt(strW);
}
if (strCodeNums != null && strCodeNums.length() != 0) {
codeNum = Integer.parseInt(strCodeNums);
}
} catch (NumberFormatException e) {
}
//控制字符的間距 - 2
x = width / (codeNum + 1) - 2;
fontHeight = height - 2;
codeY = height - 4;
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
// 定義驗證碼圖像的緩沖流
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 產(chǎn)生圖形上下文
Graphics2D g = buffImg.createGraphics();
// 創(chuàng)建隨機數(shù)產(chǎn)生函數(shù)
Random random = new Random();
// 將驗證碼圖像背景填充為白色
g.setColor(getRandColor(210, 260));
g.fillRect(0, 0, width, height);
// 創(chuàng)建字體格式,字體的大小則根據(jù)驗證碼圖片的高度來設(shè)定。
Font font = new Font("宋體", Font.PLAIN, fontHeight);
// 設(shè)置字體。
g.setFont(font);
// 為驗證碼圖片畫邊框,為一個像素。
g.setColor(Color.BLACK);
// g.drawRect(0, 0, width - 1, height - 1);
// 隨機生產(chǎn)100跳圖片干擾線條,使驗證碼圖片中的字符不被輕易識別
g.setColor(getRandColor(110, 240));
for (int i = 0; i < 100; 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);
}
// randomCode保存隨機產(chǎn)生的驗證碼
StringBuffer randomCode = new StringBuffer();
// 隨機生產(chǎn)codeNum個數(shù)字驗證碼
for (int i = 0; i < codeNum; i++) {
// 得到隨機產(chǎn)生的驗證碼
String strRand = String.valueOf(codes[random.nextInt(codes.length)]);
// 用隨機產(chǎn)生的顏色將驗證碼繪制到圖像中。
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
// 將隨機字符寫入到圖像環(huán)境中
g.drawString(strRand, (i + 1) * x, codeY);
// 將產(chǎn)生的隨機字符組合在一起。
randomCode.append(strRand);
}
// 將生產(chǎn)的驗證碼保存到Session中
HttpSession session = req.getSession();
session.setAttribute("validate", randomCode.toString());
// 設(shè)置圖像緩存為no-cache。
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
resp.setContentType("image/jpeg");
// 將最終生產(chǎn)的驗證碼圖片輸出到Servlet的輸出流中
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}效果如下:

