此演示代码主要包括以下三部分:
1.checkCode.java:用于生成验证码
2.checkCodeServler
3.check.jsp 验证
下面是checkCode.java的内容:
//用于获取四位随机数
private char mapTable[] = {'0','1','2','3','4','5','6','7','8','9'};
//生成验证码,并返回随机生成的数字
public String getEnsure(int width, int height, OutputStream os){
if (width <= 0)
width = 60;
if (height <= 0)
height = 20;
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景色
g.setColor(new Color(0xDCCCCC));
g.fillRect(0, 0, width, height);
// 画边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 取随机产生的认证码
String strEnsure = "";
// 4代表4位验证码
for (int i = 0; i < 4; ++i){
strEnsure += mapTable[(int) (mapTable.length * Math.random())];
}
// 将认证码显示到图象中
g.setColor(Color.red);
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 14));
// 画的具体坐标
String str = strEnsure.substring(0, 1);
g.drawString(str, 8, 14);
str = strEnsure.substring(1, 2);
g.drawString(str, 20, 15);
str = strEnsure.substring(2, 3);
g.drawString(str, 35, 18);
str = strEnsure.substring(3, 4);
g.drawString(str, 45, 15);
// 释放图形上下文
g.dispose();
try{
// 输出图象到页面
ImageIO.write(image, "JPEG", os);
} catch (IOException e){
return "";
}
return strEnsure; //返回生成的随机数
}
再是checkCodeServlet的内容
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//禁用缓存,每次访问此页面,都重新生成
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
//生成验证码的实例对象
CheckCode ie = new CheckCode();
//调用里面的方法,返回的是生成的验证码中的字符串
String str = ie.getEnsure(0,0,response.getOutputStream());
//获得session,并把字符串保存在session中,为后面的对比做基础
HttpSession session = request.getSession();
session.setAttribute("strEnsure", str);
}
然后是web.xml对servlet的配置
<servlet>
<servlet-name>CheckServlet</servlet-name>
<servlet-class>com.blog.servlet.CheckServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckServlet</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
最后是jsp页面的引用
<html>
<head>
<title>验证码</title>
<script type="text/javascript" language="javascript">
//重新获取验证字符
function changeImage()
{
//单击触发图片重载事件,完成图片验证码的更换
document.getElementById("imgRandom").src = document.getElementById("imgRandom").src + '?';
}
</script>
</head>
<body>
<img alt= "看不清楚?点击更换验证码 " src= "check" width= "100" height= "50" id="imgRandom" onclick="changeImage()"/>
<a href="javascript:changeImage();">看不清?</a>
</body>
</html>
在jsp页面中,只需要将img的src的属性指向生成验证码的servlet就可以了,指向servle在web.xmlt映射的url。