使用AJAX验证JSP页面中的Captcha

时间:2015-12-07 11:31:12

标签: javascript java jquery ajax

尝试在我的JSP页面中使用Captcha,如下所示

<%@ page import="net.tanesha.recaptcha.ReCaptcha" %>
<%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
<html>
<head>
<title>Sample Application JSP Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>

<body bgcolor=white>
<form action="CaptchaServlet">
<table border="0" cellpadding="10">
<tr>
<td width="10" align="center" height="10">
<img src="SimpleServletPath">
</td>
<td>
<h1>Sample Application JSP Page</h1>
</td>
</tr>
<tr>
<td>
Please Enter your Comments
<p>
<%
ReCaptcha c = ReCaptchaFactory.newReCaptcha   
("6LdlHOsSAAAAAM8ypy8W2KXvgMtY2dFsiQT3HVq-    ", "6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY", false);
out.print(c.createRecaptchaHtml(null, null));
%>
<INPUT TYPE="TEXT" NAME="text1">
<input type="submit" value="submit" />
</p>  
</td>
</tr>
</table>

</form>
</body>
</html> 

servlet如下

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

    String remoteAddr = request.getRemoteAddr();
    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPrivateKey("6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY");

    String challenge = request.getParameter("recaptcha_challenge_field");
    String uresponse = request.getParameter("recaptcha_response_field");
    ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
    PrintWriter out= response.getWriter();
    if (reCaptchaResponse.isValid()) {
        String user = request.getParameter("user");
        out.write("CAPTCHA Validation Success! User "+user+" registered.");
    } else {
        out.write("CAPTCHA Validation Failed! Try Again.");
    }   
}

这很好用,但单击提交值时会刷新JSP页面。我们如何使用AJAX将Captcha值传递给Servlet,并在不刷新页面的情况下返回Capcha有效或无效的值。

1 个答案:

答案 0 :(得分:1)

这是策略。

通过javascript方法跟踪您的提交。该方法将验证码数据发送到服务器。并且在成功或错误时,javascript将使用服务器/ Servlet发送的错误消息更新dom。

请点击此链接https://gist.github.com/madan712/4972634

在上面的链接中,它使用另一个jsp进行验证(像servlet一样工作)但你可以在url中给出url映射名称:[your_servlet_path]