1. 需要的jar包: patchca.jar: http://code.google.com/p/patchca/
patchca使用LGPL协议: GNU Lesser General Public License
2. 请求验证码的 JSP: validate.jsp
3. 产生验证码的 Servlet: ValidationCode.java
4. 验证验证码的 Servlet: ValidateCode.java
验证过程: validate.jsp请求验证码 -> ValidationCode.java生成验证码图片和相应的字符给validate.jsp -> 用户输入验证码 -> ValidateCode.java验证用户的验证码是否输入正确.
================================== validate.jsp ==================================
<%@page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtml PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<imgsrc="ValidationCode">
<formaction="ValidateCode"method="post">
<inputtype="text"name="validateCode"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
================================== ValidateCode.java ==================================
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Validate
*/
publicclass ValidateCode extends HttpServlet {
private staticfinal long serialVersionUID = 1L;
public ValidateCode() {
super();
}
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,
IOException {
String validateCode = request.getParameter("validateCode");
HttpSession session = request.getSession();
// 从session中取得验证码与用户输入的验证码进行比较
String storedValidateCode = (String) session.getAttribute(session.getId());
response.setHeader("Content-type","text/html; charset=UTF-8");
if (validateCode.equalsIgnoreCase(storedValidateCode)) {
response.getWriter().println("验证码输入正确: " + validateCode);
} else {
response.getWriter().println("验证码输入错误: " + validateCode);
}
}
@Override
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,
IOException {
doGet(request, response);
}
}
================================== ValidationCode.java ==================================
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.patchca.color.GradientColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.filter.predefined.DiffuseRippleFilterFactory;
import org.patchca.filter.predefined.DoubleRippleFilterFactory;
import org.patchca.filter.predefined.MarbleRippleFilterFactory;
import org.patchca.filter.predefined.RippleFilterFactory;
import org.patchca.filter.predefined.WobbleRippleFilterFactory;
import org.patchca.service.Captcha;
import org.patchca.service.ConfigurableCaptchaService;
/**
* Servlet implementation class ValidateCode
*/
publicclass ValidationCode extends HttpServlet {
private staticfinal long serialVersionUID = 1L;
public ValidationCode() {
super();
}
// 关键之处,产生图片
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,
IOException {
response.setContentType("image/png");
ValidateEntry ve = new ValidateEntry();
HttpSession session = request.getSession();
session.setAttribute(session.getId(), ve.getCode());// 验证码保存在session中
ServletOutputStream out = response.getOutputStream();
BufferedImage img = ve.getImage();
ImageIO.write(img, "png", out);
out.close();
}
@Override
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,
IOException {
doGet(request, response);
}
protectedclass ValidateEntry {
String code;
BufferedImage image;
ValidateEntry() {
createEntry();
}
public String getCode() {
return code;
}
public BufferedImage getImage() {
return image;
}
private void createEntry() {
ConfigurableCaptchaService cs =new ConfigurableCaptchaService();
cs.setColorFactory(new GradientColorFactory());
switch ((int) (System.currentTimeMillis() % 6)) {
case 0:
cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
break;
case 1:
cs.setFilterFactory(new MarbleRippleFilterFactory());
break;
case 2:
cs.setFilterFactory(new DoubleRippleFilterFactory());
break;
case 3:
cs.setFilterFactory(new WobbleRippleFilterFactory());
break;
case 4:
cs.setFilterFactory(new DiffuseRippleFilterFactory());
break;
case 5:
cs.setFilterFactory(new RippleFilterFactory());
break;
}
Captcha captcha = cs.getCaptcha();
code = captcha.getChallenge();
image = captcha.getImage();
}
}
}
-------------------------------------------------------以上为网上找的资料-------------------------------------------------------
-------------------------------------------------------以下为本人的测试---------------------------------------------------------
public void LoadCodeImg() throws IOException { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); int width = 75, height = 25; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(GetCodeImg.getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 24)); g.setColor(GetCodeImg.getRandColor(160, 200)); for (int i = 0; i < 155; 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); } String sRand = ""; for (int i = 0; i < 4; i++) { // String rand = String.valueOf(random.nextInt(10)); String rand = randomString(1); sRand += rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 15 * i + 6, 20); } session.put("numrand", sRand);//这里是将验证码放在session中,做验证的时候从这里取出来跟用户的输入做比较 g.dispose(); ImageIO.write(image, "JPEG", response.getOutputStream()); }