作用:模拟获取验证码,10s后,重新获取。未过期前不可重复获取;
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%//获取随机短信 --不使用了Random r = new Random();StringBuilder sb = new StringBuilder();for(int i=0;i<=5;i++){int s = r.nextInt(10);sb.append(s);}%><!DOCTYPE HTML>
<html><head><title>短信验证码</title><script src="mobile/jquery-1.4.3.min.js" charset="utf-8"></script><link rel="stylesheet" href="mobile/mobile.css"><script type="text/javascript">$(function(){var code = 0;var flag = false;var get = false;$('#get').click(function(){if(flag)return;//未过期 不可再获取sendSmsCode();});function sendSmsCode(){//url:'getSms', 也可以//因为存在 异步执行的问题 所以 在ajax成功后,再设置某些值$.ajax({type : "POST",url : '<%=path%>/getSms',data : {method:"getSmsCode"},dataType : "json",success : function(data) {code = data;$('#code').html('验证码为:'+code);$('#get').attr('disabled','true');flag = true;get = true;time();},error : function(data) {$('#code').html("对不起服务器繁忙,请稍后再试!");}});}function time(){var t = 10;var time = window.setInterval(function(){t--;$('#get').val(t+'秒后失效');if(t==0){$('#code').html('验证码已失效,请重新获取!');$('#get').val('获取验证码');$('#get').removeAttr('disabled');flag = false;send = false;clearInterval(time);} },1000);}$('#in').click(function(){if(!get) {alert('请获取短信验证码!');return;}if(!flag) {alert('短信验证码已失效!');return;}var rs = $('input[name="sms"]').val();if(rs.length==0){alert('请输入短信验证码!');return;}if(rs != code){alert('短信验证码错误!');}else{alert('正确!');}});});</script></head><body><div><br/><h3 style="margin-left:110px">短信验证码 倒计时重新获取</h3></br><span style="margin-left:100px;font-weight:bold;color:red">短信验证码:</span> <input type="text" style="margin-left:0px;width:85px;font-weight:bold;" name="sms" placeholder="请输入验证码"/><input type="button" style="height:30px;width:90px;color:blue;font-weight:bold;margin-left:10px" id="get" value="获取验证码"/><br/><span id="code" style="margin-left:150px;color:red"></span><br/></div><br/><input type="button" style="margin-left:130px;height:30px;width:200px;color:blue;font-weight:bold" value="确定并提交" id="in"/></body>
</html>
后台随机产生验证码:
public class SmsService extends HttpServlet {private static final long serialVersionUID = 5846536395092919495L;@Overridepublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");String param = request.getParameter("method");System.out.println("================");System.out.println("param="+param);System.out.println("================");Random r = new Random();StringBuilder sb = new StringBuilder();for(int i=0;i<=5;i++){int s = r.nextInt(10);sb.append(s);}System.out.println("短信验证码 :"+sb);PrintWriter pw = response.getWriter();pw.write(sb.toString());pw.flush();pw.close();}}
效果示意--
Java技术圆桌会-微信群,欢迎大家的加入,专注技术讨论和学习。
加入的同学可以先加我微信:surwen0988 备注-圆桌会,然后拉你进群。