Servlet生成验证码在JSP页面显示,单击验证码图片可刷新

时间:2020-12-05 17:08:22

在ImageRandeCode这个servlet里面代码如下:

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);
//生成验证码的实例对象
//调用里面的方法,返回的是生成的验证码中的字符串
String str = this.getEnsure(0,0,response.getOutputStream());
//获得session,并把字符串保存在session中,为后面的对比做基础
HttpSession session = request.getSession();
session.setAttribute("randomCode", str);
}

//用于获取四位随机数
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 = 50;
if (height <= 0)
height = 15;
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, 10));
// 画的具体坐标
String str = strEnsure.substring(0, 1);
g.drawString(str, 3, 10);
str = strEnsure.substring(1, 2);
g.drawString(str, 15, 10);
str = strEnsure.substring(2, 3);
g.drawString(str, 27, 10);
str = strEnsure.substring(3, 4);
g.drawString(str, 39, 10);
// 释放图形上下文
g.dispose();
try{
// 输出图象到页面
ImageIO.write(image, "JPEG", os);
} catch (IOException e){
return "";
}
return strEnsure; //返回生成的随机数
}

继续编辑JS部分,用来实现单击图片改变验

function changeImage()
{

//单击触发图片重载事件,完成图片验证码的更换
document.getElementByIdx_x("imgRandom").src = document.getElementByIdx_x("imgRandom").src + '?';
}

在JSP页面引用ImageRandeCode显示验证码图片和输入如下:

<tr>
<td width="31%" height="35" class="login-text02">验证码:<br /></td>
<td width="69%">
<input name="yzm" type="text" size="12" id="yzm"/>
<img src="ImageRandeCode" title="看不清,请点击图片刷新" width="100" height="20" id="imgRandom" onclick="changeImage()"/>
</td>
</tr>

ImageRandeCode这个servlet在web.xml配置如下:

<servlet>
<servlet-name>ImageRandeCode</servlet-name>
<servlet-class>com.myhair.Servlet.ImageRandeCode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageRandeCode</servlet-name>
<url-pattern>/ImageRandeCode</url-pattern>
</servlet-mapping>