Thursday, March 26, 2015

How to create a Captcha in java?

Creating a captach in java is nothing but converting some random number or character in Image form in Servlet and send it to back as response in form of image to browser.

testCaptcha.jsp






Step 1 : Create a Servlet program and in this servlet write some logic to create a random string and convert it into form of image using awt api of java and later send it to back to browser.

CaptchaServlet.java


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.catalina.util.Base64;
import sun.misc.BASE64Encoder;

public class CaptchaServlet extends HttpServlet {

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

        int width = 150;
        int height = 50;
        List arrayList = new ArrayList();
        String capcode = "abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMONOPQURSTUVWXYZ0123456789!@#$%&*";
        for (int i = 1; i < capcode.length() - 1; i++) {
            arrayList.add(capcode.charAt(i));
        }
        Collections.shuffle(arrayList);
        Iterator itr = arrayList.iterator();
        String s = "";
        String s2 = "";
        Object obj;
        while (itr.hasNext()) {
            obj = itr.next();
            s = obj.toString();
            s2 = s2 + s;
        }
        String s1 = s2.substring(0, 6);
        char[] s3 = s1.toCharArray();
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();
        Font font = new Font("Georgia", Font.BOLD, 18);
        g2d.setFont(font);
        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHints(rh);
        GradientPaint gp = new GradientPaint(0, 0, Color.red, 0, height / 2, Color.black, true);
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(new Color(255, 153, 0));
        Random r = new Random();
        int index = Math.abs(r.nextInt()) % 5;
        String captcha = String.copyValueOf(s3);
        request.getSession().setAttribute("captcha", captcha);
        int x = 0;
        int y = 0;
        for (int i = 0; i < s3.length; i++) {
            x += 10 + (Math.abs(r.nextInt()) % 15);
            y = 20 + Math.abs(r.nextInt()) % 20;
            g2d.drawChars(s3, i, 1, x, y);
        }
        g2d.dispose();
        response.setContentType("image/png");
        
        OutputStream os = response.getOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        os.flush();
        os.close();
        
    }

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

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

In above program we have create one png image and send it back to browser as response in form of image. And request.getSession().setAttribute("captcha", captcha); we have added this captcha in session for further use at jsp or any where while submitting the form.

Step 2 : Create web.xml by configuring the below servlet entry –

web.xml


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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_2_5.xsd">

    <servlet>
        <servlet-name>CaptchaServlet</servlet-name>
        <servlet-class>test.CaptchaServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>CaptchaServlet</servlet-name>
        <url-pattern>/CaptchaServlet</url-pattern>
    </servlet-mapping>
 
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

Step 3 : Create a jsp page. 

captchaTest.jsp

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Captcha</title>
  <link rel="stylesheet" href="style.css">
 </head>
 <body>
 <center>
 <form method="post">
  <table cellspacing="15">
   <tr>
    <td>Name</td>
    <td><input type="text" name="name"></td>
   </tr>
   <tr>
    <td>Message</td>
    <td><textarea type="text" cols="25" rows="8" name="message"></textarea></td>
   </tr>
   <tr>
    <td>Are you human?</td>
    <td><input type="text" name="code"></td>
   </tr>
  </table>
  <br>
  <img src="http://localhost:8084/AllPOC/CaptchaServlet"> 
  <br><br>
  <input type="submit" value="submit">
 </form>
 <br><br>
 <%
   String captcha = (String) session.getAttribute("captcha");
   String code = (String) request.getParameter("code");

   if (captcha != null && code != null) {

  if (captcha.equals(code)) {
    out.print("<p class='alert'>Correct</p>");
  } else {
     out.print("<p class='alert'>Incorrect</p>");
  }
   }
 %>
 </center>
 </body>
</html>

In above jsp <img src="http://localhost:8084/AllPOC/CaptchaServlet"> this will insert the captcha. And while submitting the page we will retrieve the value from request -
String captcha = (String) session.getAttribute("captcha");
  
And compare the captcha with session value 
String code = (String) request.getParameter("code");

No comments :

Post a Comment