北京北大青鳥學術(shù)部:JSP驗證碼介紹

本篇文章由北京北大青鳥通州校區(qū)ACCP學術(shù)部提供:

1. random.jsp (產(chǎn)生四位的隨機字符,由0-9,a-z,A-Z構(gòu)成.并把最終字符串放到session中保存以讓后續(xù)頁面驗證真?zhèn)?
代碼如下
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*;" pageEncoding="UTF-8" %>
<%!
 private Color getRandColor(int fc, int bc) {//給定范圍獲得隨機顏色
  Random random = new Random();
  if (fc > 255)
   fc = 255;
  if (bc > 255)
   bc = 255;
  int r = fc + random.nextInt(bc - fc);
  int g = fc + random.nextInt(bc - fc);
  int b = fc + random.nextInt(bc - fc);
  return new Color(r, g, b);
 }
%>
<%
 //設置頁面不緩存(北京北大青鳥) 
 response.setHeader("Pragma", "No-cache");
 response.setHeader("Cache-Control", "no-cache");
 response.setDateHeader("Expires", 0);

 // 在內(nèi)存中創(chuàng)建圖象
 int width = 100, height = 30;
 BufferedImage image = new BufferedImage(width, height,
   BufferedImage.TYPE_INT_RGB);

 // 獲取圖形上下文
 Graphics g = image.getGraphics();

 //生成隨機類
 Random random = new Random();

 // 設定背景色
 g.setColor(getRandColor(200, 250));
 g.fillRect(0, 0, width, height);

 // 隨機產(chǎn)生5條干擾線,使圖象中的認證碼不易被其它程序探測到(北京北大青鳥) 
 for (int i = 0; i < 5; i++) {
  g.setColor(new Color(random.nextInt(50),random.nextInt(50),random.nextInt(50)));
  //設定字體
  g.setFont(new Font("Times New Roman", Font.PLAIN, random.nextInt(10)+20));
  int x = random.nextInt(30);
  int y = random.nextInt(30);
  int xl = random.nextInt(30)+80;
  int yl = random.nextInt(30);
  g.drawLine(x, y, xl, yl);
 }

 // 取隨機產(chǎn)生的認證碼(4位隨機符號)
 String sRand = "";
 //種子,可以放中文
 String rand = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 for (int i = 0; i < 4; i++) {
  String temp = String.valueOf(rand.charAt(random.nextInt(rand.length())));
  sRand += temp;
  // 將認證碼顯示到圖象中,調(diào)用函數(shù)出來的顏色相同,可能是因為種子太接近,所以直接生成(北京北大青鳥) 
  g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
  g.drawString(temp, 20 * i + 6, 20);
 }

 // 將認證碼存入SESSION
 session.setAttribute("numRand", sRand);
 // 圖象生效
 g.dispose();

 // 輸出圖象到頁面
 ImageIO.write(image, "JPEG", response.getOutputStream());
 out.clear();
 out = pageContext.pushBody();
%>

2. index.jsp (顯示驗證圖片)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>驗證碼測試</title>
  </head>
 
  <body>
    <img src="random.jsp" alt="不清楚,單擊更換圖片" onclick="this.src='',this.src='random.jsp'" />
  </body>
</html>
北京北大青鳥) 

北大青鳥網(wǎng)上報名
北大青鳥招生簡章