網上有很多關于驗證碼的代碼部分。我還是把我自己寫的驗證碼部分粘出來算了。
package com.Neil.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
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;
public class VaildationCodeServlet extends HttpServlet {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
//驗證碼圖檔的寬度。
private int width = 58;
//驗證碼圖檔的高度。
private int height = 20;
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
StringBuffer randomCode = new StringBuffer();
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
//建立一個随機數生成器類。
Random random = new Random();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
//建立字型,字型的大小應該根據圖檔的高度來定。
Font font = new Font("Times New Roman", Font.PLAIN, 18);
//設定字型。
g.setFont(font);
//畫邊框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
//随機産生160條幹擾線,使圖象中的認證碼不易被其它程式探測到。
g.setColor(Color.GRAY);
for (int i = 0; i < 160; 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用于儲存随機産生的驗證碼,以便使用者登入後進行驗證。
int red = 0, green = 0, blue = 0;
//随機産生4位數字的驗證碼。
for (int i = 0; i < 4; i++) {
//得到随機産生的驗證碼數字。
String strRand = String.valueOf(random.nextInt(10));
//産生随機的顔色分量來構造顔色值,這樣輸出的每位數字的顔色值都将不同。
red = random.nextInt(110);
green = random.nextInt(50);
blue = random.nextInt(50);
//用随機産生的顔色将驗證碼繪制到圖像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, 13 * i + 6, 16);
//将産生的四個随機數組合在一起。
randomCode.append(strRand);
}
//将四位數字的驗證碼儲存到Session中。
HttpSession session = req.getSession();
session.setAttribute("randomCode", randomCode.toString());
System.out.println(randomCode.toString());
/*ServletContext application = this.getServletContext();
application.setAttribute("randomCode", randomCode.toString());*/
//禁止圖像緩存。
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
resp.setContentType("image/jpeg");
//将圖像輸出到Servlet輸出流中。
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(bi, "jpeg", sos);
sos.close();
}
/*
* 獲得驗證碼
* */
}