servlet 实现验证码

    xiaoxiao2023-10-03  115

    //创建一个能在内存中图片的对象 int width = 100; int heigth = 50; BufferedImage bi = new BufferedImage(width,heigth,BufferedImage.TYPE_INT_RGB); //美化 Graphics gp = bi.getGraphics();//获取画笔对象 gp.setColor(Color.green);//设置画笔颜色 gp.fillRect(0,0,width,heigth); //画边框 gp.setColor(Color.yellow); gp.drawRect(0,0,width-1,heigth-1); //写验证码 String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz123456789"; //生成随机角标 Random r = new Random(); gp.setColor(Color.black); for (int i = 1; i <= 4; i++) { //获取字符 int in = r.nextInt(str.length()); int he = r.nextInt(heigth); char c = str.charAt(in); gp.drawString(c+"",width/5*i,he); } //画干扰线 gp.setColor(Color.BLUE); //随机生成15条干扰线 for (int i = 0; i < 15; i++) { int x1 = r.nextInt(width); int x2 = r.nextInt(width); int y1 = r.nextInt(heigth); int y2 = r.nextInt(heigth); gp.drawLine(x1 ,y1,x2,y2); } //输出到页面 ImageIO.write(bi,"jpg",response.getOutputStream());

    前端页面设置

    <script> //给超链接和图片链接添加单击事件 window.onload=function () { //获取图片对象 var im = document.getElementById("checkCode"); //绑定单击事件 im.onclick = function () { im.src="/res?"+new Date().getTime() } var ch = document.getElementById("change"); ch.onclick = function () { im.src = "/res?"+new Date().getTime() } } //重设图片的src </script> <body> <img src="/res" id="checkCode"> <a href="" id="change">看不清?</a> </body> </html>

     

    最新回复(0)