使用ajax实现验证码

java后台的servlet:

@WebServlet(value = "/login.love",name = "AjaxLoginServlet")
public class AjaxLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ResultMsg rm=new ResultMsg();
        PrintWriter out=resp.getWriter();
        Gson gson=new Gson();

        //1 获取前台来的验证码
        //2 获取session里面的验证码
        //3 校验

        String vcode=req.getParameter("vcode");
        String code= (String) req.getSession().getAttribute("code");

        if (null==vcode||null==code){
            rm.setResult("0002");
            rm.getMsg("验证码为空");

            out.println(gson.toJson(rm));
            return;
        }
        if (vcode.equalsIgnoreCase(code)){
            rm.setResult("0000");
            out.println(gson.toJson(rm));
        }else {
            rm.setResult("0001");
            rm.getMsg("验证码错误");
            out.println(gson.toJson(rm));
        }


    }

前端的jsp:

<!-- 提交的方式; get  post -->


    <form action="login.love" method="post">

        <!-- name : 对应我们servlet去获取前台文本框的值的 key -->
        用户名:<input id="nm" name="userName" type="text" value="${userName}" /> 
        密码:<input name="userPass" type="password" />
        验证码:<input id="vcode" name="vcode" type="text"><img id="img1"  alt="" src="image.do" onclick="flash(this)">

        <!-- 默认是submit; -->
        <button type="button" onclick="login()">登录</button>

        <label id="lab1"></label>

    </form>
</body>
<script type="text/javascript">

    function login(){
        var  xhr=XMLHttpRequest();
        xhr.open("POST","login.love",true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send("vcode="+document.getElementById("vcode").value);
        
        xhr.onreadystatechange=function () {
            
            //请求成功
            if (xhr.readyState==4&&xhr.status==200){
                var  obj=JSON.parse(xhr.responseText);
                
                if (obj.result=="0000"){
                    alert("验证码正确");
                } else if(obj.result=="0002"){
                    alert("验证码为空")
                    flash(document.getElementById("img1"))
                }else {
                    alert("验证码错误");
                    flash(document.getElementById("img1"));
                }
            } 
        }
    }
    function flash(obj){
        obj.src = "code.do?"+Math.random();
        console.info(obj.src);
    }
</script>

 使用ajax实现验证码

相关推荐