日期:2014-05-17  浏览次数:20767 次

在线等。jquery 验证码 同步验证局部刷新....附代码了................
java类代码
package com.iCloud.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.Random;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageCodeAction extends BaseAction{

private InputStream is;
private Map<String, Object> session;
@Override
public String execute()  {
try {
byte[] bs = generator();
is = new ByteArrayInputStream(bs);
} catch (Exception e) {
e.printStackTrace();
}
return super.execute();
}

private static int WIDTH = 200;

private static int HEIGHT = 80;

private static int NUM = 5;

private static char[] seq = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };

/**
 * 生成随机的验证码
 * 
 * @return
 * @throws Exception
 */
private byte[] generator() throws Exception {
Random r = new Random();

// 图片的内存映像
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);

// 获得画笔对象
Graphics g = image.getGraphics();
g.setColor(randomColor(r));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(new Color(0, 0, 0));

// 用于存储随机生成的验证码
StringBuffer number = new StringBuffer();

// 绘制验证码
for (int i = 0; i < NUM; i++) {
g.setColor(randomColor(r));
int h = (int) ((HEIGHT * 60 / 100) * r.nextDouble() + (HEIGHT * 30 / 100));
g.setFont(new Font(null, Font.BOLD | Font.ITALIC, h));
String ch = String.valueOf(seq[r.nextInt(seq.length)]);
number.append(ch);
g.drawString(ch, i * WIDTH / NUM * 90 / 100, h);
}

session.put("rand",number.toString()); //保存session
System.out.println("++++++++++++生成码:"+number.toString()); //打印值

// 绘制干扰线
for (int i = 0; i <= 12; i++) {
g.setColor(randomColor(r));
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r
.nextInt(HEIGHT));

}

// 压缩成jpeg格式
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);

// 把BufferedImage对象中的图像信息编码后
// 向创建该对象(encoder)时指定的输出流输出
encoder.encode(image);

r