Integrate Free Anti-Bot Service reCAPTCHA with Spring MVC application
reCAPTCHA is a free CAPTCHA service to protect a site against spam and other types of automated abuse by bots or computer programs. reCAPTCHA provides widget which can easily be integrated to your blog, forum, comment, registration form, contact form, etc and you can be rest assured that only human is posting in your site.
This post will guide you on how to integrate free anti-bot service reCAPTCHA with a Spring MVC application.
Tools and Technologies used in this article :
1. Sign up for reCAPTCHA API keys
Use your existing google account or open a new one to sign up for reCAPTCHA API keys for your site. Provide domain name (say www.yoursite.com) and click 'Create Key' button.
Once signed up, two keys (Public key and Private key) will be provided for your domain.
Integration of reCAPTCHA into a form, mainly consists of following two steps
Client side code to display reCAPTCHA widget.
Server side code to verify user's answer by connecting to reCAPTCHA server.
2. Add reCAPTCHA Maven dependency
Add reCAPTCHA Maven dependency along with servlet-api in pom.xml.File : pom.xml
3. Client side code to display reCAPTCHA widget
We'll encapsulate all the codes to generate reCAPTCHA widget in a tagfile (say captcha.tag) so that it can be reused in other forms as well in the application.File : WEB-INF/tags/captcha.tag
Now use this tagfile (e.g. <sc:captcha>) in your form to display reCAPTCHA widget.File : WEB-INF/pages/captcha.jsp
4. Add reCAPTCHA bean
Add bean definition of reCAPTCHA implementation in spring configuration xml. Using annotation @Autowire, this bean is injected into controller.File : WEB-INF/dispatcher-servlet.xml
5. Server side code to verify user's entry
Now we'll write one controller class (say ReCaptchaHelloWorldController) with a handler method to verify reCAPTCHA words entered by the user.File : com/srccodes/spring/controller/ReCaptchaHelloWorldController.java
User will be redirected to either initial page (captcha.jsp) having reCAPTCHA widget or success page (success.jsp) based on the ReCaptchaResponse received from the reCAPTCHA sever.File : WEB-INF/pages/success.jsp
6. Overall Project Structure
Start the server and deploy the web application. Open the url http://<IP>:<PORT>/ReCaptchaHelloWorld.
If you enter wrong words and submit the form, then you will be redirected to the same page with an error message "Try again and prove it".
For correct reCAPTCHA entry, you will be redirected to the success page.
8. Live Demo