Tutorial

How to integrate Google reCAPTCHA in Java Web Application

Published on August 4, 2022
How to integrate Google reCAPTCHA in Java Web Application

I never liked Captchas because the burden was always on end user to understand the letters and prove that he is a human and not a software bot. But when I recently saw new Google reCAPTCHA on a website, I instantly liked it. Because all we need is to check a box and it will figure out if you are a human or robot. Google is calling it No CAPTCHA reCAPTCHA experience and it uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. google recaptcha So that formed the basis of this post where I will show you how to utilize Google reCAPTCHA in your java based web application. Before we move on with our project, first thing you need to do is go to Google reCAPTCHA and sign up. After that you will get a Site key that is used to display the reCaptcha widget on your web pages. You will also get a Secret key that should be kept secret and used in communicating with Google server to verify the captcha response. After I registered a test site, I got below keys and I will utilize them in my project. Note that while signup you also need to provide domain name and the keys will work only on that domain name. Also keys will always work on localhost, so I can easily test it on my local server. Google reCAPTCHA keys Now we can head over to our example project. We will have a login page where user will enter username and password, apart from that he will also have to solve reCaptcha and submit the form. Once the form is submitted, username and password will be validated in our application, whereas we will send the captcha response with secret key to Google reCaptcha server and get the response. The response from Google reCaptcha is a JSON with a success boolean field, if validated success value will be true otherwise it will be false. I will use Java JSON Processing API to parse the response JSON. Below image shows our final project in Eclipse. Google reCAPTCHA Java Web Application To get the project skeleton, just create a “Dynamic Web Project” in Eclipse and then convert it to Maven project. Just add below dependency in pom.xml file for JSON API.

<dependency>
	<groupId>org.glassfish</groupId>
	<artifactId>javax.json</artifactId>
	<version>1.0.2</version>
</dependency>

Let’s look into each of the components one by one.

View Page with Google reCAPTCHA

Below is our login html page code. login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>

	<form action="LoginServlet" method="post">

		Username: <input type="text" name="user"> <br> Password:
		<input type="password" name="pwd"> <br>
		<div class="g-recaptcha"
			data-sitekey="6LdMAgMTAAAAAGYY5PEQeW7b3L3tqACmUcU6alQf"></div>
		<br> <input type="submit" value="Login">
	</form>
</body>
</html>

We need to add Google reCaptcha JS file in the HTML head section and then add <div class="g-recaptcha" data-sitekey="Site-key"></div> in our form to get the reCaptcha widget. That’s all at the client side, it’s really this simple! Once user is validated he will be sent to below success page. LoginSuccess.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<h3>Hi Pankaj, Login successful.</h3>
<a href="login.html">Login Page</a>
</body>
</html>

Login Servlet

Below is our simple LoginServlet.java servlet code where we are validating username and password fields. For simplicity, they are embedded as WebInitParam in the servlet code itself. Note that you need to use Servlet 3 to use these annotations, so you need to use Tomcat-7 or later versions that support servlet spec 3.

package com.journaldev.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.journaldev.utils.VerifyRecaptcha;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(description = "Login Servlet", urlPatterns = { "/LoginServlet" }, initParams = {
		@WebInitParam(name = "user", value = "Pankaj"),
		@WebInitParam(name = "password", value = "journaldev") })
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -6506682026701304964L;

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

		// get request parameters for userID and password
		String user = request.getParameter("user");
		String pwd = request.getParameter("pwd");
		// get reCAPTCHA request param
		String gRecaptchaResponse = request
				.getParameter("g-recaptcha-response");
		System.out.println(gRecaptchaResponse);
		boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);

		// get servlet config init params
		String userID = getServletConfig().getInitParameter("user");
		String password = getServletConfig().getInitParameter("password");
		// logging example
		System.out.println("User=" + user + "::password=" + pwd + "::Captcha Verify"+verify);

		if (userID.equals(user) && password.equals(pwd) && verify) {
			response.sendRedirect("LoginSuccess.jsp");
		} else {
			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					"/login.html");
			PrintWriter out = response.getWriter();
			if (verify) {
				out.println("<font color=red>Either user name or password is wrong.</font>");
			} else {
				out.println("<font color=red>You missed the Captcha.</font>");
			}
			rd.include(request, response);
		}
	}
}

Once form with captcha is submitted, we get “g-recaptcha-response” request parameter that is required to send for verification. The last part is the utility class to send POST request for verification and parse the JSON response and return accordingly.

package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.net.ssl.HttpsURLConnection;

public class VerifyRecaptcha {

	public static final String url = "https://www.google.com/recaptcha/api/siteverify";
	public static final String secret = "6LdMAgMTAAAAAJOAqKgjWe9DUujd2iyTmzjXilM7";
	private final static String USER_AGENT = "Mozilla/5.0";

	public static boolean verify(String gRecaptchaResponse) throws IOException {
		if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
			return false;
		}
		
		try{
		URL obj = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		// add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

		String postParams = "secret=" + secret + "&response="
				+ gRecaptchaResponse;

		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(postParams);
		wr.flush();
		wr.close();

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + postParams);
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// print result
		System.out.println(response.toString());
		
		//parse JSON response and return 'success' value
		JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
		JsonObject jsonObject = jsonReader.readObject();
		jsonReader.close();
		
		return jsonObject.getBoolean("success");
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}

That’s all. Our application is ready, below are the response pages we get based on user inputs. Login Page with Google Recaptcha Widget Google Recaptcha Widget Google Recaptcha Validated at client side Google Recaptcha Validated Response page after server side Google Recaptcha Validation Google Recaptcha Server Validated Response where Recaptcha was not solved Google Recaptcha Java Not Solved Recaptcha Solved but user/password didn’t match java captcha Other validation error You can download the project from below link and play around with it to learn more.

Download Google reCAPTCHA Java Web App Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 16, 2015

This recaptcha is working in with localhost tomcat.How when I put on live server in a Linux machine does not work. Could I plz help. I am really struggling.

- zahamed

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 16, 2015

What is not working, are you not getting the widget in UI, or you are not getting the response tag to server in the form or you are not able to validate it by submitting request to server. If you are putting on a live server with domain name, make sure your keys are registered with that domain name.

- Pankaj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 1, 2015

Hi Pankaj, I am using above example for our website. It is working in local host but it is not working in linux live server. I am getting connection timed out error. Could I plz help. I am really struggling. Thanks, Sadiq Ali

- Sadiq

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 19, 2020

use recaptcha v2

