Monday, September 20, 2010

integration of recaptcha in java web application

Step 1. Register your account and get key

First, go to the reCAPTCHA web site and create an account. As part of that account creation process you'll have to specify the domain your reCAPTCHA will be protecting.
The reCAPTCHA site will will give you a key pair for that domain. The key pair allows you to authenticate your reCAPTCHA requests to the reCAPTCHA servers, as we'll see.

Step 2. Put reCAPTCHA JavaScript code in your application

Following JavaScript code you need to put in your JSP / HTML page, This JavaScript will generate the reCAPTCHA box when users request the page:

You need to put with the public key that you received during the account creation process.
Be careful that you don't use your private key by mistake. If you do that then everybody will be able to see your private key and act like they're you.

Step 3. add a following code in servlet

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {

String challenge = req.getParameter("recaptcha_challenge_field");
String response = req.getParameter("recaptcha_response_field");
String remoteAddr = req.getRemoteAddr(); // code for live
// If you test on local site then need to put ipaddress where you register you site at the time of account creation
// e.g. String remoteAddr= // live ip address

ReCaptchaImpl reCaptcha = new ReCaptchaImpl();


ReCaptchaResponse reCaptchaResponse =
reCaptcha.checkAnswer(remoteAddr, challenge, response);
boolean valid = reCaptchaResponse.isValid();

String path = null;
if (valid) {
path = "/success.jsp";
} else {
path = "/failure.jsp";
res.sendRedirect(req.getContextPath() + path);

In above code You need to put with the private key that you received during the account creation process.

Step 4 : Run application

If you are test from localhost/ then you need to change ip address which is mentioned in above code reCAPTCHA will allow that.

After successfully changes recaptcha works :) enjoy

1 comment:

  1. Amazing blog! Do you have anny hints for aspiring writers?

    I'm hoping tto start my own blog soon but I'm a little lost on everything.
    Would you reecommend starting with a free platform like Wordpress
    or go for a paid option? There are so many options out there
    that I'm totally confused .. Any suggestions? Thanks
    a lot!

    my web-site - learn Spanish for free


Create MongoDB service in Windows OS

1) Open Command Prompt 2) Create directory for Database and Logs                    mkdir c:\data\db                     mkdir c:\...