Make "I'm not a robot" in Java EE (Jakarta EE)

0. Environment

The environment in which this article was written

OS...Windows 10 IDE...Eclipse 2020-3 Java...Open JDK 14 Servlet container ... Apache Tomcat 9.0.33

1. Create a reCAPTCHA

First, access the reCAPTCHA site. reCAPTCHA

Create with the + button.

Enter the information of your site.


Enter a descriptive name for the label.

For the reCAPTCHA type, I want to do "I'm not a robot", so I chose reCAPTCHA v2. Then, the "I am not a robot" checkbox will appear, so make sure it is selected.

For the domain, enter the domain for which "I am not a robot" is set. If you register the top domain, you can use it in subdomains. If you want to use it in the development environment, also register "localhost".

The owner ... well, you can do whatever you want.

Finally, accept the reCAPTCHA Terms of Service, choose to send the alert to the owner and click Send

The next screen will display two strings, so make a note of both.

2. Create a new project in Eclipse

This time, set it to "RecaptchaTest". (If you have already made it, use it.)

3. HTML creation

Let's create a new HTML file in the WebContent of the project created in Eclipse.

Or you can create it with an external editor and paste it into your project.

I don't usually write this kind of fucking code, but this time it's a sample. .. ..

<!doctype html>
<html lang="ja">
		<meta charset="utf-8">
		<title>reCAPTCHA sample</title>
		<script src="" async defer></script>
		<form action="login" method="post">
			ID:<input type="text" name="id"><br>
password:<input type="password" name="current-password">
			<div class="g-recaptcha" data-sitekey="[Enter the string in the box above, out of the two strings displayed earlier.]"></div>
			<input type="submit" value="Login">

The important thing is to read the script of the head and in the form

<div class="g-recaptcha" data-sitekey="[The one that was written in the box above that was displayed earlier]">

To put.

The "I'm not a robot" guy will be displayed where you put this div.

So, after completing the above HTML, let's try running it on the server. If it looks like the image below, it's okay! !!


4. Class creation

Let's create a class (model) that queries Google's reCAPTCHA for results.

The mechanism is simple, put the specified parameters on the determined URL, POST, and JSON will be returned in the response.

Let's change the SECRET_KEY in the code below to the character string we got ~~~

package com.sakurai_shinya.recaptcha;



public class RecaptchaAuthenticator {

	private static final String URL = "";
	private static final String SECRET_KEY = "[The string that was in the box below]";

	public static boolean checkRecaptcha(String userToken) throws IOException {
		String recaptchaResponse = post(new URL(URL), "secret=" + SECRET_KEY + "&response=" + userToken);
		return recaptchaResponse.contains("\"success\": true,");

	private static String post(URL url, String parameters) throws IOException {
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		try (DataOutputStream dos = new DataOutputStream(con.getOutputStream())) {
		if (con.getResponseCode() != 200) {
			throw new IOException("An error occurred while communicating with the server.");
		StringBuilder sb = new StringBuilder();
		try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
			String tempStr;
			while ((tempStr = in.readLine()) != null) {
		return sb.toString();

Since it is troublesome, I made the response as contains, OK if "" success ": true," was included, and NG if it was not included. If you want to do it properly, you should make an object properly and parse it.

5. Create controller (Servlet)

I'll put all the Servlet code on it, but only at POST. Or rather, just look at POST

package com.sakurai_shinya.servlet;


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

import com.sakurai_shinya.recaptcha.RecaptchaAuthenticator;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		super.service(request, response);

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		boolean recaptchaResult = false;
		try {
			recaptchaResult = RecaptchaAuthenticator.checkRecaptcha(request.getParameter("g-recaptcha-response"));
		} catch (IOException e) {
			response.getWriter().append("An error occurred while communicating with the reCAPTCHA authentication server." + e.toString());
		if (recaptchaResult) {//reCAPTCHA success
			//The process of matching the ID and password here.
			String inputId = request.getParameter("id");
			String inputPass = request.getParameter("current-password");
			response.getWriter().append("Successful reCAPTCHA certification.<br>ID:" + inputId + "<br>password:" + inputPass);
		} else {//reCAPTCHA failure
			response.getWriter().append("ReCAPTCHA authentication failed.");

If you call checkRecaptcha of the class you created earlier, the result will be true or false, or an exception will be returned. If true, reCAPTCHA will succeed, if false, reCAPTCHA will fail, and the exception will be an error.

By the way, if you paste the g-recaptcha guy on the form, the g-recaptcha-response parameters will be POSTed together with a mysterious force. You send this to Google's server to identify the user ~~~

6. Test

Let's try it out! result1.PNG

Test with and without this check! result2.PNG


7. Bonus

7-1. How to make it black

If you add data-theme = dark to the guy who has g-recaptcha, it will turn black. Now you can place it coolly even on a black site! !!

<div class="g-recaptcha" data-sitekey="6Lfx-eMUAAAAALrP774ZrvQa_AtguQhusF0M2W6s" data-theme="dark"></div>

Like this ↓


7-2. How to make it into English

If you add hl = en to the GET parameter of api.js, it will be in English.

<script src="" async defer></script>


It gives a stylish impression, unlike Japanese, which breaks lines at strange positions.

By the way, other languages are on the reCAPTCHA guide. Language Codes  |  reCAPTCHA  |  Google Developers

Recommended Posts

Make "I'm not a robot" in Java EE (Jakarta EE)
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Make Blackjack in Java
[Personal memo] Make a simple deep copy in Java
Let's make a robot! "A simple demo of Java AWT Robot"
I tried to make a login function in Java
Refactoring: Make Blackjack in Java
Find a subset in Java
[Java] Make it a constant
Make a rhombus using Java
Let's make a calculator application in Java ~ Display the application window
I just wanted to make a Reactive Property in Java
I tried to make a client of RESAS-API in Java
3 Implement a simple interpreter in Java
I created a PDF in Java.
How to make a Java container
[Java] Do not use "+" in append!
A simple sample callback in Java
I'm not sure about Java Servlet
Java Calendar is not a singleton.
Make a SOAP call in C #
Get stuck in a Java primer
Java EE 8 (Jakarta EE 8) New feature summary
How to make a Java array
[JAVA] Project Euler, I got stuck in Q8, so make a note
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I tried to make a talk application in Java using AI "A3RT"
About returning a reference in a Java Getter
What is a class in Java language (3 /?)
How to make a Java calendar Summary
When seeking multiple in a Java array
Easy to make Slack Bot in Java
[Creating] A memorandum about coding in Java
Java creates a table in a Word document
Java creates a pie chart in Excel
What is a class in Java language (1 /?)
How to make a Discord bot (Java)
What is a class in Java language (2 /?)
Create a TODO app in Java 7 Create Header
Try making a calculator app in Java
Implement something like a stack in Java
Split a string with ". (Dot)" in Java
Creating a matrix class in Java Part 1
[Java] Let's make a DB access library!
Do not declare variables in List in Java
Let's make a calculator application with Java ~ Create a display area in the window
Cause of is not visible when calling a method of another class in java
I made a primality test program in Java
GetInstance () from a @Singleton class in Groovy from Java
Two ways to start a thread in Java + @
Read a string in a PDF file with Java
Create a CSR with extended information in Java
A story about the JDK in the Java 11 era
How to display a web page in Java
[Android / Java] Operate a local database in Room
Measure the size of a folder in Java
Code to escape a JSON string in Java
I did Java to make (a == 1 && a == 2 && a == 3) always true
Try to create a bulletin board in Java
Solution for NetBeans 8.2 not working in Java 9 environment
A note when you want Tuple in Java