jsp 页面 修改 刷新图片

本文介绍如何使用Java生成带有验证码的图片,并将其通过HTTP响应发送给客户端。同时,文章还展示了如何设置Cookie来存储验证码值,以及如何利用JavaScript实现验证码图片的刷新功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java代码:图片流的生成

BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

String vCode = drawGraphic(image);
vCode = encrypt(vCode);
Cookie cookie = new Cookie(randomCodeKey, vCode);
cookie.setMaxAge(-1);
cookie.setPath("/");
response.addCookie(cookie);
response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");    //这句话是必须的,不能缺少
        
        ServletOutputStream sos = null;
        try {
sos = response.getOutputStream();
ImageIO.write(image, "jpeg",sos);
} catch (Exception e) {
throw new RuntimeException(e);
}
finally {
try {sos.close();} catch (IOException e) {e.printStackTrace();}

}

js的里面写的action的路劲,随即数不能缺少,因为不同的浏览器对action的请求次数不一样:

function changeImg(){
$("#image").attr("src",'/img?s='+Math.random());
}

html代码:

<img alt="" id="image" name="image" src="img" onclick="changeImg();" style="cursor: pointer; position: relative;" border="0" />
<a href="#" onclick="changeImg();">换一个</a>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值