使用ajax实现验证码
java后台的servlet:
1 @WebServlet(value = "/login.love",name = "AjaxLoginServlet") 2 public class AjaxLoginServlet extends HttpServlet { 3 4 @Override 5 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 6 super.doPost(req, resp); 7 } 8 9 @Override 10 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 11 12 ResultMsg rm=new ResultMsg(); 13 PrintWriter out=resp.getWriter(); 14 Gson gson=new Gson(); 15 16 //1 获取前台来的验证码 17 //2 获取session里面的验证码 18 //3 校验 19 20 String vcode=req.getParameter("vcode"); 21 String code= (String) req.getSession().getAttribute("code"); 22 23 if (null==vcode||null==code){ 24 rm.setResult("0002"); 25 rm.getMsg("验证码为空"); 26 27 out.println(gson.toJson(rm)); 28 return; 29 } 30 if (vcode.equalsIgnoreCase(code)){ 31 rm.setResult("0000"); 32 out.println(gson.toJson(rm)); 33 }else { 34 rm.setResult("0001"); 35 rm.getMsg("验证码错误"); 36 out.println(gson.toJson(rm)); 37 } 38 39 40 }
前端的jsp:
1 <!-- 提交的方式; get post --> 2 3 4 <form action="login.love" method="post"> 5 6 <!-- name : 对应我们servlet去获取前台文本框的值的 key --> 7 用户名:<input id="nm" name="userName" type="text" value="${userName}" /> 8 密码:<input name="userPass" type="password" /> 9 验证码:<input id="vcode" name="vcode" type="text"><img id="img1" alt="" src="image.do" onclick="flash(this)"> 10 11 <!-- 默认是submit; --> 12 <button type="button" onclick="login()">登录</button> 13 14 <label id="lab1"></label> 15 16 </form> 17 </body> 18 <script type="text/javascript"> 19 20 function login(){ 21 var xhr=XMLHttpRequest(); 22 xhr.open("POST","login.love",true); 23 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 24 xhr.send("vcode="+document.getElementById("vcode").value); 25 26 xhr.onreadystatechange=function () { 27 28 //请求成功 29 if (xhr.readyState==4&&xhr.status==200){ 30 var obj=JSON.parse(xhr.responseText); 31 32 if (obj.result=="0000"){ 33 alert("验证码正确"); 34 } else if(obj.result=="0002"){ 35 alert("验证码为空") 36 flash(document.getElementById("img1")) 37 }else { 38 alert("验证码错误"); 39 flash(document.getElementById("img1")); 40 } 41 } 42 } 43 } 44 function flash(obj){ 45 obj.src = "code.do?"+Math.random(); 46 console.info(obj.src); 47 } 48 </script>