Servlet方法:
public class ValidateCodeServlet extends BaseServlet {
private static final String CONTENT_TYPE = "image/jpeg";
/**
* 数字图像认证系统 随机产生一个四位的数组,转换成图象输出 产生的数组保存在Session中,绑定名字“rand”
*
* @param super.getRequest()
* @param super.getResponse()
*/
public void createImage(HttpServletRequest request,
HttpServletResponse response)
{
response.setContentType(CONTENT_TYPE);
response.setHeader("Pragma","No-cache"); // 设置页面不缓存
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
try {
request.setCharacterEncoding("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpSession session = request.getSession();
// 产生四位随机码,写入session
//String chose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//去掉容易混淆的字母:0,1,o,I,l,O
String chose = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
char display[] = { '0', ' ', '0', ' ', '0', ' ', '0' }, ran[] = { '0', '0', '0', '0' }, temp;
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
temp = chose.charAt(rand.nextInt(chose.length()));
display[i * 2] = temp;
ran[i] = temp;
}
String strRandom = String.valueOf(display); // 与String.valueOf(ran)是相同地
String sRand = request.getParameter("rand"); // 通过传递参数来设置验证码在session里的名字
if (sRand == null)
{
sRand = "rand";
}
session.setAttribute(sRand,String.valueOf(ran));
// 生成图像,返回到页页上
int width = 70, height = 26;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 以下填充背景颜色
g.setColor(Color.white);
g.setColor(getRandomColor(200,250));
// 设置边框
g.fillRect(0,0,width,height);
// 设置字体颜色、字体
g.setColor(Color.black);
g.drawRect(0,0,width - 1,height - 1); // 字要比图像边框小一点
// 将认证码写入图像
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.PLAIN, 18));
g.drawString(strRandom,1,18);
// 图像生效
g.dispose();
// 输出图像
try
{
ImageIO.write(image,"JPEG",response.getOutputStream());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* 生成随机颜色
*
* @param fc
* 前景色
* @param bc
* 背景色
*
* @return Color对象,此Color对象是RGB形式的。
*/
public Color getRandomColor(int fc, int bc)
{
Random random = new Random();
if (fc > 255)
{
fc = 200;
}
if (bc > 255)
{
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
页面:
<script type="text/javascript">
jQuery(function(){
jQuery('#urMobile').focus();
//为验证码图片绑定单击事件
jQuery("#imagepic").click(function(){
this.src="<%=path%>/ValidateCodeServlet.do?method=createImage×tamp="+Math.random();
});
});
</script>
<tr>
<td align="right" height="40">
验证码:
</td>
<td align="left">
<input type="text" size="7" name="code" id="code"/>
<img src="<%=path%>/ValidateCodeServlet.do?method=createImage" id="imagepic"
width="75" height="24" maxlength="4" title="点击图片,更换验证码"/>
</td>
</tr>
效果图: