在java后台中生成验证码的ImageIO传到前端页面显示,同时把验证码的value值传入session 中用于与用户输入的验证码进行匹配,在用户验证中使用ajax技术,在不刷新页面的同时进行验证码验证。
程序结构图:
VerifyCodeUtils程序主要内容为通过java生成验证码的图片,以及验证码的value值,程序如下:
package utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class VerifyCodeUtils {
private static BufferedImage image = null;
private static Random random = new Random();
//在自己定义的一些数中,生成4位随机数
public static String getVerifyCode() {
String str = "";
char[] code = new char[]{
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U',
'V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t',
'u','v','w','x','y','z','2','3','4','5','6','7','8','9'};
Random random = new Random();
for(int i = 0; i < 4; i++) {
str += String.valueOf(code[random.nextInt(code.length)]);
}
return str;
}
//生成验证码图像
public static Map getVerifyCode(int width, int heigth) {
VerifyCodeUtils.image = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) VerifyCodeUtils.image.getGraphics();
String verifyCode = getVerifyCode();
Map map = new HashMap();
map.put("verifyCode", verifyCode);
//将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, heigth);
//设置字体
g.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, heigth-10));
//画边框。
g.setColor(VerifyCodeUtils.getColor());
g.drawRect(0, 0, width, heigth);
//随机产生干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(Color.BLACK);
for (