jsp验证码

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);

}


// 将认证码存入SESSION

session.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>

 

 

刷新验证码js

function show(o){//重载验证码
        var timenow = new Date().getTime();
        o.src="code.jsp?d="+timenow;
        //超时执行;
        setTimeout(function(){
        o.src="code.jsp?d="+timenow;
        }
        );
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值