AJAX实现验证码刷新和判断验证码正误

`JAVA验证码实现刷新功能,并通过ajax技术异步判断验证码正误

接上一个博客,对验证码进行刷新,使用ajax技术。

前端代码如下:
通过点击超链接“看不清?换一张”进行验证码的更换

<div class="form-group">
                <label>验证码</label>
                <span id="msgVerify" style="color: red"></span>
                <input type="text" class="form-control" autocomplete="off" id="verify" name="verify"
                       placeholder="请输入验证码" required oninvalid="setCustomValidity('请输入验证码');" oninput="setCustomValidity('');">
                <img src="/VerifyPic" id="verify-pic" class="mg">
                <a href="" id="rest">看不清?换一张</a>
                <br>
            </div>

记得要在注册页面导入jQuery的 js包

获取超链接id的点击事件,然后进行后台的更换代码操作,传过去随机值作为颜色的值

$(function () {
    //刷新验证码
    $("#rest").click(function () {
        //更换src的值使验证码重新加载
        $(this).attr("src",  "/VerifyPic?"+Math.random())
    })

通过ajax技术将前端页面输入的验证码传到 /AjaxCheckVerify的servlet进行正误判断,后台会传回json字符串

//询问后台验证码是否输入正确
    $("#verify").blur(function () {
        var verify=$("#verify").val();
        //发送ajax请求
        if(verify != "" && verify!=undefined) {
            $.get("/AjaxCheckVerify", {"verify": verify}, function (resp) {
                var result = JSON.parse(resp);
                if (result.verifyCorrect == "false") {
                    $("#verify").css('borderColor','red');
                    $("#msgVerify").html("验证码输入错误!");
                }
            })
        }
    })

/AjaxCheckVerify的servlet的代码如下:


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/AjaxCheckVerify")
public class AjaxCheckVerify extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        request.getSession().setAttribute("regUser",request.getParameter("user"));
        request.getSession().setAttribute("regPwd",request.getParameter("password"));
        request.getSession().setAttribute("regName",request.getParameter("name"));
        request.getSession().setAttribute("regVerify",request.getParameter("verify"));

        String verify = request.getParameter("verify");
        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute("verifyCode");
        if(verifyCode.equalsIgnoreCase(verify)){
            response.getWriter().println("{" + '"' + "verifyCorrect" + '"' + ":" + '"' + "true" + '"' + "}");
        }else {
            response.getWriter().println("{" + '"' + "verifyCorrect" + '"' + ":" + '"' + "false" + '"' + "}");
        }
    }
}

匿名

发表评论

匿名网友