页面端的代码:(checkNum.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'checkNum.jsp' starting page</title>
</head>
<!-- 获得验证码的代码,与ajax无关-->
<body>
<script language="javascript">
function chk_image(){
var img = document.getElementById("validationpwd");
img.src = "validateCodeServlet?" + Math.random();
}
</script>
<li><SPAN style="DISPLAY: inline-block" class=chs><FONT color=red>*</FONT>验证码:</SPAN></li>
<A title=点击重新获取图片><img id="validationpwd" style="BORDER-BOTTOM-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-TOP-STYLE: none; BORDER-LEFT-STYLE: none"src='/validateCodeServlet?,Math.random();' οnclick="return chk_image();" style='border : none;'/></a>
<input id="validatecontent" name="validatecontent" type="text" value="" style="width:50px" /><a style="color: blue" οnclick="chk_image()">点击重新获得验证码</a>
<span id="error_validatecontent_1" style="display: none" class="red" ><img src="/images/no.png" />验证码不能为空!</span>
<span id="ok_validatecontent" style="display: none" class="grn" ><img src="/images/yes.png" />
</span>
<font color="red"><%=(request.getAttribute("registervalidaterror")!=null)?("<img src=/"/images/no.png/"/>"+request.getAttribute("registervalidaterror")):"" %></font>
</body>
</html>
sevlet端的代码:(ValidateCodeServlet.java)
package servlet;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ValidateCodeServlet extends HttpServlet {
private int x = 0;
private int fontHeight;
private int codeY;
private int width = 60;
private int height = 20;
private int codeNum = 5;
char[] codes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', };
public void init() throws ServletException {
String strCodeNums = this.getInitParameter("codeNum");
String strW = this.getInitParameter("w");
String strH = this.getInitParameter("h");
try {
if (strH != null && strH.length() != 0) {
height = Integer.parseInt(strH);
}
if (strW != null && strW.length() != 0) {
width = Integer.parseInt(strW);
}
if (strCodeNums != null && strCodeNums.length() != 0) {
codeNum = Integer.parseInt(strCodeNums);
}
} catch (NumberFormatException e) {
}
x = width / (codeNum + 1);
fontHeight = height - 2;
codeY = height - 4;
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
Random random = new Random();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
g.setFont(font);
g.drawRect(0, 0, width - 1, height - 1);
for (int i = 0; i < 222; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
for (int i = 0; i < codeNum; i++) {
String strRand = String.valueOf(codes[random.nextInt(codes.length)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i + 1) * x, codeY);
randomCode.append(strRand);
}
HttpSession session = req.getSession();
session.setAttribute("validate", randomCode.toString());
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
resp.setContentType("image/jpeg");
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
web.xml里的代码:
<servlet>
<servlet-name>ValidateCodeServlet</servlet-name>
<servlet-class>servlet.ValidateCodeServlet</servlet-class>
<init-param>
<param-name>width</param-name>
<param-value>160</param-value>
</init-param>
<init-param>
<param-name>height</param-name>
<param-value>68</param-value>
</init-param>
<init-param>
<param-name>codeCount</param-name>
<param-value>5</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ValidateCodeServlet</servlet-name>
<url-pattern>/validateCodeServlet</url-pattern>
</servlet-mapping>