使用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>
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05