- surendra

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 31, 2015

    Connection.getoutputstream and getInputstream() showing connection timeout exception. What is the issue behind this ? Please respond asap

    - Sagar Rout

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 10, 2015

      i am not able to connect to https://ww.google —verify url . The problem is in making a https connection .Please reply how did you trust the certificates to make the https connection

      - saranya

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 19, 2015

        Thank you sir

        - FlyingCat

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          June 1, 2015

          I get error: “Require String parameter ‘g-recaptcha-response’ is not present”. I’m a newbie, please help me. Below are the images: error : https://i.imgur.com/cFYwJwU.png Controller: https://i.imgur.com/ZUgoG7L.png jsp: https://i.imgur.com/aR7trX9.png

          - BlueMan

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 24, 2015

            It is working fine when I integrate this in our web application. But how can I remove Privacy Terms in the widget, because our business doesn’t want to display google terms and conditions on our web application.

            - vasu

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 25, 2015

            I don’t think there is a way to remove it, since you are using Google service you will have to respect their privacy terms.

            - Pankaj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 19, 2015

              Post is useful. Thanks. As per above post, we do the captcha verification from servlet code. Servlet code mostly deployed in application server in production site. It is not practice to allow internet access from production application server. Since we have to hit google url “https://www.google.com/recaptcha/api/siteverify”, what is the alternative to verify the “g-recaptcha-response” before reach to servlet(server), that is get the verification done at browser code itself.

              - Venkatesa Kumar

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 24, 2015

                Congrats on this post, very helpfull!

                - Gaspar

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 31, 2015

                  This tip helped me too much, I was giving up already to make recaptcha, then I saw here I have to do the server-side validation, not the angularJS. Thank You !!!

                  - Renan Campos

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    September 15, 2015

                    Thank you, Pankaj, this demo helps me a lot!

                    - iridiumcao

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 17, 2015

                      I am trying to do this in JSF 2. I am able to show the script, but fail to get the parameter. truied following way HttpServletRequest req = (HttpServletRequest)context.getExternalContext().getRequest(); String val = req.getParameter(“g-recaptcha-response”); Should it be straight forward like in jsp? Thanks.

                      - wahid

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        November 27, 2015

                        Hi, It’s possible to make a unit test with Mockito framework ? If not, what Is the Best Way to test the recaptcha.

                        - zoom

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          February 9, 2016

                          When I try to use your example I am getting connection timeout errors. I have registered localhost and got the sitekey and secret key. and it all works fine when I directly hit the verify URL in the browser. JSON obj is returning true, but its not wokring in the code. java.net.ConnectException: Connection timed out: connect

                          - Manjunath

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          October 12, 2018

                          I am getting the same issue. Did you find out the solution ?

                          - Sunny Roy

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            February 10, 2016

                            Connection Timeout Exception is thrown from: DataOutputStream wr = new DataOutputStream(con.getOutputStream()); If I open URL from browser along with secretkey and response value, JSON object returning true. For example: https://www.google.com/recaptcha/api/siteverify?secret=&response= JSON: { “success”: true }

                            - Manjunath

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              February 25, 2016

                              Great sample page, right-to-the-pont explanation what to do, truly working examples and helpful code snippets. You just saved me a few hours of time. Thank you!

                              - Elmar Christen

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                March 9, 2016

                                Really nice article, I found it quite helpful while integrating Google captcha in my application.

                                - Parkash Kumar

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  March 17, 2016

                                  getting recaptcha verified without i click on any images that we get after clicking on check-box, instead it is directly getting verified without any user input. How to resolve this issue

                                  - GAJANAN KULKARNI

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    April 27, 2016

                                    very good simple sample~~ thank you.

                                    - leb

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      June 3, 2016

                                      recaptcha requires google certificate on application server, and validity on certificate is is just couple of months, how to maintain ever changing certificate on production servers.

                                      - Prasad

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        August 9, 2016

                                        Hi Pankaj, Do you have any mock test for reCaptcha?

                                        - Singh

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          September 6, 2016

                                          You help us. Thank you so much. This tutorial is perfect man.

                                          - Paulo Silveira

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            November 20, 2016

                                            Occasionally I see posts like this one, that works as a charm, without any effort, Great thank you guy

                                            - Ali Faradjpour

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              November 23, 2016

                                              very nice i tried to implement is and its working good thank you!!

                                              - Ravi Sah

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                February 14, 2017

                                                Hi pankaj, Tried of searching many tutos but found this is very useful, while implementing your exercise I’m getting this error: " ERROR for site owner: Invalid site key ". I have given proper site and secret key, googled it with google suggestion recreated my site keys but on my local site I’m not getting can you please help in this regard. Thanks a lot,

                                                - Cyril Thudumu

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                July 13, 2020

                                                Even i am getting same issue. Have u found the solution?

                                                - rahul chauhan

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  March 12, 2017

                                                  Works perfectly well on localhost. Haven’t tested on live server, but I haven’t had such a need, just needed to quickly test the recaptcha. For a live scenario I’d use a different JSON and HTTP client libraries.

                                                  - Serge

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    April 18, 2017

                                                    Nice writting. Very helpful. Do you know how to integrate reCaptcha with Spring security?

                                                    - Leo Wu

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      May 17, 2017

                                                      This is not going to work when proxy server in place Do you have steps how to make it work when application is hidden behind proxy. At the time of captcha verification, application could not able to connect to google verification url and throws unknownHostException

                                                      - Anupam

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        April 25, 2018

                                                        Nice article…worked for me

                                                        - lok

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          May 8, 2018

                                                          This code is not working on IE11

                                                          - Ali Bahadar

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            June 12, 2018

                                                            Hello Pankaj sir, i got an error : Localhost is not in the list of supported domains for this site key. please help me.

                                                            - Tejas Dahake

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            October 10, 2018

                                                            Go to this link https://www.google.com/recaptcha/admin#list and put localhost as a domain releven to your key

                                                            - SRL

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              May 23, 2019

                                                              you found the solution to that?

                                                              - shajo

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                July 30, 2020

                                                                please give the domain name instead of localhost.it will work

                                                                - Gopal Mohankuda

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  April 15, 2019

                                                                  Hi Pankaj, I ma receiving below exception at localhost. 19/04/15 07:18:58 java.net.ConnectException: Connection refused: connect 19/04/15 07:18:58 at java.net.PlainSocketImpl.socketConnect(Native Method)

                                                                  - Prakash

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    April 23, 2019

                                                                    Hi Pankaj, I am receiving below exception while implementing google captcha on localhost javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Please help

                                                                    - Prakash

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      May 23, 2019

                                                                      i ran the codein the eclipse and i gave the corresponding keys the site key and the security key,but it shows that error with the captcha site owner.Please help

                                                                      - shajo

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        May 23, 2019

                                                                        “Localhost is not in the list of supported domains for this site key” i keep seeing this in the captcha, i have given the label and the domain name as localhost.Please help me resolve this.

                                                                        - jojo

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          May 30, 2019

                                                                          Getting NULL value of reCaptcha response.

                                                                          - Hema

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            June 24, 2020

                                                                            Thank you for sharing!

                                                                            - Vu Nguyen

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              August 12, 2020

                                                                              Very good! I made a version with JSF / ManagedBean / Controller based in you example and works! Thanks!

                                                                              - André Hiroshi Tanaka

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                May 6, 2021

                                                                                I’m getting below error on JSF page: Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse () at recaptcha__en.js:59 at recaptcha__en.js:81 at Array. (recaptcha__en.js:93) at Array. (recaptcha__en.js:80) at KA.B (recaptcha__en.js:59) at Array. (recaptcha__en.js:53) at Hf.next (recaptcha__en.js:259) at h (recaptcha__en.js:325) Can you please help with this?

                                                                                - Manisha

                                                                                  Join the Tech Talk
                                                                                  Success! Thank you! Please check your email for further details.

                                                                                  Please complete your information!

                                                                                  Become a contributor for community

                                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                  DigitalOcean Documentation

                                                                                  Full documentation for every DigitalOcean product.

                                                                                  Resources for startups and SMBs

                                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                  Get our newsletter

                                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                  The developer cloud

                                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                  Get started for free

                                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                  *This promotional offer applies to new accounts only.