First need to download JAR file for JCaptcha from
You also need common apache library.
Now create a Web Applications in NetBeans or Eclipse and add the jars to your application classpath.
Now need to create Other classes:
CaptchaServiceSingleton.java
package com.ss; import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore; import com.octo.captcha.service.image.ImageCaptchaService; import com.octo.captcha.service.image.DefaultManageableImageCaptchaService; public class CaptchaServiceSingleton { private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService( new FastHashMapCaptchaStore(),new MyCaptchaEngine(),180,100000,75000); public static ImageCaptchaService getInstance() { return instance; } }
And MyCaptchaEngine.java
package com.ss; import java.awt.Font; import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator; import com.octo.captcha.component.image.backgroundgenerator.FunkyBackgroundGenerator; import com.octo.captcha.component.image.color.RandomRangeColorGenerator; import com.octo.captcha.component.image.fontgenerator.FontGenerator; import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator; import com.octo.captcha.component.image.textpaster.RandomTextPaster; import com.octo.captcha.component.image.textpaster.TextPaster; import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage; import com.octo.captcha.component.image.wordtoimage.WordToImage; import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator; import com.octo.captcha.component.word.wordgenerator.WordGenerator; import com.octo.captcha.engine.image.ListImageCaptchaEngine; import com.octo.captcha.image.gimpy.GimpyFactory; public class MyCaptchaEngine extends ListImageCaptchaEngine { protected void buildInitialFactories() { WordGenerator wgen = new RandomWordGenerator( "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789"); RandomRangeColorGenerator cgen = new RandomRangeColorGenerator( new int[] { 0, 100 },new int[] { 0, 100 },new int[] { 0, 100 }); TextPaster textPaster = new RandomTextPaster(new Integer(4), new Integer(6), cgen, true); BackgroundGenerator backgroundGenerator = new FunkyBackgroundGenerator( new Integer(200), new Integer(100)); /** * BackgroundGenerator backgroundGenerator = new * GradientBackgroundGenerator(new Integer(200),new * Integer(100),Color.blue,Color.white); */ Font[] fontsList = new Font[] { new Font("Arial", 1, 10),new Font("Tahoma", 10, 15),new Font("Verdana", 11, 12), }; FontGenerator fontGenerator = new RandomFontGenerator(new Integer(20), new Integer(35), fontsList); WordToImage wordToImage = new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster); this.addFactory(new GimpyFactory(wgen, wordToImage)); } }
Now Create Servlet named ImageCaptchaServlet:
import com.octo.captcha.service.CaptchaServiceException; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; 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 java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; 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(); } }
Create other Servlet named: Register.java
package com.ss; import java.io.IOException; import java.io.PrintWriter; 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; public class Register extends HttpServlet { public Register() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println("<br />"); Boolean isResponseCorrect = Boolean.FALSE; // remenber that we need an id to validate! String captchaId = request.getSession().getId(); // retrieve the response String response2 = request.getParameter("j_captcha_response"); // Call the Service method try { isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,response2); if (isResponseCorrect) out.println(" Your Code is matched with captcha..." + captchaId); else out.println(" Your Code is not matched with captcha..." + captchaId); } catch (CaptchaServiceException e) { // should not happen, may be thrown if the id is not valid out.println(" Erro on Captcha..." + e); } out.println("<br />"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void init() throws ServletException { } }
Create JSP page for captcha:
index.jsp
<html> <body> <form action="./register" method="post"> <input type='text' name='j_captcha_response' value=''> <br /> <input type="submit" value="Submit" /> </form> <br /> </body> </html>
So, now at end your WEB.xml will have entry like with two servlet:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <description>Captcha Servlet</description> <display-name> This is the display name of my J2EE component </display-name> <servlet-name>jcaptcha</servlet-name> <servlet-class>com.ss.ImageCaptchaServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet> <description>Captcha Servlet</description> <display-name> This is the display name of my J2EE component </display-name> <servlet-name>Register</servlet-name> <servlet-class>com.ss.Register</servlet-class> </servlet> <servlet-mapping> <servlet-name>jcaptcha</servlet-name> <url-pattern>/jcaptcha</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Register</servlet-name> <url-pattern>/register</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
And run the application.
1 comment:
Thanks,and good one
Post a Comment