验证码功能经常应用到网站中,放到此处便于查阅。
核心代码如下,如需全部代码请查看附件。
1、java生成验证码代码如下:(此代码也可放到servlet中)
2、action引用验证码
核心代码如下,如需全部代码请查看附件。
1、java生成验证码代码如下:(此代码也可放到servlet中)
public class ImageUtil {
private static String[] chars = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
private static final int WIDTH = 200;
private static final int HEIGHT = 100;
private static final int NUM = 4;
private static final int LINE = 10;
/**
* 生成随机图
*
* @return string 随机字符 image随机图片
*/
public static Map getImage() {
Map map = new HashMap();
String s = "";
// 创建�?个BufferedImage
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
Random ran = new Random();
// 画背景色
graphics.setColor(new Color(ran.nextInt(100), ran.nextInt(100), ran
.nextInt(100)));
graphics.fillRect(0, 0, WIDTH, HEIGHT);
// 画随机字�?
for (int i = 0; i < NUM; i++) {
graphics.setColor(new Color(ran.nextInt(20)+200, ran.nextInt(20)+200, ran
.nextInt(200)+20));
graphics.setFont(new Font(null, Font.BOLD, ran.nextInt(10) + 80));
String ranstr = chars[ran.nextInt(chars.length)];
graphics.drawString(ranstr, WIDTH / NUM * (i), HEIGHT / 4 * 3);
s += ranstr;
}
// 画干扰线
for (int j = 0; j < LINE; j++) {
graphics.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran
.nextInt(255)));
graphics.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran
.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
map.put("code", s);
map.put("image", image);
return map;
}
/**
* 将随机图片转换成inputStream
*/
public static InputStream getInputStream(BufferedImage image)
throws IOException {
// 将BufferedImage转换成符合JPEG格式字节数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(bos);
encode.encode(image);
// 将图片的字节数组信息,封装成InputStream
byte[] byteArr = bos.toByteArray();
return new ByteArrayInputStream(byteArr);
}
}
2、action引用验证码
public class ImageCodeAction {
private InputStream imageStream;
public String execute() {
Map map = ImageUtil.getImage();
//存放在session中便于用户输入后进行验证 此处略去
//getSession().put(Constants.SESSION_CODE, map.get("code"));
try {
imageStream = ImageUtil.getInputStream((BufferedImage) map
.get("image"));
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
public InputStream getImageStream() {
return imageStream;
}
public void setImageStream(InputStream imageStream) {
this.imageStream = imageStream;
}
}