You'll find it convenient to download the recaptcha4j library. It provides a simple API for submitting user responses to the reCAPTCHA server and finding out whether a user's response is valid.
At this point I'm just going to lay some code on you. As mentioned above I'm using Spring 2.5 MVC with annotations and Commons Validator, but the main thing is
for you to look at how I'm using the ReCaptchaImpl
class and just copy that.
import net.tanesha.recaptcha.ReCaptchaImpl; import net.tanesha.recaptcha.ReCaptchaResponse; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; ... @RequestMapping(value = "/comments/postcomment.do", method = RequestMethod.POST) public String doPost( HttpServletRequest req, @RequestParam("articleId") long articleId, @RequestParam("recaptcha_challenge_field") String challenge, @RequestParam("recaptcha_response_field") String response, @ModelAttribute("comment") Comment comment, BindingResult result) { // Validate the form (other than the reCAPTCHA) validator.validate(comment, result); // Validate the reCAPTCHA String remoteAddr = req.getRemoteAddr(); ReCaptchaImpl reCaptcha = new ReCaptchaImpl(); // Probably don't want to hardcode your private key here but // just to get it working is OK... reCaptcha.setPrivateKey("<your_private_key>"); ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, response); if (!reCaptchaResponse.isValid()) { FieldError fieldError = new FieldError( "comment", "captcha", response, false, new String[] { "errors.badCaptcha" }, null, "Please try again."); result.addError(fieldError); } // If there are errors, then validation fails. if (result.hasErrors()) { String path = comment.getPagePath(); log.debug("Form validation error; forwarding to " + path); return "forward:" + path; } // Else validation succeeds. log.debug("Form validation passed"); comment.setIpAddress(remoteAddr); comment.setDate(new Date()); // Post the comment log.debug("Posting the comment"); articleService.postComment(articleId, comment); log.debug("Comment posted"); return "redirect:" + comment.getPagePath() + "#comments"; }
Here's the API for FieldError since I know that's not clear from the code. Basically I'm using that to indicate that a validation error occurred and set up an error message for the user. If you're not using Spring/Validator then you'll do something else here.
The Comment
class is just a class from my app, so don't worry about that one.
Good job. If you're feeling ambitious, try to defeat reCAPTCHA with super-advanced OCR. If you succeed then it represents an advance in OCR technology. Tell somebody and become famous. :-)