其他分享
首页 > 其他分享> > 【验证码输出】利用时间戳实现永远不重复的刷新

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

作者:互联网

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>

标签:输出,width,int,刷新,验证码,height,nextInt,graphics,import
来源: https://blog.csdn.net/sunjiangdomg/article/details/121570170