六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 77|回复: 0

jsp验证码

[复制链接]

升级  29.33%

24

主题

24

主题

24

主题

秀才

Rank: 2

积分
94
 楼主| 发表于 2013-1-16 16:46:25 | 显示全部楼层 |阅读模式
code.jsp
<%@ page autoFlush="false" contentType="text/html; charset=GBK" import="java.util.*,java.io.*,java.awt.*,javax.imageio.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*"%><%!Color getRundColor(int x, int y) {Random random = new Random();//判断sRGB 分量if (x > 225)x = 225;if (y > 225)y = 225;//生成0.0-1.0之间的颜色值int red = x + random.nextInt(y - x); //红色色值int green = x + random.nextInt(y - x); //绿色值int blue = x + random.nextInt(y - x); //蓝色色值//返回创建的颜色对象return new Color(red, green, blue); // 用指定的红色、绿色和蓝色值创建一种不透明的 sRGB 颜色,这三个颜色值都在 0.0 - 1.0 的范围内。}%><%//设置页面不缓存response.setHeader("Pragma", "No-cache"); //用于设定禁止浏览器从本地机的缓存中调阅页面内容,设定后一旦离开网页就无法从Cache中再调出;response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);//设置指定名称的Data类型的HTTP头的值//在内存中创建图象int width = 60, height = 20; //声明图片高和宽//具有 8 位 RGB 颜色分量的图像,对应于 Windows 或 Solaris 风格的 BGR 颜色模型,具有打包为整数像素的 Blue、Green 和 Red 三种颜色。BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);//声明并获取图片上下文的基类对象,用于设置字体颜色等属性Graphics crGraphics = image.getGraphics();//声明一个随机类对象Random random = new Random();//设置背景颜色crGraphics.setColor(getRundColor(200, 250));crGraphics.fillRect(0, 0, width, height); //使用图形上下文的当前颜色填充该矩形。//设置字休crGraphics.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //将此图形上下文的字体设置为指定字体//随机生成干扰线crGraphics.setColor(getRundColor(160, 200));for (int i = 0; i < 160; i++) {int x = random.nextInt(width);int y = random.nextInt(height);int x2 = random.nextInt(12);int y2 = random.nextInt(12);crGraphics.drawLine(x, y, x + x2, y + y2);}// 取随机产生的认证码(4位数字)String sRand = "";//随机数已在JSP页面产生for (int i = 0; i < 4; i++) {String rand = String.valueOf(random.nextInt(10));sRand += rand;// 将认证码显示到图象中crGraphics.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110), 20 + random.nextInt(110)));crGraphics.drawString(rand, 13 * i + 6, 16);}// 将认证码存入SESSIONsession.setAttribute("hcode", sRand);// 图象生效crGraphics.dispose();// 输出图象到页面ImageIO.write(image, "JPEG", response.getOutputStream());out.clear();out = pageContext.pushBody();%> 
 
显示页面
   <a href="javascript:show(document.getElementById('hcode'))"><img id="hcode" alt="" title="点击刷新" src="code.jsp" class="alltext"/></a> 
 
刷新验证码jsfunction show(o){//重载验证码        var timenow = new Date().getTime();        o.src="code.jsp?d="+timenow;        //超时执行;        setTimeout(function(){        o.src="code.jsp?d="+timenow;        }        );} 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表