Press enter to see results or esc to cancel.


Add reCaptcha I m not a robot in JAVA websites

This tutorial shows how to add reCaptcha I m not robot in Websites using Servlet in JAVA and JSON.

  1. First login to google and go to the link https://www.google.com/recaptcha/admin#list You can see the Register a new site form as below.
  2. 2.1 Fill any Label
    2.1 Enter your host name, Now I am giving domain name as localhost. You can enter your website name if you want to host this in your website.
  3. After Registering new site, You will get a Site key and Secret key as Shown
  4. Project Structure in Eclipse IDE,
  5. LoginServlet.java
    package com.chillyfacts.com;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.chillyfacts.com.utils.VerifyRecaptcha;
    /**
     * Servlet implementation class LoginServlet
     */
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = -6506682026701304964L;
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		//hardcoded user name and password
    		String userID = "jinu" ;
    		String password = "jawad";
    		// 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
    		// 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);
    		}
    	}
    }
    
  6. VerifyRecaptcha.java
    package com.chillyfacts.com.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 = "Update your Secret key here";
    	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;
    		}
    	}
    }
    



  7. web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     	xmlns="http://java.sun.com/xml/ns/javaee"
     	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     	id="WebApp_ID" version="3.0">
     	<display-name>LoginExample</display-name>
     	<welcome-file-list>
     		<welcome-file>login.html</welcome-file>
    	 </welcome-file-list>
     	<servlet>
     		<servlet-name>LoginServlet</servlet-name>
     		<servlet-class>com.chillyfacts.com.LoginServlet</servlet-class>
     	</servlet>
     	<servlet-mapping>
     		<servlet-name>LoginServlet</servlet-name>
     		<url-pattern>/LoginServlet/*</url-pattern>
     	</servlet-mapping>
    </web-app>
    
  8. 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="Update your Site key here"></div>
          <br> <input type="submit" value="Login">
          </form>
    </body>
    </html>
    
  9. LoginSuccess.jsp

    <%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://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>Login successful.</h3>
     <a href="login.html">Login Page</a>
     </body>
     </html>
    
  10. Login.html after running the Application
  11. Error message if you missed captcha
  12. LoginSuccess.jsp after successful login

  13. Download the project here,
    Download the project here