******************************servlet***************************
BufferedImage image = CheckCodeUtil.getImage();
String checkCodeString = CheckCodeUtil.getCodeString();
req.getSession().setAttribute("code", checkCodeString);
//设置响应类型
resp.setContentType("image/jpeg");
//输出图片
ImageIO.write(image, "jpeg", resp.getOutputStream());
**************************jsp************************
<script type="text/javascript">
function reload(){
var img = document.getElementById("img");
img.src = "code?id=" + new Date();
}
</script>
<body>
<font color="red">${error}</font>
<form action="check">
验证码:<input type="text" name="code"/>
<img src="code" onclick="this.src='code?r='+Math.random()" id="img"/>
<a href="javascript:reload()">看不清,换一张</a><br/>
<input type="submit" value="提交"/>
</form>
</body>
********************************生成验证码的工具类***********************
package com.chinasoft.checkcode.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CheckCodeUtil {
private static String code = null;
public static String getCodeString(){
return code;
}
private static Font getFont(){
Random r = new Random();
Font[] f = new Font[5];
f[0] = new Font("微软雅黑",Font.PLAIN,20);
f[1] = new Font("Antique Olive Compact",Font.PLAIN,20);
f[2] = new Font("Forte",Font.PLAIN,20);
f[3] = new Font("Wide Latin",Font.PLAIN,20);
f[4] = new Font("Gill Sans Ultra Bold",Font.PLAIN,20);
return f[r.nextInt(f.length)];
}
public static BufferedImage getImage(){
code = "";
Random r = new Random();
//创建画板
BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
//创建一支笔
Graphics g = image.getGraphics();
//为笔设置颜色,即画板的背景色,值越大颜色越浅
g.setColor(new Color(180,208,255));
//创建一张画纸,位置,宽度,长度
g.fillRect(0, 0, 100, 30);
String random = "QWERTYUPLKJHGFDSAZXCVBNM98765432";
for (int i = 0; i < 4; i++) {
//设置字体
g.setFont(getFont());
//为画的字符设置颜色
g.setColor(new Color(r.nextInt(100),r.nextInt(100),r.nextInt(100)));
char c = random.charAt(r.nextInt(random.length()));
g.drawString(c+"", i*20+8, 25);
code += c;
}
//画干扰线
for (int i = 0; i < 4; i++) {
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
}
//画干扰点
for (int i = 0; i < 20; i++) {
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.drawOval(r.nextInt(100), r.nextInt(30),3, 3);
}
return image;
}
}