網(wǎng)頁登錄中圖片驗證的實現(xiàn),核心代碼如下所示:
創(chuàng)建圖片資源 BufferedImage image = new BufferedImage(WIDTH, Hight, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();
* 設(shè)置內(nèi)容
/
private void setContent(Graphics2D g) {
g.setColor(Color.BLACK);
g.setFont(new Font("宋體", Font.BOLD,40));
int x = 20;
int y = 40;
for(int i = 0; i < 4; i ++){
double degree = new Random().nextInt()%30 ;
g.rotate(degree * Math.PI/180, x + 20, y - 20);
String num = new Random().nextInt(9) + "";
g.drawString(num, x, y);
g.rotate(-degree Math.PI/180, x + 20, y - 20);
x += 30;
}
}
/**
* 設(shè)置干擾線
* @param g
*/
private void setLine(Graphics g) {
g.setColor(Color.BLACK);
for(int i = 0; i < 5; i ++){
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(Hight);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(Hight);
g.drawLine(x1, y1, x2, y2);
}
}
/**
* 畫出邊框
* @param g
*/
private void setFrame(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect(0, 0, WIDTH, Hight);
}
/**
* 填充背景顏色
* @param g
*/
private void setBackgroundColor(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(1, 1, WIDTH-2, Hight-2);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//將數(shù)據(jù)寫入流中
ImageIO.write(image, "jpg", response.getOutputStream());
在登錄中我們有時會使用漢字認證,漢字的范圍:\u4e00-\u9fa5。
實現(xiàn)點擊圖片換一張,在js點擊事件中的代碼:
this.src = this.src + "?" + new Date().getTime();
this:指的是圖片image標(biāo)簽
src:指的是servlet資源,將資源重新賦值給image,就是再次向服務(wù)器發(fā)送請求.
"?" + new Date().getTime():由于緩存的存在,這句話是為了避免和上次發(fā)送的請求相同而取本地緩存。