手动制作java的验证码

Web应用验证码的组成

(1)输入框

(2)显示验证码的图片

验证码的制作流程

                                  

 

生成验证码的容器使用 j2ee的servlet

生成图片需要的类

(1) BufferedImage 图像数据缓冲区

(2)Graphic绘制图片

(3)Color获取颜色

(4)Random生成随机数

(5)ImageIO输入图片

具体实现流程:

(1)定义一个Servlet,用于生成验证码

(2)定已BufferedImage对象,主要作用就是制作一个图片缓冲区,作为图片的一个临时容器。

(3)获得Graphic对象,画图的“背景”,理解为”画布”

(4)通过Random生成随机数,来制作验证信息

(5)通过Graphic操作,进行具体画图

(6)信息存至session中

(7)使用ImageIO输出生成的图片,通过设置ImageIO的 write()方法中的out参数,response.getOutputStream(),将图片传至前台

(8)制作验证用的servlet,提取session中的数据进行验证(这里采用ajax异步方法)

具体代码实现(Web端验证码实例)

 

 1 <html>
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 4 <title>java验证码</title>
 5 <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
 6 </head>
 7 <body>
 8    验证码输入:<input type="text" name="checkcode"> &nbsp;
 9    <img id="codeimg" alt="验证码" src="ImageServlet">
10    <a href="javascript:reloadCode();">看不出清楚?</a><br/>
11    <input type="submit" value="提交">
12    <div id="info" style="color:red;"></div>
13    
14   <script type="text/javascript">
15     $(function(){
16         //ajax异步传验证码至后台
17         $("input[type=submit]").click(function(){
18             $.post("CheckCode",
19                     {"code":$("input[name=checkcode]").val()},
20                     function(data,textStatus)
21                     {
22                         console.log(textStatus);
23                         $("#info").html(data);
24                     },"text");
25         });
26     })
27     //js刷新,重新请求页面,获得新的验证码
28     function reloadCode(){
29         var time = new Date().getTime();//创建不同的时间
30         $("#codeimg").attr("src","ImageServlet?time="+time);//因为时间参数不同,请求重新
31     }
32   </script> 
33 </body>
34 </html>

 

ImageServlet类(验证码生成部分)

@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        BufferedImage bimg = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics g = bimg.getGraphics();
        Color color = new Color(200,151,255);//颜色生成
        g.setColor(color);
        g.fillRect(0, 0, 68, 22);
        char[] ch="ABCDEFGHJIKLMNOPQRSTUVWXYZ0123456789".toCharArray();//获得一个含有字母和数字的数组,后续随机从中获取字符
        Random random = new Random(); //创建随机数
        int len = ch.length,index;
        StringBuffer sBuffer = new StringBuffer();
        
        //循环产生4个随机字符
        for(int i = 0 ;i<4;i++)
        {
            index = random.nextInt(len);//产生随机字母与数字
            g.setColor(new Color(random.nextInt(88),random.nextInt(120),random.nextInt(90)));//创建随机颜色
            g.drawString(ch[index]+"", (i)*15+3, 18);
            sBuffer.append(ch[index]);//将随机获取的字符放置缓冲串中
        }
        request.getSession().setAttribute("newCode", sBuffer.toString());//存至session便于后续验证
        ImageIO.write(bimg, "JPG", response.getOutputStream());//通过ImageIO输出图片,并传至前台
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

CheckCode(验证码验证servlet)

 

@WebServlet("/CheckCode")
public class CheckCode extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckCode() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("utf-8");
        String code = request.getParameter("code").toUpperCase();//获取传来验证码并进行大小写转换
        String result=null;
        if(request.getSession().getAttribute("newCode").equals(code))
        {
            result="验证成功!";
            response.getWriter().append(result);
        }
        else {
            result="验证码错误!";
            response.getWriter().append(result);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

版权声明:本文为TheGCC原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/TheGCC/p/8903586.html