在系統登錄或者註冊時,爲防止有人惡意註冊賬號或者嘗試暴力破解用戶密碼,常需要使用驗證碼來驗證用戶是否是人爲操作。
話不多說,直接上代碼:
public class yzm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public yzm() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 設置瀏覽器不緩存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//設置響應類型
response.setContentType("image/jpeg");
//定義圖片寬高
int width = 60;
int height = 20;
//創建一個緩衝區圖片
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//使用緩衝區圖片創建 圖形對象以用於繪製驗證碼
Graphics g = img.getGraphics();
//設置畫筆顏色爲黃色,後續畫矩陣,相當於設置圖形背景顏色爲黃色
g.setColor(new Color(255, 255, 0));
g.fillRect(0, 0, width, height);
//設置字體
g.setFont(new Font("微軟雅黑", Font.ITALIC, 18));
//定義空字符串,以便後續連接
String srand = "";
Random random = new Random();
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
srand += rand;
//隨機更換顏色,以便驗證碼數字顏色多樣
g.setColor(new Color(30 + random.nextInt(160), 50 + random.nextInt(100), 80 + random.nextInt(140)));
//將隨機數畫入圖形
g.drawString(rand, i*16, 18);
}
//隨機生成30條線條
for (int i = 0; i < 30; i++) {
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(10);
int y1=random.nextInt(10);
g.drawLine(x, y, x+x1, y+y1);
}
//在session中設置連接好的驗證碼字符串
request.getSession().setAttribute("yzm", srand);
//釋放 圖形資源
g.dispose();
//將圖片寫入到response輸出流
ImageIO.write(img, "jpeg", response.getOutputStream());
}
接下來可在jsp中驗證:
<body>
<form action="index.jsp">
<input type="text" name="yzm"> <img alt="" src="yzm"> <input
type="submit">
</form>
<%
if (request.getParameter("yzm") != null) {
if (request.getParameter("yzm").toString().equals(session.getAttribute("yzm").toString()))
out.print("<script>alert('succeed!')</script>");
}
%>
</body>
運行效果: