10

I am developing a web application in java using netbeans and mysql. There is a registration form in the application. When the user submits the form, the client and server side validation is performed.

Now I want to insert a captcha in the form. How do I insert it, and how to check that user has entered the correct captcha value?

Handcraftsman
  • 6,863
  • 2
  • 40
  • 33
Asma Ihsan
  • 131
  • 1
  • 3
  • 10
  • 1
    possible duplicate of [CAPTCHA in java](http://stackoverflow.com/questions/3326778/captcha-in-java) – Raedwald Feb 11 '13 at 13:18

5 Answers5

7

Your captcha code works without any change inside a servlet's doGet(...) method.

package test.captcha;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CaptchaServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {


    response.setContentType("image/jpg");
    /*
     * Define number characters contains the captcha image, declare global
     */
    int iTotalChars = 6;

    /*
     * Size image iHeight and iWidth, declare globl
     */
    int iHeight = 40;
    int iWidth = 150;

    /*
     * font style
     */
    Font fntStyle1 = new Font("Arial", Font.BOLD, 30);
    Font fntStyle2 = new Font("Verdana", Font.BOLD, 20);

    /*
     * Possible random characters in the image
     */
    Random randChars = new Random();
    String sImageCode = (Long.toString(Math.abs(randChars.nextLong()), 36)).substring(0, iTotalChars);

    /*
     * BufferedImage is used to create a create new image
     */
    /*
     * TYPE_INT_RGB - does not support transpatency, TYPE_INT_ARGB - support transpatency
     */
    BufferedImage biImage = new BufferedImage(iWidth, iHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2dImage = (Graphics2D) biImage.getGraphics();

    // Draw background rectangle and noisey filled round rectangles
    int iCircle = 15;
    //g2dImage.fillRect(0, 0, iWidth, iHeight);
    for (int i = 0; i < iCircle; i++) {
        g2dImage.setColor(new Color(randChars.nextInt(255), randChars.nextInt(255), randChars.nextInt(255)));
        int iRadius = (int) (Math.random() * iHeight / 2.0);
        int iX = (int) (Math.random() * iWidth - iRadius);
        int iY = (int) (Math.random() * iHeight - iRadius);
        //g2dImage.fillRoundRect(iX, iY, iRadius * 2, iRadius * 2,100,100);
    }
    g2dImage.setFont(fntStyle1);
    for (int i = 0; i < iTotalChars; i++) {
        g2dImage.setColor(new Color(randChars.nextInt(255), randChars.nextInt(255), randChars.nextInt(255)));
        if (i % 2 == 0) {
            g2dImage.drawString(sImageCode.substring(i, i + 1), 25 * i, 24);
        } else {
            g2dImage.drawString(sImageCode.substring(i, i + 1), 25 * i, 35);
        }
    }

    /*
     * create jpeg image and display on the screen
     */
    OutputStream osImage = response.getOutputStream();
    ImageIO.write(biImage, "jpeg", osImage);
    //osImage.close();

    /*
     * Dispose function is used destory an image object
     */
    g2dImage.dispose();

    HttpSession session = request.getSession();
    session.setAttribute("dns_security_code", sImageCode);
    //System.out.println("Captcha Page :"+session.getAttribute("dns_security_code"));

}



protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


}

create if not exist a web application descriptor: /WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<servlet>
        <servlet-name>CaptchaServlet</servlet-name>
        <servlet-class>test.captcha.CaptchaServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>CaptchaServlet</servlet-name>
    <url-pattern>/captcha-image.jpg</url-pattern>
</servlet-mapping>
</web-app>
Amol Fasale
  • 942
  • 1
  • 10
  • 32
  • Please also tell me that how we create link for this code in jsp? I don't know that Kindly help me – Asma Ihsan Feb 11 '13 at 13:21
  • @Asma I think using `` should do the trick. – Jus12 Jul 06 '13 at 16:59
  • You need to move the session creation further up in your code otherwise you'll get an error to the effect that the session can't be created or have something added to it after the response has already been written (or similarly worded) – Marcus Junius Brutus Jan 06 '17 at 18:14
2

Just google it and you will find lots of examples. Here is the first one, easy enough to get started http://www.devmanuals.com/tutorials/java/jsp/captcha.html

AL̲̳I
  • 2,441
  • 4
  • 29
  • 50
0

Here you go with sample code. Hope it helps.

http://captchas.net/sample/jsp/

melbourne-geek
  • 377
  • 1
  • 11
0

Try reCAPTCHA https://developers.google.com/recaptcha/ - it is widely used library with proved plugins for multiple programming languages (including Java/JSP) - see Plugins section. Btw, you can use this library without server side handling too - see sections Display Without Plugins and Verify Without plugins.

Pavla Nováková
  • 796
  • 4
  • 11
0

This code is working:

//put in your jsp page

<div class="form-cont">
                        <img src="CaptchaImg.jpg" alt="image">
                    </div>
                    <div class="form-cont">
                     <input autocomplete="off"  type="text" class="captcha input-elm" tabindex="3"  
                        placeholder="Captcha Code" name="j_captcha_response" id="j_captcha_response" 
                         maxlength="4">
                    </div>

//PUT in YOUR class


 String parm = httpServletRequest.getParameter("j_captcha_response");
        String captchaKey = (String)session.getAttribute(CaptchaServlet.CAPTCHA_KEY) ;

        if(parm.equalsIgnoreCase(captchaKey)){
true
//CODE HERE
}
else{
faLSE
ERROR HERE 
}
Gavriel Cohen
  • 4,355
  • 34
  • 39
Mr. GK
  • 1
  • 1