【验证码输出】利用时间戳实现永远不重复的刷新

package web.response;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CheckCodeServlet1", value = "/CheckCodeServlet1")
public class CheckCodeServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        验证码的实现
//        1.获取验证码图片对象,设置图片大小
        int width = 200;
        int height = 100;

        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

//        2.获取画笔对象
        Graphics graphics = bufferedImage.getGraphics();

//        3.填充背景色,包括背景颜色,填充或者画
        graphics.setColor(Color.cyan);
        graphics.fillRect(0,0,width,height);

//        4.画边框
        graphics.setColor(Color.orange);
        graphics.drawRect(0,0,width-1,height-1);

//        5.写验证码
        String str = "QWERTYUIOPASDFGHJKLZXCVBNMqazwsxedcrfvtgbyhnujmikolp0123456789";
//      随机生成验证码
        Random random = new Random();
        for (int i = 1; i < 5; i++) {
            //      随机索引值
            int nextInt = random.nextInt(str.length());

            char charAt = str.charAt(nextInt);
//        写验证码
            graphics.drawString(charAt+"",width/5*i,height/2);
        }
        //        画干扰线
        graphics.setColor(Color.red);
//        随机生成坐标点
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);

            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);

            graphics.drawLine(x1,y1,x2,y2);
        }
//        输出验证码图片到页面
        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
    }
}

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册界面</title>

    <script>
        window.onload = function (){
            //获取图片对象
            var img = document.getElementById("checkcode");
        //    绑定单击时间
            img.onclick =function (){
            //    加时间戳
                var data = new Date().getTime();

                img.src = "CheckCodeServlet1"+data;
            }
        }
    </script>
</head>
<body>
    <img id="checkcode" src="CheckCodeServlet1" ><br>
    <a href="" id="change">看不清,换一张</a>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值