步骤一、先写好图片生成的工具类:
public final class ImageUtil {
private static final char[] chars = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
private static final int SIZE = 4;
private static final int LINES = 5;
private static final int WIDTH = 100;
private static final int HEIGHT = 45;
private static final int FONT_SIZE = 30;
/**
* 随机生成一个图片对象。
* 返回Map类型,key是图片中的文字,
* value是图片对象
*/
public static Map<String, BufferedImage> createImage() {
StringBuffer sb = new StringBuffer();
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.LIGHT_GRAY);
graphic.fillRect(0, 0, WIDTH, HEIGHT);
Random ran = new Random();
// 画随机字符
for (int i = 1; i <= SIZE; i++) {
int r = ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
graphic.drawString(chars[r] + "", (i - 1) * WIDTH / SIZE,
(HEIGHT-HEIGHT/3) );
sb.append(chars[r]);
}
// 画干扰线
for (int i = 1; i <= LINES; i++) {
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
map.put(sb.toString(), image);
return map;
}
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256), ran.nextInt(256),
ran.nextInt(256));
return color;
}
/**
* 将图片对象转换为输入流
* @param image 图片对象
* @return 输入流
* @throws IOException
*/
public static InputStream getInputStream(BufferedImage image)
throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
byte[] imageBts = bos.toByteArray();
InputStream in = new ByteArrayInputStream(imageBts);
return in;
}
}
步骤二、在Action中生成验证码:
/**
* 生成验证码
* @return
*/
public String createValidCode(){
//1调用组件生成图片和验证码
Map<String,BufferedImage> imageMap =
ImageUtil.createImage();
//2将验证码记录到Session,验证时要用
String imageCode =
imageMap.keySet().iterator().next();
session.setAttribute("imageCode", imageCode);
System.out.println("===========存入session中的code:"+imageCode);
//3将生成的图片转换成输入流,赋值给输出属性
BufferedImage image = imageMap.get(imageCode);
try {
imageStream = ImageUtil.getInputStream(image);
} catch (IOException e) {
e.printStackTrace();
return "error";
}
//4返回success,找到对应的result做输出
return "success";
}
/**
* 校验验证码是否正确
* @return
* @throws IOException
*/
public String checkValidCode() throws IOException{
System.out.println("页面输入框传过来的code:"+code);
validateCode=(String) session.getAttribute("imageCode");
//如果输入的跟生成的验证码相同,则通过
if(code.equalsIgnoreCase(validateCode)){
pass=true;
System.out.println(pass);
response.getWriter().write(pass+"");
return null;
}else{
pass=false;
System.out.println(pass);
response.getWriter().write(pass+"");
return null;
}
}
步骤三、配置struts.xml: <!-- 生成登录验证码的action --> <action name="validateCode" class="userAction" method="createValidCode"> <result name="success" type="stream"> <param name="inputName">imageStream</param> </result> </action> <!-- 用来验证的action --> <action name="checkValidateCode" class="userAction" method="checkValidCode"> </action> 步骤四、HTML和JS代码: <div class="ggg">验证码</div> <div class="gggt" style="width:280px;"> <input type="text" style="width:96%" class="yun yun2" name="validCode" id="input1" placeholder="必填" onFocus="if (this.placeholder == '必填') {this.placeholder = '';this.style.background='#EEEEEE';}" onBlur="if (this.placeholder == '') {this.placeholder = '必填';this.style.background='#FFFFFF';}"> </div> <br/> <div style="width:168px;height:45px; vertical-align:middle;margin:0 auto;clear:both;"> <img src="validateCode.do" alt="验证码" title="点击更换" onclick="change(this);"/> <span margin-top="14px" class="required" id="span1"></span> </div>
<script>
var pass=false;
$(function(){
$('#input1').blur(function(){
var code=$(this).val();
$.post(
'checkValidateCode.do',
{'code':code},
function(data){
if(data=="true"){
$('#span1').html("验证码正确").css('color','green');
pass=true;
}else{
$('#span1').html("验证码错误").css('color','red');
pass=false;
}
}
);
});
});
function change(imgObj){
imgObj.src="validateCode.do?date="+new Date().getTime();
}
</script>