Java Captcha in Struts 2 Application

This Java Captcha Example demonstrates you how to develop a captcha Servlet and use in your Struts 2 application.



Java Captcha in Struts 2 Application


This Java Captcha Example demonstrates you how to develop a captcha Servlet and use in your Struts 2 application.

Developing Struts 2 Captcha Application
In this section we are going to develop Captcha Servlet and then use the same to validate Struts 2 based web applications. We have developed a Servlet that generates Captcha image. 

Let's see how our Captcha application works. 

Working of the application

  1. captcha.jsp:  This page contains the captcha image and one text field. 
  2. User reads the image text and then enters in the "Code" text field. After entering the value in the text field, user clicks on the "Verify"  command button.
  3. Then our Struts 2 action validates the user input and the session Captcha value.  If user enters the correct image code in the text filed, then action  forward to the "success.jsp" page. Otherwise, it gives an error and go to again the "captcha.jsp".

1. Index page
In the  index.html we have added a link to captcha.jsp. User can click on this link to go to the captcha form.

<title>Capcha Validation</title>
a:link{ color:red; text-decoration:underline; }
a:visited{ color:red; text-decoration:underline; }
a:hover{ color:green; text-decoration:none; }
a:active{ color:red; text-decoration:underline; }
<tr><td><a href="captcha.jsp">Captcha Application</a></td></tr>

2. Captcha Page
The GUI of the application consists of  Captcha page  (captcha.jsp). 
The captcha.jsp is used to display the valid code and a text box. 

<%@ taglib prefix="s" uri="/struts-tags" %>
<title>Capcha Validation</title>
.errorMessage {
color: red;
font-size: 0.8em;

.label {
<h1>Captcha Validation</h1>
<s:form action="doCaptcha" method="POST">
<s:actionerror /> 
<img src="Captcha.jpg" border="0">
<s:textfield label="Code" name="j_captcha_response" size="20" maxlength="10"/>
<s:submit value="Verify" align="center" />

The code :
<s:actionerror />
displays action errors and field validation errors.

The code <s:form action="doLogin" method="POST"> generates the html form for the application.

The code :

<img src="Captcha.jpg" border="0">
<s:textfield label="Code" name="j_captcha_response" size="20" maxlength="10"/>

The submit button is generated through <s:submit value="Verify" align="center" /> code.

3. Servlet Class
Develop a Servlet class "" to create a Captcha image. Here is the code of Servlet class:

package com.roseindiaCaptcha.servlet;

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.http.*;
import javax.servlet.*;
import java.awt.*;
import java.util.*;
import java.awt.font.TextAttribute;
public class RoseIndiaCaptcha extends HttpServlet {

  private int height=0;
  private int width=0;
  public static final String CAPTCHA_KEY = "captcha_key_name";

  public void init(ServletConfig config) throws ServletException {

 protected void doGet(HttpServletRequest req, HttpServletResponse response) 
   throws IOException, ServletException {
    //Expire response
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Max-Age", 0);
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
    Graphics2D graphics2D = image.createGraphics();
    Hashtable map = new Hashtable();
    Random r = new Random();
    String token = Long.toString(Math.abs(r.nextLong()), 36);
    String ch = token.substring(0,6);
    Color c = new Color(0.6662f, 0.4569f, 0.3232f);
    GradientPaint gp = new GradientPaint(30, 30, c, 15, 25, Color.white, true);
    Font font=new Font("Verdana", Font.CENTER_BASELINE , 26);
    HttpSession session = req.getSession(true);

    OutputStream outputStream = response.getOutputStream();
    ImageIO.write(image, "jpeg", outputStream);



4.Mapping  for Servlet class in web.xml

<description>passing height</description> 
<description>passing height</description> 


5.Success page

After successful validation page  transfer to the ""

<title>Capcha Validation</title>
<table><tr><td><h1>You are Succesfully Validate</h1></td></tr></table>

6.Developing Action Class
Now let's develop the action class to handle the Captcha validation request. 

The code  String c= (String)session.getAttribute(RoseIndiaCaptcha.CAPTCHA_KEY) is used to get the Captcha value stored in session and then validate it with the user input. Here is the code of the Action class.

package com.roseindiaCaptcha.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
import javax.servlet.http.*;
import javax.servlet.*;
import com.opensymphony.xwork2.ActionContext;
import com.roseindiaCaptcha.servlet.*;

public  class CaptchaAction  extends ActionSupport {
  public String execute() throws Exception {
      HttpServletRequest request  = (HttpServletRequest)
      Boolean isResponseCorrect = Boolean.FALSE;
      javax.servlet.http.HttpSession session = request.getSession();
      String parm = request.getParameter("j_captcha_response");
      String c= (String)session.getAttribute(RoseIndiaCaptcha.CAPTCHA_KEY) ;
      if(!parm.equals(c) ){
      addActionError("Invalid Code! Please try again!");
      return ERROR;
    return SUCCESS;


7.Configuring action mapping (in struts.xml)
Now we will create action mapping in the struts.xml file. Here is the code to be added in the struts.xml:
<action name="doCaptcha" class="com.roseindiaCaptcha.action.CaptchaAction">
<result name="error">captcha.jsp</result>

In the above mapping the action "doCaptcha" is used to validates the user using action class (

Output : 

If invalid code the error message is display.


After successfully validation message :

Download the application


Share on Google+Share on Google+

Java Captcha in Struts 2 Application

Posted on: May 24, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Java Captcha in Struts 2 Application   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
June 10, 2011
Excellent Example! Thanks

This is what I call an excellent example. Thank you very much. Ray
February 28, 2012

thanx dear......
July 9, 2012
How can I refresh the captcha Image

Please give me some idea to refresh the captcha image without refreshing the whole page.
October 7, 2013
About struts2 captcha image

sir am using u r above captcha code but image is not dispalying why? plese help me....
December 8, 2013
Captcha implementation

Am getting error on click of verify button: plz suggest on the same. java.lang.reflect.InvocationTargetException sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke( sun.reflect.DelegatingMethodAccessorImpl.invoke( java.lang.reflect.Method.invoke( com.opensymphony.xwork2.DefaultActionInvocation.invokeAction( com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept( com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept( org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept( com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept( com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept( com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( org.apache.struts2.interceptor.MultiselectInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( org.apache.struts2.interceptor.CheckboxInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( org.apache.struts2.interceptor.FileUploadInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept( com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( org.apache.struts2.interceptor.ServletConfigInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept( com.opensymphony.xwork2.DefaultActionInvocation.invoke( org.apache.struts2.impl.StrutsActionProxy.execute( org.apache.struts2.dispatcher.Dispatcher.serviceAction( org.apache.struts2.dispatcher.FilterDispatcher.doFilter( sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke( sun.reflect.DelegatingMethodAccessorImpl.invoke( java.lang.reflect.Method.invoke($ Method)
March 21, 2014
Java Captcha in Struts 2 Application

Please share the image "Captcha.jpg" as it is not visible on the jsp page
May 18, 2015
hi i am java learner

i am using ur code but i have problem with struts of course i am new to struts but i tried and change the code of captcha.jsp remove the taglib and i tried it in completely in java but the actual problem is captcha image is not displaying i don't know what is the proble can u plz help to know to captch technology and how the captcha code can refreshed and how to prepare captcha as shown in ur site..... Thanks & Regard's Srikant