最近学习了一下验证码实现,学习了一下jcaptcha开源验证技术,网上搜索了一下资料,学习整理了一下
1.需要的JAR
commons-collections-3.1.jar,commons-collections-3.1.jar
Java代码
package com.code;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;
/***********************************************************************
*
* CaptchaServiceSingleton.java
* @copyright Copyright: 2009-2012
* @creator 周辉<br/>
* @create-time Jun 18, 2009 1:31:44 PM
* @revision $Id: *
***********************************************************************/
public class CaptchaServiceSingleton {
private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
public static ImageCaptchaService getInstance(){
return instance;
}
}
编写一个产生图片的servlet
package com.code;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/***********************************************************************
*
* ImageCaptchaServlet.java
* @copyright Copyright: 2009-2012
* @creator 周辉<br/>
* @create-time Jun 18, 2009 1:32:50 PM
* @revision $Id: *
***********************************************************************/
public class ImageCaptchaServlet extends HttpServlet {
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
}
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
byte[] captchaChallengeAsJpeg = null;
// the output stream to render the captcha image as jpeg into
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// get the session id that will identify the generated captcha.
//the same id must be used to validate the response, the session id is a good candidate!
String captchaId = httpServletRequest.getSession().getId();
// call the ImageCaptchaService getChallenge method
BufferedImage challenge =
CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,
httpServletRequest.getLocale());
// a jpeg encoder
JPEGImageEncoder jpegEncoder =
JPEGCodec.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} catch (CaptchaServiceException e) {
httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
// flush it in the response
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream =
httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
为servlet修改web.xml配置文件
<servlet>
<servlet-name>jcaptcha</servlet-name>
<servlet-class>com.code.ImageCaptchaServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jcaptcha</servlet-name>
<url-pattern>/jcaptcha</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>checkjcaptcha</servlet-name>
<servlet-class>com.code.ValidationServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>checkjcaptcha</servlet-name>
<url-pattern>/validateAction</url-pattern>
</servlet-mapping>
其中jcaptcha 是生成图片的Servlet
checkjcaptcha是验证用的Servlet
编写你的客户端的展示
login.html
<html>
<head>
<title>MyHtml.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<form name="f1" id="f1" action="/jcaptcha/validateAction" method="get">
<table border="0">
<tr>
<td>验证码:</td>
<td><img src="jcaptcha"><input type='text' name='j_captcha_response' value=''></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
2 个检验成功失败的页面success.html ,failture.html 这2个页面超级简单这里略
后台逻辑验证
package com.code;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.octo.captcha.service.CaptchaServiceException;
/***********************************************************************
*
* ValidationServlet.java
* @copyright Copyright: 2009-2012
* @creator 周辉<br/>
* @create-time Jun 18, 2009 1:36:02 PM
* @revision $Id: *
***********************************************************************/
public class ValidationServlet extends HttpServlet {
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
}
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException {
Boolean isResponseCorrect = Boolean.FALSE;
//remenber that we need an id to validate!
String captchaId = httpServletRequest.getSession().getId();
//retrieve the response
String response = httpServletRequest.getParameter("j_captcha_response");
// Call the Service method
try {
isResponseCorrect = CaptchaServiceSingleton.getInstance()
.validateResponseForID(captchaId, response);
} catch (CaptchaServiceException e) {
//should not happen, may be thrown if the id is not valid
}
System.out.println(isResponseCorrect);
// httpServletResponse.encodeUrl("sucess.html");
if(isResponseCorrect.booleanValue()){
httpServletResponse.sendRedirect("success.html");
}
else {
httpServletResponse.sendRedirect("failture.html");
}
}
}
最后发布程序 启动TOMCAT
运行http://localhost:8081/jcaptcha/login.html运行看到了吧(我的TOMCAT 端口是8081,默认是8080)