Javascript 使用AJAX在JSP页面中验证验证码

Javascript 使用AJAX在JSP页面中验证验证码,javascript,java,jquery,ajax,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-equi

尝试在我的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> 
这很好,但是当单击submit值时,JSP页面会被刷新。我们如何使用AJAX将Captcha值传递给Servlet,并在不刷新页面的情况下返回Capcha有效或无效的值。

以下是策略

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

点击这个链接


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

@Rehan,然后您应该接受我的答案,单击勾号,这是一个好的做法
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.");
    }   
}