Nowadays the simplest way to secure your formular against robots and automated tools is to add a captcha to it.
I found Google’s Recaptcha 2.0 to be an elegant solution. It looks good and it’s easy to
implement. The general mechanism is thoroughly documented in the developer’s guide so it makes no sense to just repeat it here. Instead I
want to show you how I would implement it together with a Java EE @POST method.
Assume you have a contact form which has the following 3 fields: name, email and message . The class that maps the form
looks like this:
And the JAX-RS resource with the post method that handles the form:
Now, when the user resolves the captcha, a hidden field is added in the html <form> element, with the name g-recaptcha-response .
You can use this name to map the field on the ContactForm, together with the other 3. The ContactForm class now has one more
field (+ getters and setters):
Note: I always add @DefaultValue("") when dealing with strings, to avoid null values in case the parameter isn’t supplied.
Let’s add the class GoogleRecaptchaCheck which will encapsulate the call to Google’s web service. I’m going to keep it simple here and
only use the user’s captcha response. As the documentation states, you can, optionally, send the user’s IP as well.
Note: this class uses Apache’s HttpClient to make the POST to Google’s web service.
Your REST post method now looks like this:
Done. Now no bots will be able to send your formular. I hope this article was useful - feel free to ask any questions in the Disqus thread below.