美文网首页
Java+JSP实现验证码

Java+JSP实现验证码

作者: 念念碎平安夜 | 来源:发表于2019-12-30 14:08 被阅读0次
    1、创建Servlet类

    (1)主要目的为返回生成随机字符串的图片

    @WebServlet("/newCode")
    public class NewCode extends HttpServlet {
        private Random random = new Random(); // 随机数对象
        private int width = 80; // 宽度
        private int height = 30; // 高度
        private int fontsize = 12; // 字体大小
        private String str = "0123456789abcdef"; // 字体大小
        
        //生成最少4个字符的随机字符串
            private String randCode(int len){
                if(len < 4) {
                    len = 4;
                }
                //更改宽度
                width = 5 + fontsize*len;
                //生成字符串
                String code = "";
                for (int i = 0; i < len; i++) {
                    code += str.charAt(random.nextInt(str.length()));
                }
                return code;
            }
        
        // 返回随机颜色
        private Color randColor() {
            int r = random.nextInt(256);
            int g = random.nextInt(256);
            int b = random.nextInt(256);
            return new Color(r, g, b);
        }
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 1.创建画板
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 2.创建画笔
            Graphics2D pen = (Graphics2D) img.getGraphics();
            // 3.生成随机内容
            String code = randCode(4);
            request.getSession().setAttribute("valiCode", code);
            // 4.绘制内容
            // 4.1设置绘制区域
            pen.fillRect(0, 0, width, height);
            // 4.2设置字体
            pen.setFont(new Font("微软雅黑", Font.BOLD, fontsize));
            // 4.3按顺序逐个绘制字符
            for (int i = 0; i < code.length(); i++) {
                pen.setColor(randColor());
                // 绘制字符
                pen.drawString(code.charAt(i) + "", 5 + i * fontsize, (fontsize + height) / 2);
            }
            // 4.4绘制噪音线
            for (int i = 0; i < 2; i++) {
                pen.setColor(randColor());
                pen.setStroke(new BasicStroke(3));
                pen.drawLine(random.nextInt(width/2), random.nextInt(height),
                        random.nextInt(width), random.nextInt(height));
            }
            // 5、存为图片并发送
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(img, "png", out);
            out.flush();
            out.close();
        }
    }
    

    (2)主要目的是判断用户输入的字符串是否与session中的字符串(图片验证码)一致,若一致则跳转到正确页面,否则提示重新输入。

    @WebServlet("/valiCode")
    public class ValiCode extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            this.doPost(request, response);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 1、得到数据
            String inCode = request.getParameter("inCode").toString().toLowerCase();
            String valiCode = request.getSession().getAttribute("valiCode").toString().toLowerCase();
            // 2、验证是否正确
            if (inCode.equals(valiCode)) {
                response.sendRedirect("index.jsp");
            } else {
                request.getSession().setAttribute("err", "验证码输入错误,请重新输入!");
                // 返回上一页
                String url = request.getHeader("Referer");
                response.sendRedirect(url);
            }
        }
    }
    
    2、创建JSP页面

    (1)目的为验证码匹配成功后跳转到正确响应页面

    <body>
    This is my JSP page.
    </body>
    

    (2)用户输入界面

    <style type="text/css">
    .code_a {
        color: #0000ff;
        font-size: 12px;
        text-decoration: none;
        cursor: pointer;
    }
    
    #imgCode {
        cursor: pointer;
    }
    </style>
    <script type="text/javascript">
        function changeCode() {
            var imgCode = document.getElementById("imgCode");
            imgCode.src = "newCode?" + Math.random();
        }
    </script>
    </head>
    <body>
        <form action="valiCode" method="post">
            <label>验证码:</label> <input type="text" id="inCode" name="inCode" /> <img
                alt="" src="newCode" align="center" id="imgCode"
                onclick="changeCode()"> <a class="code_a"
                onclick="changeCode()">换一张</a><br /> <input type="submit" value="登录" />
        </form>
        <div style="color: red;">${err}</div>
    </body>
    

    相关文章

      网友评论

          本文标题:Java+JSP实现验证码

          本文链接:https://www.haomeiwen.com/subject/amokoctx.html