Monday 10 June 2013

Using jcaptach in Java

Hi
I went through a number of code snippets as I had to integrate captcha in my web application.
I found the jCaptcha very easy and interesting..

I will like to share my code so that it can be by others too :)..

Good luck!

1) Download the jcpatcha jar fiel
I used : jcaptcha-all-1.0-RC3.jar


Your front end - the jsp file.

 <form name="SimpleServletForm" action="/mbis/simple" method="post">
        <input type="hidden" name="hidCaptchaID" value="<%= session.getId() %>"/>
         <table>
                 <tr>
                     <td>Username </td>
                     <Td> <input type="text" name="username" />  </Td>
                 </tr>
                 <tr>
                     <td>Password </td>
                     <Td> <input type="password" name="password" />  </Td>
                 </tr>
                 <tr>
                    <td > </td>
                    <Td><img src="/mbis/simple" align="middle" alt="Enter the characters appearing in this image" border="1"/></td>
                   
                  </tr>
                
                 <tr>
                    <td > </td>
                    <td><input type="text" name="inCaptchaChars"/></td>
                  </tr>
                 
                 <tr>
                     <td> </td>
                     <Td>  <input type="submit" value="Login" /></Td>
                 </tr>
                
         </table>
         </form>

//====  i have created a file with name SimpleCaptchaServlet
// I have mapped this servlet in web.xml file as


in web.xml file
<servlet>
    <servlet-name>SimpleCaptchaServlet</servlet-name>
    <servlet-class>com.breeze.servlet.SimpleCaptchaServlet</servlet-class>
    <init-param>
      <param-name>ImageType</param-name>
      <param-value>JPG</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SimpleCaptchaServlet</servlet-name>
    <url-pattern>/simple</url-pattern>
  </servlet-mapping>
  <servlet>




/// The actual java file.....
package com.breeze.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SimpleCaptchaServlet
 */

import com.breeze.service.MyCaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import javax.servlet.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import javax.imageio.ImageIO;

public class SimpleCaptchaServlet extends HttpServlet{

String sImgType = null;
public void init( ServletConfig servletConfig ) throws ServletException
{
super.init( servletConfig );

// For this servlet, supported image types are PNG and JPG.
sImgType = servletConfig.getInitParameter( "ImageType" );
sImgType = sImgType==null ? "png" : sImgType.trim().toLowerCase();
if ( !sImgType.equalsIgnoreCase("png") && !sImgType.equalsIgnoreCase("jpg") &&
!sImgType.equalsIgnoreCase("jpeg") )
{
  sImgType = "png";
}
}

protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
byte[] captchaBytes;

if ( request.getQueryString()!=null )
{
  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "GET request should have no query string." );
  return;
}
try
{
  // Session ID is used to identify the particular captcha.
  String captchaId = request.getSession().getId();

  // Generate the captcha image.
  BufferedImage challengeImage = MyCaptchaService.getInstance().getImageChallengeForID(
  captchaId, request.getLocale() );
  ImageIO.write( challengeImage, sImgType, imgOutputStream );
  captchaBytes = imgOutputStream.toByteArray();

  // Clear any existing flag.
  request.getSession().removeAttribute( "PassedCaptcha" );
}
catch( CaptchaServiceException cse )
{
   System.out.println( "CaptchaServiceException - " + cse.getMessage() );
   response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem generating captcha image." );
   return;
}
catch( IOException ioe )
{
   System.out.println( "IOException - " + ioe.getMessage() );
   response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem generating captcha image." );
   return;
}

// Set appropriate http headers.
response.setHeader( "Cache-Control", "no-store" );
response.setHeader( "Pragma", "no-cache" );
response.setDateHeader( "Expires", 0 );
response.setContentType( "image/" + (sImgType.equalsIgnoreCase("png") ? "png" : "jpeg") );

// Write the image to the client.
ServletOutputStream outStream = response.getOutputStream();
outStream.write( captchaBytes );
outStream.flush();
outStream.close();
}

protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
// Get the request params.
Map paramMap = request.getParameterMap();
if ( paramMap.isEmpty() )
{
  response.sendError( HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Post method not allowed without parameters." );
  return;
}
String[] arr1 = (String[])paramMap.get( "hidCaptchaID" );
String[] arr2 = (String[])paramMap.get( "inCaptchaChars" );
if ( arr1==null || arr2==null  )
{
  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Expected parameters were not found." );
  return;
}

String sessId = request.getSession().getId();
String incomingCaptchaId = arr1.length>0 ? arr1[0] : "";
String inputChars = arr2.length>0 ? arr2[0] : "";

// Check validity and consistency of the data.
if ( sessId==null || incomingCaptchaId==null || !sessId.equals(incomingCaptchaId) )
{
  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Browser must support session cookies." );
  return;
}

// Validate whether input from user is correct.
System.out.println( "Validating - inputChars are: " + inputChars );
boolean passedCaptchaTest = validateCaptcha( incomingCaptchaId, inputChars );

// Set flag into session.
request.getSession().setAttribute( "PassedCaptcha", new Boolean(passedCaptchaTest) );

// Forward request to results page.
request.setAttribute("username", request.getParameter("username"));
request.setAttribute("password", request.getParameter("password"));

if(passedCaptchaTest){   // If correct CAPTCHA code inserted, Send it to the Login servlet
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login");
    rd.forward( request, response );
}
else {
    request.setAttribute("loginMessage", "Invalid Captcha code....");
    getServletContext().getRequestDispatcher("/pages/index.jsp").forward(request, response);
 }
}

private boolean validateCaptcha( String captchaId, String inputChars )
{
boolean bValidated = false;
try
{
  bValidated = MyCaptchaService.getInstance().validateResponseForID( captchaId, inputChars );
}
catch( CaptchaServiceException cse )
{}
return bValidated;
}
}



If you are interested to get the source code..just message me, I will send the source code too..
I am not attaching it here because I need to get it separated from my web application.

Thanks.

No comments:

Post a Comment