北京北大青鸟学术部:JSP验证码介绍

本篇文章由北京北大青鸟通州校区ACCP学术部提供:

1. random.jsp (产生四位的随机字符,由0-9,a-z,A-Z构成.并把最终字符串放到session中保存以让后续页面验证真伪)
代码如下
<%@ 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);

 // 在内存中创建图象
 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);

 // 随机产生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);
 }

 // 取随机产生的认证码(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;
  // 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以直接生成(北京北大青鸟) 
  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>
北京北大青鸟) 

北大青鸟网上报名
北大青鸟招生简章