日期:2014-05-16  浏览次数:21020 次

使用Ajax进行验证码的刷新

利用Ajax实现验证码的刷新

废话不多说,大部分网站都有设置验证码防止恶意攻击。现在用最简单的实现进行我们的验证码刷新。
注册页面:login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 
  <script src="../js/check_login.js" type="text/javascript"></script><!--这里的路径要这样设置  -->
    <base href="<%=basePath%>">
   
    <title>欢迎登陆</title>
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- 这里会需要引入外部的CSS文件,路径如下 -->
<link rel="stylesheet" type="text/css" href="CSS/style.css">


  </head>
  <style type="text/css">
 
 
 
  </style>
  <body>
 
  <div id="main">
  <form method="post" action="user/checkUserLogin.jsp">
   <table align="left">
   <tr>
   <td>用户名:</td>
   <td><input type="text" name="username" id="username" onchange="return check_username() == true;"></td>
   <td></td>
   <td><div id="display_username" class="display"></div></td>
   </tr>
   <tr>
   <td>密&nbsp;&nbsp;码:</td>
   <td><input type="password" name="password" id="password" onchange="return check_password() == true"></td>
   <td></td>
   <td><div id="display_password" class="display"></div></td>
   </tr>
   <tr>
   <td>验证码:</td>
   <td><input type="text" name="certCode" maxlength="4" id="certCode" onchange="return check_certCode()==true;"></td>
   <td><img src="makeCertPic.jsp" id="img" title="refresh" name="img">
   <a href="JavaScript:reLoadImg();">换一张</a></td>
   <td><div id="display_certCode" class="display"></div></td>
   </tr>
   <tr><td></td><td></td>
   <td><font size="4"><input type="submit" value="登陆"></font></td></tr>
   </table>
    </form>
    </div>
  </body>
</html>
生成验证码图片:makeCertPic.jsp
<%@page contentType="image/jpeg" %>
<jsp:useBean id="image" scope="page" class="util.makeCertPic" />
<%
String str = image.getCertPic(0,0,response.getOutputStream());
session.setAttribute("certCode", str);
out.clear();//该行及下一行代码可以解决respons.getOutputStream() has already been called 的问题
out = pageContext.pushBody();

%>
生成验证码的类:makeCertPic.java
package util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
im