图片验证码可以通过img标签的src请求一个servlet生成。
Jsp页面代码片段:
<tr>
<td>验证码</td>
<td>
<input type="text" name="verifyCode" style="width: 60px;"/>
<img onclick="changeUrl(this)" style="cursor: pointer;" src="${pageContext.request.contextPath}/client/verifyCodeServlet" />
</td>
</tr>
点击切换图片的js脚本:
<script type="text/javascript">
function changeUrl(obj){
obj.src = "${pageContext.request.contextPath}/client/verifyCodeServlet?t=" + new Date();
}
</script>
生成图片的servlet代码:
//生成随机验证码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//准备数据
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
//准备随机函数
Random random = new Random();
int width = 60;
int height = 30;
//图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//画板
Graphics g = image.getGraphics();
//设置画笔颜色
g.setColor(Color.BLACK);
//填充矩形
g.fillRect(0, 0, width, height);
g.setColor(Color.WHITE);
g.fillRect(1, 1, width-2, height-2);
//设置字体
g.setFont(new Font("宋体",Font.BOLD,20));
//提供缓冲4个随机字符串
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 4; i++) {
//设置随机颜色
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
//获得一个随机字符
int index = random.nextInt(data.length());
String str = data.substring(index, index + 1);
//缓冲随机字符串
builder.append(str);
//绘制到画板
g.drawString(str, width/6*(i+1), 20);
}
//将缓存的数据存到session中
String bufferData = builder.toString();
request.getSession().setAttribute("sessionVerifyCodeData", bufferData);
//添加干扰线、点
for(int i = 0 ; i < 5 ; i ++){
g.setColor(new Color(random.nextInt(255),random.nextInt(255), random.nextInt(255)));
g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
//将服务器内存中的数据发送到浏览器
ImageIO.write(image, "jpg", response.getOutputStream());
}
验证提交的图片验证码的servlet的代码:
//或得用户填写的验证码
String verifyCode = request.getParameter("verifyCode");
//或得session中的验证码
String sessionVerifyCodeData = (String) request.getSession().getAttribute("sessionVerifyCodeData");
//判断服务器是否有数据
if(sessionVerifyCodeData != null){
// 将session中缓存的数据移除,保证一次性
request.getSession().removeAttribute("sessionVerifyCodeData");
if(! sessionVerifyCodeData.equalsIgnoreCase(verifyCode)){
//不匹配
request.setAttribute("message", "验证码有误,请重写填写");
request.getRequestDispatcher("/client/register.jsp").forward(request, response);
return;
}
}else{
// 重复提交
request.setAttribute("message", "不要重复提交");
request.getRequestDispatcher("/client/register.jsp").forward(request, response);
return;
}
页面效果: