Java Web制作登录验证码实现代码解析
导读
图例如下
具体操作如下:
新建一个servlet,代码如下:标记一个WebServlet,
1 @WebServlet(urlPatterns = {"/checkCode"}) //验证码Servlet
绘制验证码图片的核心代码:
int width = 100; int height = 50; //创建图片对象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //美化图片 Graphics g = image.getGraphics(); //1:填充背景 g.setColor(Color.pink); g.fillRect(0, 0, width, height); //画边框 g.setColor(Color.blue); g.drawRect(0, 0, width - 1, height - 1); //生成一个验证码字符串 String strCheckCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StrCheckCode = ""; for (int i = 1; i <= 4; i++) { int index = random.nextInt(strCheckCode.length()); char ch = strCheckCode.charAt(index); StrCheckCode += ch;//拼接验证码 g.drawString(ch + "", width / 5 * i, height / 2); } //画干扰线 for (int i = 0; i < 5; i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(height); int y2 = random.nextInt(height); g.drawLine(x1, x2, y1, y2); } //输出,显示出来 ImageIO.write(image, "jpg", resp.getOutputStream()); }
首先是new一个BufferedImage,然后给定长和宽,之后是指边框和背景色,接着使用随机数生成4个字符绘制在图片上,接着使用DrawLine绘随机制干扰线,
然后在前端页面引入图片,然后给图片绑定点击事件,点击后重新访问servlet即可:
//点击验证码图片,重新生成新验证 $(function () { $("#imgCheckCode").click(function () { var img = document.getElementById("imgCheckCode"); var date = new Date(); img.src = "http://localhost:8080/blogs_war_exploded/checkCode?op=setCheckCode&a=" + date; }) })
<div class="inputCheckCode"> <div class="inputCheckCodeLeftIco">➤</div> <div class="inputCheckCodeRightInput"> <input type="text" name="checkCode" id="checkCode" placeholder="验证码" autocomplete="off"/> </div> <img src="http://localhost:8080/blogs_war_exploded/checkCode?op=setCheckCode" id="imgCheckCode"> </div>
最后输出即可,效果如下:
评论(0)