1 验证码的作用
验证码是为了区分人与机器,如果没有验证码机制,web网站或者应用会遇到很多问题,具体如下:
① 网站容易被暴力登录攻破密码,可以制作一个自动程序不断的尝试登录,密码很容易被破解,系统容易瘫痪;
② 黑客可以创建自动程序不断的注册账户,不断的发帖,不断的刷票,消耗服务器资源,产生大量垃圾信息;
验证码分为两部分:图片与输入框
<html><br/> <image src=‘images/logo1.jpg‘ /><hr/> <head><br/><title>登录</title> <br/><h1> 欢迎登录</h1></head> <br/> <body> <br/> <form action=‘/LoginValid/LoginVerify‘ method=‘post‘ > 用户id:<input type=‘text‘ name=‘userid‘ value=‘‘> <br/> 用户密码:<input type=‘password‘ name=‘password‘ value=‘‘> <br/> <br/> 验证码:<input type=‘text‘ name=‘inputCode‘ value=‘‘ /> <img src=‘/LoginValid/CreateCode2‘ /><br/> <input type=‘submit‘ value=‘登录‘ /><br/> </form> </body> <br/> </html>
CreateCode实时生成图片
1 private static final int IMG_W=82; 2 private static final int IMG_H=25; 3 private static final int NUM_CHS=5; 4 private static char[] chs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890".toCharArray(); 5 private static Random rand = new Random(); 6 7 public void doGet(HttpServletRequest request, HttpServletResponse response) 8 throws ServletException, IOException { 9 10 //禁止浏览器缓存随机图片 11 response.setDateHeader("Expires",-1); 12 response.setHeader("Cache-Control", "no-cache"); 13 response.setHeader("Pragma", "no-cache"); 14 15 //通知客户端以图片的方式打开发送过去的数据 16 response.setHeader("Content-Type", "image/jpeg"); 17 18 //创建image对象 19 BufferedImage image = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_RGB); 20 Graphics g = image.getGraphics(); 21 22 //验证码图片背景颜色 23 Color co = new Color(200,200,255); 24 g.setColor(co); 25 26 g.fillRect(0, 0, IMG_W, IMG_H); 27 //保存验证码字符 28 StringBuilder sb = new StringBuilder(); 29 int index=0; 30 for(int i=0; i<NUM_CHS; i++) 31 { 32 //获取随机一个下标 33 index = rand.nextInt(chs.length); 34 //给画笔随机一个颜色 35 g.setColor(new Color(rand.nextInt(88),rand.nextInt(210),rand.nextInt(150))); 36 //画出字符 37 g.drawString(chs[index]+"", 15*i+3, 18); 38 sb.append(chs[index]); 39 } 40 41 //将验证码保存至session 42 request.getSession().setAttribute("checkCode", sb.toString()); 43 ImageIO.write(image, "jpg", response.getOutputStream()); 44 }
验证用户输入的验证码与session里保存的是否一致:
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 4 response.setContentType("text/html;charset=utf-8"); 5 request.setCharacterEncoding("utf-8"); 6 PrintWriter out = response.getWriter(); 7 8 HttpSession session = request.getSession(); 9 String seCode = (String)session.getAttribute("checkCode"); 10 String inputCode = (String)request.getParameter("inputCode"); 11 if(seCode.equals(inputCode)) 12 { 13 request.getRequestDispatcher("/Main").forward(request, response); 14 } 15 else 16 { 17 request.getRequestDispatcher("/Err").forward(request, response); 18 } 19 20 }