Press enter to see results or esc to cancel.


Add reCaptcha I m not a robot in JAVA JSF Websites

This tutorial shows step by step how to include reCaptcha I m not a robot in JAVA JSF Websites.

  1. First you have to register with Google recaptcha and get the Site Key and Secret Key.
    Visit this link to get the step by step process.
    http://chillyfacts.com/add-recaptcha-i-m-not-a-robot-in-java-websites/
  2. After Registering new site, You will get a Site key and Secret key as Shown
  3. Project Structure in Netbeans IDE.
  4. login.java
    package com;
    import javax.faces.application.FacesMessage;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
    import javax.faces.context.FacesContext;
    @ManagedBean
    @RequestScoped
    public class login {
        private String user_name;
        public void setUser_name(String user_name) {
            this.user_name = user_name;
        }
        public String getUser_name() {
            return user_name;
        }
         public String submit_form(){
             try {
            String gRecaptchaResponse = FacesContext.getCurrentInstance().
            getExternalContext().getRequestParameterMap().get("g-recaptcha-response");
            boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);
            if(verify){
                 return "Success";
            }else{
                 FacesContext context = FacesContext.getCurrentInstance();
                 context.addMessage( null, new FacesMessage( "Select Captcha") );
                 return null;
              }
             } catch (Exception e) {
                 System.out.println(e);
             }
            return null;
         }    
    }
    
  5. VerifyRecaptcha.java
    package com;
    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 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;
    		}
    	}
    }
    
  6. index.xhtml
    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:h="http://xmlns.jcp.org/jsf/html">
     <h:head>
     <title>Facelet Title</title>
     <script src="https://www.google.com/recaptcha/api.js"></script>
     </h:head>
     <h:body>
     <h:form> 
     User Name <h:inputText value="#{login.user_name}" required="true" requiredMessage="Enter Name"></h:inputText>
     <div class="g-recaptcha" data-sitekey="UPDATE SITE KEY HERE"></div>
     <h:commandButton value="Submit" action="#{login.submit_form}"></h:commandButton>
     </h:form> 
     </h:body>
    </html>
  7. success.xhtml
    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
         <title>Facelet Title</title>
    </h:head>
         <h:body>
              Success......!!!!
              <br></br>
              <h:outputText value="#{login.user_name}"></h:outputText>
         </h:body>
    </html>
    
  8. faces-config.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <faces-config version="2.2"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-		
         facesconfig_2_2.xsd">
               <navigation-rule>
                    <from-view-id>index.xhtml</from-view-id>
               <navigation-case>
                    <from-action>#{login.submit_form}</from-action>
                    <from-outcome>Success</from-outcome>
                    <to-view-id>success.xhtml</to-view-id>
               </navigation-case>
               </navigation-rule>
         </faces-config>
    
  9. web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     <context-param>
    	 <param-name>javax.faces.PROJECT_STAGE</param-name>
     	<param-value>Development</param-value>
     </context-param>
     <servlet>
     	<servlet-name>Faces Servlet</servlet-name>
     	<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
     	<load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
     	<servlet-name>Faces Servlet</servlet-name>
     	<url-pattern>/faces/*</url-pattern>
    	 </servlet-mapping>
     <session-config>
     	<session-timeout>
     		30
     	</session-timeout>
     </session-config>
     <welcome-file-list>
     	<welcome-file>faces/index.xhtml</welcome-file>
     </welcome-file-list>
    </web-app>
    
  10. index.xhtml
  11. success.xhtml
  12. Download the project here.
    recaptchatest

Comments

Leave a Comment