JavaWeb-验证码案例

案例代码-创建验证码

java

@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int width = 100;
        int height = 50;
        //        1. 创建对象,在内存中储存图片,即验证码图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //        2. 美化图片
        //         2.1创建画笔对象
        Graphics g = image.getGraphics();
        //        2.2 设置画笔颜色
        g.setColor(Color.PINK);
        //        2.3使用画笔设置填充色
        g.fillRect(0, 0, width, height);
        //         2.4 画边框
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width - 1, height - 1);

        //        定义所有码的集合
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        //        生成随机角标
        Random ran = new Random();

        //        获取字符
        for (int i=1;i<=4;i++){
            int index = ran.nextInt(str.length());
            char ch = str.charAt(index);
            //        2.5写验证码
            g.drawString(ch+"",width/5*i,height/2);

        }

        //         -------------------2.6 画干扰线-------------------
        g.setColor(Color.GREEN);
        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
        //         -------------------画干扰线-------------------
        //        3. 将图片输出到页面显示
        boolean jpg = ImageIO.write(image, "jpg", resp.getOutputStream());

    }}

效果:

image

说明: 上述的servlet可以作为img资源,即/checkCodeServlet可以作为验证码图片的资源,可以使用src引用。

模拟验证码点击刷新

思路: 点击超链接或验证码图片,请求这个servlet即会刷新图片。但要注意处理图片缓存问题。

register.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>$Title$</title>

        <script>

            window.onload = function (){
                // 1. 获取图片对象
                var img = document.getElementById("checkCode")
                // 2. 给图片绑定单击事件
                img.onclick = function (){
                    // 添加时间戳, 处理图片缓存问题使得加载的图片不是缓存中的旧图片
                    var date = new Date().getTime();
                    img.src = "/day15/checkCodeServlet?"+date;
                }
                // 获取链接对象
                var  a = document.getElementById("change");

                a.onclick = function (){
                    a.href ="/day15/checkCodeServlet?"+date;
                }

            }


        </script>
    </head>
    <body>

        <img id="checkCode" src="/day15/checkCodeServlet" />

        <a id="change" href=""> 看不清,换一张?</a>

    </body>
</html>

效果: 使用火狐浏览器访问http://localhost:8086/day15/register.html的效果

image

posted @ 2022-01-15 00:13  茶哩哩  阅读(135)  评论(0编辑  收藏  举报