티스토리 뷰
1. 구글 리캡차 api key 발급
https://www.google.com/recaptcha/admin#list
label : 이름
domain : URL입력 (로컬이라면 localhost 입력)
owner : 소유자 이메일
발급받은 후 sitekey, secretkey 복사
2. 메이븐 의존성 주입
<dependency>
<groupId>net.tanesha.recaptcha4j</groupId>
<artifactId>recaptcha4j</artifactId>
<version>0.0.7</version>
</dependency>
3. jsp 엘리먼트 작성
<html> <head> <title>reCAPTCHA demo: Simple page</title> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </head> <body> <form action="?" method="POST"> <div class="g-recaptcha" data-sitekey="${siteKey}"></div> <br/> <input type="submit" value="Submit"> </form> </body> </html>
siteKey는 발급받은 것 적으면 됨
4. 자바스크립트 메서드 작성(본인은 ajax 처리)
$.ajax({ url : '/member/captchaAjax', type : 'post', data : { recaptcha : document.getElementById("g-recaptcha-response").value }, success : function(data){ //성공여부 } });
5. 리캡차 인증 코드 소스 작성
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"; private final static String USER_AGENT = "Mozilla/5.0"; private static String secret = ""; //local public static void setSecretKey(String key){ secret = key; } 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. ajax controller 메서드 구현부 작성
VerifyRecaptcha.setSecretKey(secretKey); //secretKey 세팅 String gRecaptchaResponse = request.getParameter("recaptcha"); //recapcha 파라미터 가져오기 boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse); //리캡챠 인증 true,false 설공 실패 리턴 String result = "fail"; if(verify){ result = "success"; }
ModelAndView view = new ModelAndView(); view.addObject("result",result); view.setViewName("jsonView"); return view;
'SPRING > 정리' 카테고리의 다른 글
요청 파라미터 바인딩 (0) | 2016.04.27 |
---|---|
JUnit 테스트 (0) | 2016.04.22 |
@ControllerAdvice로 전역 예외 관리하기 (0) | 2016.01.15 |
PROFILE 기능으로 서버설정과 로컬 설정을 구분하여 사용하기. (0) | 2016.01.14 |
객체검증 @Valid 사용하기 (0) | 2015.12.05 |