验证码的作用:区分用户是计算机还是人;验证码有图片、拖拽、短信等各种形式,其中图片形式最为常见:
工具类:
public class VerifyCodeUtils {
/**
* 创建验证码
* @param width 图片宽度
* @param height 图片高度
* @param length 字符数
* @param fontName 字体名
* @return
*/
public static BufferedImage createValidate(int width, int height, int length, String fontName,
HttpServletRequest request) {
HttpSession session = request.getSession();
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
// 创建一个不带透明色的BufferedImage对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 产生Image对象的Graphics对象,该对象可以在图像上进行各种绘制操作
Graphics graphics = image.createGraphics();
graphics.fillRect(0, 0, width, height);// 图片大小
// 绘制边框
graphics.setColor(Color.LIGHT_GRAY);
graphics.drawRect(0, 0, width - 1, height - 1);
graphics.drawRect(1, 1, width - 2, height - 2);
// 生成指定长度的[a-z]的随机字符串, 包含大小写
String str = RandomStringUtils.randomAlphabetic(length);
char[] chs = str.toCharArray(