簡單圖片驗證碼
1.將驗證碼作為一個jsp頁面顯示,並用圖片進行載入
<img id="loginform:vCode" src="${pageContext.request.contextPath }/validatecode.jsp"
onclick="javascript:document.getElementById('loginform:vCode').src='${pageContext.request.contextPath }/validatecode.jsp?'+Math.random();" />
注意:後面+Math.random()時為了防止提交重複性,保證每次點選都會重新整理
2.jsp頁面書寫
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.Random"%>
<%@ page import="java.io.OutputStream"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.Font"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="javax.imageio.ImageIO"%>
<%
int width = 80;
int height = 32;
//建立圖片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 設定背景顏色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
// draw the border
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 生成隨機數 並轉成16進位制數 (0到9 a到f所以不會有f以後的字母)
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
// make some confusion
for (int i = 0; i < 50; i++) {
int x = rdm.nextInt(width);
int y = rdm.nextInt(height);
g.drawOval(x, y, 0, 0);
}
//寫隨機程式碼
String capstr = hash1.substring(0, 4);
session.setAttribute("key", capstr);
g.setColor(new Color(0, 100, 0));
g.setFont(new Font("Candara", Font.BOLD, 24));
g.drawString(capstr, 8, 24);
g.dispose();
response.setContentType("image/jpeg");
out.clear();
out = pageContext.pushBody();
OutputStream strm = response.getOutputStream();
ImageIO.write(image, "jpeg", strm);
strm.close();
%>
後再補充