北京北大青鳥(niǎo)學(xué)術(shù)部:JSP驗(yàn)證碼介紹

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

1. random.jsp (產(chǎn)生四位的隨機(jī)字符,由0-9,a-z,A-Z構(gòu)成.并把最終字符串放到session中保存以讓后續(xù)頁(yè)面驗(yàn)證真?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) {//給定范圍獲得隨機(jī)顏色
  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);
 }
%>
<%
 //設(shè)置頁(yè)面不緩存(北京北大青鳥(niǎo)) 
 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();

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

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

 // 隨機(jī)產(chǎn)生5條干擾線,使圖象中的認(rèn)證碼不易被其它程序探測(cè)到(北京北大青鳥(niǎo)) 
 for (int i = 0; i < 5; i++) {
  g.setColor(new Color(random.nextInt(50),random.nextInt(50),random.nextInt(50)));
  //設(shè)定字體
  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);
 }

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

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

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

2. index.jsp (顯示驗(yàn)證圖片)
<%@ 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>驗(yàn)證碼測(cè)試</title>
  </head>
 
  <body>
    <img src="random.jsp" alt="不清楚,單擊更換圖片" onclick="this.src='',this.src='random.jsp'" />
  </body>
</html>
北京北大青鳥(niǎo)) 

北大青鳥(niǎo)網(wǎng)上報(bào)名
北大青鳥(niǎo)招生簡(jiǎn)章