jcaptcha是一个开源的用来生成图形验证码的Java开源组件,使用起来也是非常的简单方便。
1.jsp部分
<body>
<h2>Simple Captcha Servlet sample</h2>
<form action="submit.action" method="post">
<img src="jcaptcha.jpg" /> <input type="text" name="japtcha" value="" />
<input type="submit"/>
</form>
</body>
2.Servlet部分
先导入jcaptcha-2.0-alpha-1-SNAPSHOT.jar
jcaptcha-api-1.0.jar
jcaptcha-integration-simple-servlet-2.0-alpha-1-SNAPSHOT.jar
这三个包
下载地址:上传的资源暂时未审核通过,通过后放上来,也可百度搜索下载,一样的。
package com.octo.captcha.module.servlet.image.sample;
import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SubmitActionServlet extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String userCaptchaResponse = request.getParameter("japtcha");
boolean captchaPassed = SimpleImageCaptchaServlet.validateResponse(request, userCaptchaResponse);
if (captchaPassed)
response.getWriter().write("captcha passed");
else {
response.getWriter().write("captcha failed");
}
response.getWriter().write("<br/><a href='index.jsp'>Try again</a>");
}
}
3. web.xml部分
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Simple Image Captcha Servlet Sample</display-name>
<servlet>
<servlet-name>jcaptcha</servlet-name>
<servlet-class>com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>submit</servlet-name>
<servlet-class>com.octo.captcha.module.servlet.image.sample.SubmitActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jcaptcha</servlet-name>
<url-pattern>/jcaptcha.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>submit</servlet-name>
<url-pattern>/submit.action</url-pattern>
</servlet-mapping>
</web-app>
总结:
开源组件很好用,方便快捷,节省了开发时间,但是还是要把每一步都试一下,才能更详细的了解每一个功能怎么用。