一、关于验证码
首先来说,验证码在我们的日常登录,发表言论时比较常见,它是一种用来区分登录用户是人还是机器的一种公共自动程序。它可以防止恶意破解密码、刷票、论坛灌水。
二、用java来实现验证码
了解了验证码的作用,接下来我们就用java来实现验证码这一功能。首先我们先分析一下,怎么生成一个验证码。我们需要一个BufferedImage对象来保存图片;通过它来获得Graphics对象;通过Randrom产生随机验证码信息;使用Graphics绘制图片;记录验证码信息到session中;使用ImageIO输出图片;
1 package com.water.servlet; 2 3 import com.sun.javafx.font.FontStrike; 4 5 import javax.imageio.ImageIO; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import java.awt.*; 11 import java.awt.image.BufferedImage; 12 import java.io.IOException; 13 import java.util.Random; 14 15 public class ImgServlet extends HttpServlet { 16 @Override 17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB); 19 Graphics graphics = bi.getGraphics(); 20 Color color = new Color(200, 150, 255); 21 graphics.setColor(color); 22 graphics.fillRect(0,0,68,32); 23 char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); 24 StringBuffer sb = new StringBuffer(); 25 Random random = new Random(); 26 for (int i = 0; i < 4; i++) { 27 char aChar = chars[random.nextInt(36)]; 28 graphics.setColor(new Color(random.nextInt(88),random.nextInt(188),random.nextInt(255))); 29 graphics.drawString(aChar+"",(i*15)+3,18); 30 sb.append(aChar); 31 } 32 req.getSession().setAttribute("charCode",sb.toString()); 33 ImageIO.write(bi,"jpg",resp.getOutputStream()); 34 35 } 36 }