实现网站验证码切换功能
一、样例
样例1、
样例2、
二、实现原理
三、实现代码
com.fry.servlet.VerifyCodeServlet
1 package com.fry.servlet; 2 3 import javax.imageio.ImageIO; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.awt.*; 10 import java.awt.image.BufferedImage; 11 import java.io.IOException; 12 import java.util.Random; 13 14 /** 15 * Created by fry on 2017/5/31. 16 */ 17 @WebServlet(name = "VerifyCodeServlet", urlPatterns = "/code") 18 public class VerifyCodeServlet extends HttpServlet { 19 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 20 21 } 22 23 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 24 int width = 100; 25 int height = 30; 26 27 String data = "abcdefghijklmnopqrst01234567890"; 28 29 Random random = new Random(); 30 //1、用BufferedImage生成一张图片,最后一个参数是图片类型 31 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 32 33 //3、调用image的画图对象 34 Graphics graphics = image.getGraphics(); 35 graphics.setColor(Color.gray); 36 //左上角和右下角 37 graphics.fillRect(0, 0, width, height); 38 39 40 graphics.setColor(Color.black); 41 for (int i = 0; i < 4; i++) { 42 //4、随机生成字符串,取到随机的位置,就取到了随机的字符串 43 int position = random.nextInt(data.length()); 44 String randomStr = data.substring(position, position + 1);//分割字符串 45 graphics.drawString(randomStr, width / 5 * (i + 1), 15);//画字符串 46 47 } 48 49 //2、ImageIO的write()方法可以将图片转化为OutputStream类型 50 /** 51 * 第二个参数是要格式化的类型 52 * 最后一个参数是将格式化的图片写到response的输出流中 53 */ 54 ImageIO.write(image, "jpg", response.getOutputStream()); 55 56 57 } 58 }
verifyCode.html
要让按钮一直能点
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 9 </body> 10 <center> 11 <h2>切换验证码</h2> 12 <!--js代码--> 13 <script> 14 function changeImageCode() { 15 document.getElementById('btn').isDisabled=true; 16 <!-- 为了使每次的验证码都不一样,防止页面缓存,所以加上时间,ts是get方式请求传过去的参数,每次的请求都不一样,所以页面没法缓存--> 17 document.getElementById('identity').src='code?ts='+new Date().getTime(); 18 } 19 </script> 20 <!--从servlet的映射是code的servlet处获取图片--> 21 <image src="code" id="identity" onload="btn.disable=false;" style="cursor:pointer; vertical-align:middle"></image> 22 <input type="button" value="看不清,更换验证码" onclick="changeImageCode()" id="btn" style="vertical-align:middle"> 23 24 </center> 25 </html>