验证码实现代码(全)
注册登陆界面验证码的作用及代码实现
注册登陆界⾯验证码的作⽤及代码实现简介:验证码的作⽤:主要是为了有效防⽌机器恶意注册,对某⼀个特定已注册⽤户⽤特定程序暴⼒破解⽅式进⾏不断的登陆尝试。
验证码是现在很多⽹站注册/登录时必填的,虽然对⽤户可能有点⿇烦,但是对⽹站/社区来说这个功能还是很有必要,也很重要,不少⽹站为了防⽌⽤户利⽤机器⼈⾃动注册、登录、灌⽔,都采⽤了验证码技术。
所谓验证码,就是将⼀串随机产⽣的数字或符号,⽣成⼀幅图⽚,图⽚⾥加上⼀些⼲扰象素(防⽌OCR),由⽤户⾁眼识别其中的验证码信息,输⼊表单提交⽹站验证,验证成功后才能使⽤某项功能。
在这⾥想要提醒⼤家要保护⾃⼰的密码,尽量使⽤混杂了数字、字母、符号在内的6位以上密码,不要使⽤诸如1234之类的简单密码或者与⽤户名相同、类似的密码。
任何时候在任何地⽅都不要随意设置密码,保护你⾃⼰的密码也是保护你⾃⼰,免得你的账号给⼈盗⽤给⾃⼰带来不必要的⿇烦。
常见的验证码:1.四位数字,随机的⼀数字字符串,最原始的验证码,验证作⽤⼏乎为零。
2.⽹站⽤户登录⽤的是GIF格式,⽬前常⽤的随机数字图⽚验证码。
图⽚上的字符⽐较中规中矩,验证作⽤⽐上⼀个好。
没有基本图形图像学知识的⼈,不可破!可惜读取它的程序,在CSDN使⽤它的第⼀天,好像就在论坛⾥发布了。
3.QQ⽹站⽤户登录⽤的是PNG格式,图⽚⽤的随机数字+随机⼤写英⽂字母,整个构图有点张扬,每刷新⼀次,每个字符还会变位置呢!有时候出来的图⽚,⼈眼都识别不了,厉害啊…4.MS的申请时候的是, 随机数字+随机⼤写英⽂字母+随机⼲扰像素+随机位置。
5.的Gmail注册时候的是JPG格式,随机英⽂字母+随机颜⾊+随机位置+随机长度。
6,其他各⼤论坛的是XBM格式,内容随机。
实现代码:⽣成验证码图⽚(dlimage.jsp):1 <%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="UTF-8" %>2 2 <%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜⾊3 3 Random random = new Random();4 4 if (fc > 255)5 5 fc = 255;6 6 if (bc > 255)7 7 bc = 255;8 8 int r = fc + random.nextInt(bc - fc);9 9 int g = fc + random.nextInt(bc - fc);10 10 int b = fc + random.nextInt(bc - fc);11 11 return new Color(r, g, b);12 12 }%>13 13 <%14 14 //设置页⾯不缓存15 15 response.setHeader("Pragma", "No-cache");16 16 response.setHeader("Cache-Control", "no-cache");17 17 response.setDateHeader("Expires", 0);18 1819 19 // 在内存中创建图象20 20 int width = 75, height = 32;21 21 BufferedImage image = new BufferedImage(width, height,22 22 BufferedImage.TYPE_INT_RGB);23 2324 24 // 获取图形上下⽂25 25 Graphics g = image.getGraphics();26 2627 27 //⽣成随机类28 28 Random random = new Random();29 2930 30 // 设定背景⾊31 31 g.setColor(getRandColor(200, 250));32 32 g.fillRect(0, 0, width, height);33 3334 34 //设定字体35 35 g.setFont(new Font("Times New Roman", Font.BOLD, 18));//18是设置的字体⼤⼩36 3637 37 //画边框38 38 g.setColor(new Color(0, 0, 0));39 39 g.drawRect(0, 0, width - 1, height -1);// 细线围成的边框范围40 4041 41 // 随机产⽣155条⼲扰线,使图象中的认证码不易被其它程序探测到42 42 g.setColor(getRandColor(160, 200));43 43 for (int i = 0; i < 155; i++) {44 44 int x = random.nextInt(width);45 45 int y = random.nextInt(height);46 46 int xl = random.nextInt(12);47 47 int yl = random.nextInt(12);48 48 g.drawLine(x, y, x + xl, y + yl);49 49 }50 5051 51 // 取随机产⽣的认证码(4位数字)52 52 String sRand = "";53 53 for (int i = 0; i < 4; i++) {54 54 String rand = null;55 55 //随机⽣成数字或者字母56 56 if (random.nextInt(10) > 5) {57 57 rand = String.valueOf((char)(random58 58 .nextInt(10) + 48));59 59 } else {60 60 rand = String.valueOf((char)(random61 61 .nextInt(26) + 65));62 62 }63 63 sRand += rand;64 64 // 将认证码显⽰到图象中65 65 g.setColor(new Color(random.nextInt(80), random66 66 .nextInt(80), random.nextInt(80)));67 67 //调⽤函数出来的颜⾊相同,可能是因为种⼦太接近,所以只能直接⽣成68 68 g.drawString(rand, 15 * i + 10, 16);69 69 }70 7071 71 // 将认证码存⼊SESSION72 72 session.setAttribute("rand", sRand);73 7374 74 // 图象⽣效75 75 g.dispose();76 7677 77 // 输出图象到页⾯78 78 ImageIO.write(image, "JPEG", response.getOutputStream());79 79 %>在注册或登陆页⾯中引⽤⽣成的验证码图⽚:<!-- 验证码图⽚的⽣成--><img id="code" src="dlimage.jsp"/><a href="#" onclick="javascript:var dt=new Date();document.getElementById('code').src='dlimage.jsp?dt='+dt;"> <img alt="看不清,换⼀张"src="dlimages/1.png"/></a>(*区分字母⼤⼩写)检验验证码输⼊正确与否:<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %><html><head><title>注册出现问题</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="0"></head><body><%String rand = (String)session.getAttribute("rand");<!-系统随机产⽣的验证码-->String input = request.getParameter("rand");<!--⽤户输⼊的验证码--> if (input.equals(rand)){%><!-- 验证码正确的情况下 --><jsp:forward page="dl.jsp"/> <!-- 此处重定向到的页⾯可改为登录成功后可进⼊的页⾯ --><%} else {%>系统产⽣的验证码为: <%= rand %><br/>您输⼊的验证码为: <%= input %><br/><!--验证码错误情况下-->认证失败,请返回登录界⾯,重新输验证码!<br/><a href="dl.jsp">返回登录界⾯</a><%}%></body></html>。
vue实现登录时图形验证码
vue实现登录时图形验证码本⽂实例为⼤家分享了vue实现登录时图形验证码的具体代码,供⼤家参考,具体内容如下效果图:点击图案可以切换字符1.新建 Identify.vue 组件<template><div><canvasid="s-canvas":width="contentWidth":height="contentHeight"></canvas></div></template><script>export default {name: "identify",props: {identifyCode: {type: String,default: ''},fontSizeMin: {type: Number,default: 28},fontSizeMax: {type: Number,default: 40},backgroundColorMin: {type: Number,default: 180},backgroundColorMax: {type: Number,default: 240},colorMin: {type: Number,default: 50},colorMax: {type: Number,default: 160},lineColorMin: {type: Number,default: 40},lineColorMax: {type: Number,default: 180},dotColorMin: {type: Number,default: 0},dotColorMax: {type: Number,default: 255},contentWidth: {type: Number,default: 130},contentHeight: {type: Number,default: 40}},methods:{// ⽣成⼀个随机数randomNum (min, max) {return Math.floor(Math.random() * (max - min) + min)},// ⽣成⼀个随机的颜⾊randomColor (min, max) {let r = this.randomNum(min, max)let g = this.randomNum(min, max)let b = this.randomNum(min, max)return 'rgb(' + r + ',' + g + ',' + b + ')'},drawPic () {let canvas = document.getElementById('s-canvas')let ctx = canvas.getContext('2d')ctx.textBaseline = 'bottom'// 绘制背景ctx.fillStyle = this.randomColor(this.backgroundColorMin,this.backgroundColorMax)ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)// 绘制⽂字for (let i = 0; i < this.identifyCode.length; i++) {this.drawText(ctx, this.identifyCode[i], i)}this.drawLine(ctx)this.drawDot(ctx)},drawText (ctx, txt, i) {ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)ctx.font =this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei' let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))let y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)let deg = this.randomNum(-30, 30)// 修改坐标原点和旋转⾓度ctx.translate(x, y)ctx.rotate(deg * Math.PI / 270)ctx.fillText(txt, 0, 0)// 恢复坐标原点和旋转⾓度ctx.rotate(-deg * Math.PI / 270)ctx.translate(-x, -y)},drawLine (ctx) {// 绘制⼲扰线for (let i = 0; i < 2; i++) {ctx.strokeStyle = this.randomColor(this.lineColorMin,this.lineColorMax)ctx.beginPath()ctx.moveTo(this.randomNum(0, this.contentWidth),this.randomNum(0, this.contentHeight))ctx.lineTo(this.randomNum(0, this.contentWidth),this.randomNum(0, this.contentHeight))ctx.stroke()}},drawDot (ctx) {// 绘制⼲扰点for (let i = 0; i < 20; i++) {ctx.fillStyle = this.randomColor(0, 255)ctx.beginPath()ctx.arc(this.randomNum(0, this.contentWidth),this.randomNum(0, this.contentHeight),1,0,2 * Math.PI)ctx.fill()}}},watch: {identifyCode () {this.drawPic()}},mounted () {this.drawPic()}}</script><style lang="scss" scoped>#s-canvas {height: 38px;}</style>2.在⽗组件 index.vue注册使⽤<template><div @click="refreshCode" style="cursor: pointer;"><Identify :identifyCode="identifyCode" ></Identify></div></template><script>import Identify from '@/components/test/identify'export default {name: "index",components:{Identify},data(){return {identifyCode: '',// 验证码规则identifyCodes: '123456789ABCDEFGHGKMNPQRSTUVWXYZ',}},methods:{// 切换验证码refreshCode() {this.identifyCode = ''this.makeCode(this.identifyCodes, 4)console.log(this.identifyCode)},// ⽣成随机验证码makeCode(o, l) {for (let i = 0; i<l; i++) {this.identifyCode += this.identifyCodes[Math.floor(Math.random() * (this.identifyCodes.length - 0) + 0)]}},mounted() {this.refreshCode()}}</script><style scoped></style>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
php手机短信验证代码(共9篇)
php手机短信验证代码(共9篇)篇一:短信验证码PHP代码篇二:用维泰SDK实现发送短信验证码php源码phprequire "httprequest.php";/*' 该示范程序通过:88/ 发送短信''返回值:'返回值大于0表示成功,小于0表示失败。
如果失败,返回信息还包括失败原因的文字描述。
'说明:'返回成功仅表示服务器已经成功接收客户提交的任务,并不表示对方已经收到短信。
'因移动公司对短信内容审核严格,如测试未收到,请及时联系客服'请不要发送"测试","你好","abc"等无意义的内容*/function smsend($strMobile,$strText){//发送短信的服务器地址$strServerURL = ":88/cgi/sendsmsbatch.asp";// 短信账号:免费申请,如有问题请联系QQ732055019// :88/mis/user_reg_form.asp?interest=sms.api $strUser= "username";// 验证密码: 初始密码由平台通过短信发送, 用户可登录平台自己修改$strPass= "userpass";if($strUser==""){echo ("短信帐号没有设定!");return;}if($strPass==""){echo ("短信验证密码没有设定!");return;}if($strMobile==""){echo ("短信接收号码无效!");return;}if($strText=="undefined|| $strText==""){echo ("短信内容不能为空!");return;}if(strlen($strText)69){echo ("短信内容不能超过69个字");return;}//准备表单:使用urlencode对参数进行编码,字符集gb2312 $strForm = "User=. urlencode($strUser);$strForm .= "&Pass=. urlencode($strPass);$strForm .= "&Mobile=. urlencode($strMobile);$strForm .= "&Text=. urlencode($strText);$h= new HttpRequest();$s= $h-request("GET",$strServerURL."?".$strFor m,"");if (strpos($s,"SUCCESS")===false){//出现错误echo ("短信通知发送失败!br.$s);}else {//发送成功echo("短信通知发送成功!");}}htmlheadtitle发送短信通知/titlemeta http-equiv="Content-Typecontent="text/html; charset=gb2312"/headbodybrdiv class="title1"发送短信通知/divdiv class="content1"$strMobile="132****9999";//接收短信的手机号码 $strText="Test SMS";//短信内容(不要超过69个字) smsend($strMobile,$strText);/div/body/htmlphp //httprequest.phpclass HttpRequest{var $_host;var $_uri;var $_port;var $_response;function parseURL($url){$req = $url;$pos = strpos($req, '://');$this-_protocol = strtolower(substr($req, 0, $pos));$req = substr($req, $pos+3);$pos = strpos($req, '/');if($pos === false)$pos = strlen($req);$host = substr($req, 0, $pos);if(strpos($host, ':') === false){$this-_host = $host;$this-_port = ($this-_protocol == 'https') ? 443 : 80;}else{list($this-_host, $this-_port) = explode(':', $host);}$this-_uri = substr($req, $pos);if($this-_uri == '')$this-_uri = '/';}function request($method , $url, $sPostData){$this-parseURL($url);$fp = pfsockopen( $this-_host, $this-_port, &$errno, &$errstr, 120); if( !$fp ) {echo "$errstr ($errno)br\n";return "";}if( strtoupper($method) == "GET"){fputs( $fp, "GET ".$this-_uri.HTTP/1.0\r\n"); }else if( strtoupper($method) == "POST) {fputs( $fp, "POST ".$this-_uri.HTTP/1.0\r\n"); }fputs( $fp, "Accept: */*\n");fputs( $fp, "Host: ".$this-_host."\r\n");fputs( $fp, "Connection: Close\r\n");if( strtoupper($method) == "POST) {$strlength = strlen( $data);fputs( $fp, "Content-type:application/x-www-form-urlencoded\r\n); fputs( $fp, "Content-length: ".$strlength."\r\n");fputs($fp, "\r\n");fputs( $fp, $data."\r\n");}else{fputs($fp, "\r\n");}$this-_response = "";while( !feof( $fp ) ) {$this-_response .= fgets( $fp, 4096);}fclose( $fp);$s = $this-getResponseBody();return $s;}function getResponse(){return $this-_response;}function getResponseBody(){$sKey = "\r\n\r\n";$pos = strpos($this-_response,$sKey);if($pos===false) return "";$str= substr($this-_response,$pos + 4);return $str;}}篇三:用免费短信验证码SDK实现手机注册验证功能用免费短信验证码SDK实现手机注册验证功能第一步获取短信SDK请到Mob官网下载最新版本的SDK,下载回来后解压,可以看到下面的文件结构:其中SMS_SDK.framework 为依赖库文件SMS_SDKDemo 为示例demo ,其中保存了短信SDK的演示项目代码。
Demo_登陆表单生成随机验证码(附所有源代码)
Demo_登陆表单⽣成随机验证码(附所有源代码)所实现的页⾯为:点击验证码后,会⽣成另⼀个验证码login.html<!DOCTYPE html><html><head><title>login.html</title><meta name="keywords" content="keyword1,keyword2,keyword3"><meta name="description" content="this is my page"><meta name="content-type" content="text/html; charset=Unicode"><!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript">function changeImg(obj){obj.src = "/WEB14/checkIMG?time="+new Date().getTime();}</script></head><body><form actiom="/WEB14/login" method="post">⽤户名:<input type="text" name="username"><br>密码:<input type="password" name="password"><br>验证码:<input type="text" name="username"><img onclick="changeImg(this)" src="/WEB14/checkIMG"><br><input type="submit" value="登陆"><br></form></body></html>CheckImgServlet.javapackage com.soar.checking;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** 验证码⽣成程序**/public class CheckImgServlet extends HttpServlet {// 集合中保存所有成语private List<String> words = new ArrayList<String>();@Overridepublic void init() throws ServletException {// 初始化阶段,读取new_words.txt// web⼯程中读取⽂件,必须使⽤绝对磁盘路径String path = getServletContext().getRealPath("/WEB-INF/new_words.txt");try {BufferedReader reader = new BufferedReader(new FileReader(path));String line;while ((line = reader.readLine()) != null) {words.add(line);}reader.close();} catch (IOException e) {e.printStackTrace();}}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 禁⽌缓存// response.setHeader("Cache-Control", "no-cache");// response.setHeader("Pragma", "no-cache");// response.setDateHeader("Expires", -1);int width = 120;int height = 30;// 步骤⼀绘制⼀张内存中图⽚BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);// 步骤⼆图⽚绘制背景颜⾊ ---通过绘图对象Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔 // 绘制任何图形之前都必须指定⼀个颜⾊graphics.setColor(getRandColor(200, 250));graphics.fillRect(0, 0, width, height);// 步骤三绘制边框graphics.setColor(Color.WHITE);graphics.drawRect(0, 0, width - 1, height - 1);// 步骤四四个随机数字Graphics2D graphics2d = (Graphics2D) graphics;// 设置输出字体graphics2d.setFont(new Font("宋体", Font.BOLD, 18));Random random = new Random();// ⽣成随机数int index = random.nextInt(words.size());String word = words.get(index);// 获得成语// 定义x坐标int x = 10;for (int i = 0; i < word.length(); i++) {// 随机颜⾊graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));// 旋转 -30 --- 30度int jiaodu = random.nextInt(60) - 30;// 换算弧度double theta = jiaodu * Math.PI / 180;// 获得字母数字char c = word.charAt(i);// 将c 输出到图⽚graphics2d.rotate(theta, x, 20);graphics2d.drawString(String.valueOf(c), x, 20);graphics2d.rotate(-theta, x, 20);x += 30;}// 将验证码内容保存sessionrequest.getSession().setAttribute("checkcode_session", word);// 步骤五绘制⼲扰线graphics.setColor(getRandColor(160, 200));int x1;int x2;int y1;int y2;for (int i = 0; i < 30; i++) {x1 = random.nextInt(width);x2 = random.nextInt(12);y1 = random.nextInt(height);y2 = random.nextInt(12);graphics.drawLine(x1, y1, x1 + x2, x2 + y2);}// 将上⾯图⽚输出到浏览器 ImageIOgraphics.dispose();// 释放资源//将图⽚写到response.getOutputStream()中ImageIO.write(bufferedImage, "jpg", response.getOutputStream());}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}/*** 取其某⼀范围的color** @param fc* int 范围参数1* @param bc* int 范围参数2* @return Color*/private Color getRandColor(int fc, int bc) {// 取其随机颜⾊Random random = new Random();if (fc > 255) {fc = 255;}if (bc > 255) {bc = 255;}int r = fc + random.nextInt(bc - fc);int g = fc + random.nextInt(bc - fc);int b = fc + random.nextInt(bc - fc);return new Color(r, g, b);}}。
微信小程序中短信验证码登录全流程及代码
微信⼩程序中短信验证码登录全流程及代码短信验证码实现流程1、构造⼿机验证码,⽣成⼀个6位的随机数字串;2、使⽤接⼝向短信平台发送⼿机号和验证码,然后短信平台再把验证码发送到制定⼿机号上3、将⼿机号验证码、操作时间存⼊Session,redis中,作为后⾯验证使⽤;4、接收⽤户填写的验证码、⼿机号及其他注册数据;5、对⽐提交的验证码与Session,redis中的验证码是否⼀致,同时判断提交动作是否在有效期内;6、验证码正确且在有效期内,请求通过,处理相应的业务。
package com.foen.utils;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;import monRequest;import monResponse;import com.aliyuncs.DefaultAcsClient;import com.aliyuncs.IAcsClient;import com.aliyuncs.exceptions.ClientException;import com.aliyuncs.exceptions.ServerException;import com.aliyuncs.http.HttpRequest;import com.aliyuncs.http.MethodType;import com.aliyuncs.profile.DefaultProfile;import com.foen.car.dto.BaseResultDto;import com.foen.car.service.RedisService;import ng.StringUtils;import org.apache.shiro.SecurityUtils;import org.apache.shiro.session.Session;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;/*** ⼿机短信通信类* @auther: 作者 gzh* @description: 类说明* @Date: created in 9:45 2020/5/27*/public class MoblieMessageUtil {private static final Logger logger = LoggerFactory.getLogger(MoblieMessageUtil.class);// 产品名称:云通信短信API产品,开发者⽆需替换private static final String product = "Dysmsapi";private static final String domain = "";// 此处需要替换成开发者⾃⼰的AK(在阿⾥云访问控制台寻找)private static String accessKeyId = "---";private static String accessKeySecret = "---";private static String signName = "--";private static String identifyingTempleteCode = "{\"code\":\"1111\"}";private static String registTempleteCode = "---";public static BaseResultDto sendSmsCode(String tel, String code, HttpServletRequest httpServletRequest) {BaseResultDto baseResultDto = Utils.baseDefaultResultMessageError();DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain("");request.setSysVersion("2017-05-25");request.setSysAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", tel);request.putQueryParameter("SignName", signName);request.putQueryParameter("TemplateCode", registTempleteCode);request.putQueryParameter("TemplateParam","{\"code\":"+code+"}" );request.putQueryParameter("SmsUpExtendCode", code);try {CommonResponse response = client.getCommonResponse(request);("==>"+response.getData());if(response.getData().indexOf("OK")!=-1){baseResultDto=Utils.renderBaseResultDtoSuccess("短信发送成功");}else{baseResultDto=Utils.renderBaseResultDtoError(response.getData());}} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}return baseResultDto;}/*** 保存数据到session* @param request* @param code* @param phone*/private static void setSendSmsCode(HttpServletRequest request,String code,String phone){ Session session = SecurityUtils.getSubject().getSession();session.setAttribute(Constants.CRM_STR+phone, code);try {final Timer timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {String yxcode1 = (String) session.getAttribute(Constants.CRM_STR+phone);if(StringUtils.isNotEmpty(yxcode1)){session.removeAttribute(Constants.CRM_STR+phone);}timer.cancel();}},Constants.SIGN_EXPIRED_TIME);} catch (Exception e) {e.printStackTrace();}}public static void setRegistData(RedisService service, String phone, String code){service.setValue(Constants.CRM_STR+phone,code);service.setValue(Constants.CRM_TIME+phone,DateUtils.dateToStringFromat());try {//TimerTask实现5分钟后从session.resdis中删除checkCodefinal Timer timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {String phone_ = service.getValue(Constants.CRM_STR+phone);String vcode_ = service.getValue(Constants.CRM_TIME+phone);if(StringUtils.isNotEmpty(phone_)){service.delete(Constants.CRM_STR+phone);}if(StringUtils.isNotEmpty(vcode_)){service.delete(Constants.CRM_TIME+phone);}timer.cancel();}},Constants.SIGN_EXPIRED_TIME);} catch (Exception e) {e.printStackTrace();}}}短信通信类短信验证码实现流程1、构造⼿机验证码,⽣成⼀个6位的随机数字串;2、使⽤接⼝向短信平台发送⼿机号和验证码,然后短信平台再把验证码发送到制定⼿机号上3、将⼿机号验证码、操作时间存⼊Session,redis中,作为后⾯验证使⽤;4、接收⽤户填写的验证码、⼿机号及其他注册数据;5、对⽐提交的验证码与Session,redis中的验证码是否⼀致,同时判断提交动作是否在有效期内;6、验证码正确且在有效期内,请求通过,处理相应的业务。
验证码的实现(C# WinForm)
《企业信息化项目开发》上机内容验证码的实现(C# WinForm)一、实训目标1.验证码的概念2.绘制验证码二、涉及知识点1.验证码在程序中有着重要的作用,它通常用于判定程序或者网站页面的刷新,防止通过特殊工具恶意登录或注册信息。
2.验证码的编写主要使用GDI+技术。
预先引用命名空间:System.Drawing.Drawing2D;三、实训内容验证码的实现(80分钟)四、实训步骤从下面(一)或(二)中选择任意一种验证码实现功能:(一)简单验证码的实现1.新建一个窗口项目,添加控件:PictureBox、TextBox、Button,其中PictureBox用于显示验证码,文本框用于填入字符串,按钮用于判定验证码的正确性。
2.在项目中添加一个类“VerifyCodeImgSimple.cs”,该类中要实现的方法有2个:这两个方法的实现代码如下:3.在主窗口中添加如下事件代码:(1)在窗体中定义一个全局变量:(2)定义刷新验证码方法:(3)窗口事件及其调用代码:(二)常规验证码的实现(实现起来更难)1.窗口设计跟上述一样,添加控件:PictureBox、TextBox、Button。
2.在项目中添加一个类“VerifyCodeImg.cs”,该类包括如下字段、属性和方法:方法的实现代码如下:(1)构造方法:(2)生成英文或数字字符:(3)生成汉子字符:(4)生成默认长度5的随机字符码:(5)生成随机字符码(重载):(6)生成校验码图片:3.在主窗口中添加如下事件代码:(1)在窗体中定义如下全局变量:(2)定义刷新验证码方法:(3)窗口事件及其调用代码:五、课后作业预习存储过程的使用。
一步步实现滑动验证码(拼图验证码),Java图片处理关键代码
⼀步步实现滑动验证码(拼图验证码),Java图⽚处理关键代码 最近滑动验证码在很多⽹站逐步流⾏起来,⼀⽅⾯对⽤户体验来说,⽐较新颖,操作简单,另⼀⽅⾯相对图形验证码来说,安全性并没有很⼤的降低。
当然到⽬前为⽌,没有绝对的安全验证,只是不断增加攻击者的绕过成本。
接下来分析下滑动验证码的核⼼流程:1. 后端随机⽣成抠图和带有抠图阴影的背景图⽚,后台保存随机抠图位置坐标2. 前端实现滑动交互,将抠图拼在抠图阴影之上,获取到⽤户滑动距离值,⽐如以下⽰例3. 前端将⽤户滑动距离值传⼊后端,后端校验误差是否在容许范围内。
这⾥单纯校验⽤户滑动距离是最基本的校验,出于更⾼的安全考虑,可能还会考虑⽤户滑动的整个轨迹,⽤户在当前页⾯的访问⾏为等。
这些可以很复杂,甚⾄借助到⽤户⾏为数据分析模型,最终的⽬标都是增加⾮法的模拟和绕过的难度。
这些有机会可以再归纳总结常⽤到的⽅法,本⽂重点集中在如何基于Java来⼀步步实现滑动验证码的⽣成。
可以看到,滑动图形验证码,重要有两个图⽚组成,抠块和带有抠块阴影的原图,这⾥⾯有两个重要特性保证被暴⼒破解的难度:抠块的形状随机和抠块所在原图的位置随机。
这样就可以在有限的图集中制造出随机的、⽆规律可寻的抠图和原图的配对。
⽤代码如何从⼀张⼤图中抠出⼀个有特定随机形状的⼩图呢?第⼀步,先确定⼀个抠出图的轮廓,⽅便后续真正开始执⾏图⽚处理操作图⽚是有像素组成,每个像素点对应⼀种颜⾊,颜⾊可以⽤RGB形式表⽰,外加⼀个透明度,把⼀张图理解成⼀个平⾯图形,左上⾓为原点,向右x轴,向下y轴,⼀个坐标值对应该位置像素点的颜⾊,这样就可以把⼀张图转换成⼀个⼆维数组。
基于这个考虑,轮廓也⽤⼆维数组来表⽰,轮廓内元素值为1,轮廓外元素值对应0。
这时候就要想这个轮廓形状怎么⽣成了。
有坐标系、有矩形、有圆形,没错,⽤到数学的图形函数。
典型⽤到⼀个圆的函数⽅程和矩形的边线的函数,类似:(x-a)²+(y-b)²=r²中,有三个参数a、b、r,即圆⼼坐标为(a,b),半径r。
Unity利用SMSSDK实现短信验证码(附代码)
Unity利⽤SMSSDK实现短信验证码(附代码)最近⼀直在研究如何给app更多实⽤性的功能,在app进⾏登录或者注册时,为了⽅便⽤户更加快捷的完成登录功能,所以就决定采⽤短信验证码的⽅式进⾏验证登录。
在学习的过程中,先使⽤了Mob的短信服务进⾏短信验证,因为他是免费的,⽽且不需要提交什么材料(单纯为了测试),后期加⼊到项⽬中的话,还是需要去创建⾃⼰的签名和短信模板,先拿Mob练练⼿,后期在项⽬中还是会使⽤阿⾥云的短信服务,到时候实现了之后也会分享出来。
因为我这⾥只是做了⼀个简单的Demo,所以就没有必要去申请这些权限,其实申请的话很容易过的,只要上传⼀下公司的营业执照就好。
好了,废话不多说了,实现功能吧!需要先在Mob上有⼀个⾃⼰的账号,⽤⾃⼰的常⽤邮箱注册就好,然后进⼊到后台,创建⼀个⾃⼰的应⽤,随便取个名字就可以创建成功,创建成功后就可以拿到Appkey及Appsecret,这两个数据后⾯是需要⽤到的,有了这个就可以⾮常⽅便的看到后台的统计信息,然后再,因为都是开源项⽬,所以Mob的代码都是托管在git上的,然后将⾥⾯的Unity包导⼊到项⽬中。
我新建了⼀个⼯程来实现该功能,利⽤UGUI搭建了⼀个简易的收发验证码的界⾯。
接下来就是开始码代码了,新建⼀个测试脚本,并且继承且实现SMSSDKHandler接⼝,为了⽅便接收验证码发送的回调结果。
先申明SMSSDK变量,然后在Start中初始化,将先前创建的Appkey及App secret填⼊,第三个参数为是否warn,根据官⽹建议设置为false。
ssdk.init("292449f735890", "f1bee8045aac2e6cbb7c535a5277aa1c", false);ssdk.setHandler(this);接下来是实现短信验证码功能,特别需要注意的是第四个参数,它表⽰的短信模板,因为我们⼀开始是没有申请到短信模板的,因为Mob需要我们的应⽤中先利⽤他们sdk实现了短信验证码功能,提交的app才能通过审核。
随机验证码的代码实现方法
随机验证码的代码实现方法下面是一个使用 Python 生成随机验证码的示例代码:```pythonimport randomimport stringdef generate_random_code(length=6):# 定义所有可能的字符all_characters = string.ascii_letters + string.digits# 生成指定长度的随机验证码random_code = ''.join(random.choice(all_characters) for _ in range(length))return random_code# 生成一个随机验证码random_code = generate_random_code()print("随机验证码:", random_code)```在这个示例中,我们首先定义了一个`generate_random_code`函数,它接受一个可选的参数`length`,用于指定生成的随机验证码的长度。
默认情况下,生成的随机验证码的长度为 6 个字符。
在函数内部,我们使用`string.ascii_letters`表示所有的字母(包括大小写),`string.digits`表示所有的数字。
然后,我们使用`random.choice()`方法从所有可能的字符中随机选择字符,并使用循环生成指定长度的随机验证码。
最后,我们调用`generate_random_code`函数生成一个随机验证码,并将其打印输出。
你可以根据需要调整`length`参数的值来生成不同长度的随机验证码。
希望这个示例对你有所帮助!如果还有其他问题,请随时提问。
springboot+vue实现验证码功能
springboot+vue实现验证码功能本⽂实例为⼤家分享了springboot+vue实现验证码功能的具体代码,供⼤家参考,具体内容如下1.⼯具类直接⽤不⽤改package com.example.demo.Util;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.awt.*;import java.awt.image.BufferedImage;import java.util.HashMap;import java.util.Map;import java.util.Random;//import java.util.logging.Logger;public class CodeUtil {public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的keyprivate String randString = "0123456789";//随机产⽣只有数字的字符串 private String//private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产⽣只有字母的字符串//private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产⽣数字与字母组合的字符串 private int width = 95;// 图⽚宽private int height = 25;// 图⽚⾼private int lineSize = 40;// ⼲扰线数量private int stringNum = 4;// 随机产⽣字符数量private static final Logger logger = LoggerFactory.getLogger(CodeUtil.class);private Random random = new Random();/*** 获得字体*/private Font getFont() {return new Font("Fixedsys", Font.CENTER_BASELINE, 18);}/*** 获得颜⾊*/private Color getRandColor(int fc, int bc) {if (fc > 255)fc = 255;if (bc > 255)bc = 255;int r = fc + random.nextInt(bc - fc - 16);int g = fc + random.nextInt(bc - fc - 14);int b = fc + random.nextInt(bc - fc - 18);return new Color(r, g, b);}/*** ⽣成随机图⽚*/public void getRandcode(HttpServletRequest request, HttpServletResponse response) {HttpSession session = request.getSession();// BufferedImage类是具有缓冲区的Image类,Image类是⽤于描述图像信息的类BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);Graphics g = image.getGraphics();// 产⽣Image对象的Graphics对象,改对象可以在图像上进⾏各种绘制操作g.fillRect(0, 0, width, height);//图⽚⼤⼩g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体⼤⼩g.setColor(getRandColor(110, 133));//字体颜⾊// 绘制⼲扰线for (int i = 0; i <= lineSize; i++) {drowLine(g);}// 绘制随机字符String randomString = "";for (int i = 1; i <= stringNum; i++) {randomString = drowString(g, randomString, i);}(randomString);//将⽣成的随机字符串保存到session中session.removeAttribute(RANDOMCODEKEY);session.setAttribute(RANDOMCODEKEY, randomString);g.dispose();try {// 将内存中的图⽚通过流动形式输出到客户端ImageIO.write(image, "JPEG", response.getOutputStream());} catch (Exception e) {e.printStackTrace();// logger.error("将内存中的图⽚通过流动形式输出到客户端失败>>>> ", e);}}/*** 绘制字符串*/private String drowString(Graphics g, String randomString, int i) {g.setFont(getFont());g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));randomString += rand;g.translate(random.nextInt(3), random.nextInt(3));g.drawString(rand, 13 * i, 16);return randomString;}/*** 绘制⼲扰线*/private void drowLine(Graphics g) {int x = random.nextInt(width);int y = random.nextInt(height);int xl = random.nextInt(13);int yl = random.nextInt(15);g.drawLine(x, y, x + xl, y + yl);}/*** 获取随机的字符*/public String getRandomString(int num) {return String.valueOf(randString.charAt(num));}}2.Controller层要跨域!!@RestController@RequestMapping("/Code")public class CodeController {private final static Logger logger = LoggerFactory.getLogger(CodeController.class);/*** ⽣成验证码*/@GetMapping("getVerify")@CrossOrigin(origins = "*")// @RequestMapping(value = "/getVerify")public void getVerify(HttpServletRequest request, HttpServletResponse response) {try {response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图⽚response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容 response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expire", 0);CodeUtil randomValidateCode = new CodeUtil();randomValidateCode.getRandcode(request, response);//输出验证码图⽚⽅法} catch (Exception e) {e.printStackTrace();// logger.error("获取验证码失败>>>> ", e);}}/*** 校验验证码*/@RequestMapping(value = "/checkVerify",headers = "Accept=application/json")@CrossOrigin(origins = "*",allowCredentials="true")public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) { try{//从session中获取随机数String inputStr = verifyInput;String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY"); if (random == null) {return false;}if (random.equals(inputStr)) {return true;} else {return false;}}catch (Exception e){e.printStackTrace();// logger.error("验证码校验失败", e);return false;}}}3.前台vue⽅式:页⾯部分<template><div><el-row :gutter="0"><el-formref="elForm":model="formData":rules="rules"size="medium"label-width="83px"label-position="left"><img :src="imgUrl" alt="更换验证码" @click="getVerify(this)" /><el-col :span="6"><el-form-item label="验证码" prop="code"><el-inputv-model="formData.code"placeholder="请输⼊验证码"clearable:style="{ width: '100%' }"></el-input></el-form-item></el-col><el-col :span="24"><el-form-item size="large"><el-button type="primary" @click="aVerify()">提交</el-button><el-button @click="resetForm">重置</el-button></el-form-item></el-col></el-form></el-row></div></template>js部分:vue⽅法:data() {return {imgUrl: "/api/Code/getVerify",formData: {code: undefined,},rules: {code: [{required: true,message: "请输⼊验证码",trigger: "blur",},],},};},methods: {aVerify() {var that = this;var data = Qs.stringify({verifyInput: this.formData.code,});that.axios({method: "post",url: "/api/Code/checkVerify",data: data,}).then((response) => {console.log(response);if ( response.data) {alert("success!");} else {alert("failed!");}getVerify();});},getVerify(obj) {console.log(obj);// obj.src = "/api/Code/getVerify?" + Math.random();this.imgUrl = "/api/Code/getVerify?" + Math.random();},resetForm() {this.$refs["elForm"].resetFields();},},原⽣js⽅法:function getVerify(obj) {// obj.src = "/api/Code/getVerify"obj.src = "/api/Code/getVerify?" + Math.random(); //原⽣js⽅式console.log(obj.src);// this.imgCode= "/api/Code/getVerify?"+Math.random();}// function getVerify() {// // $("#imgCode").on("click", function() {// $("#imgVerify").attr("src", 'Code/getVerify?' + Math.random());//jquery⽅式// // });// }function aVerify() {var value = $("#verify_input").val();// alert(value);$.ajax({async: false,type: "post",url: "/api/Code/checkVerify",dataType: "json",data: {verifyInput: value,},success: function (result) {if (result) {alert("success!");} else {alert("failed!");}// window.location.reload();getVerify();},});}实际应⽤中:防⽌页⾯跳回不重新加载:imgUrl直接绑定随机数imgUrl: "/api/Code/getVerify?" + Math.random(),aVerify() {var that = this;var data = Qs.stringify({verifyInput: this.formData.code,});that.axios({method: "post",url: "/api/Code/checkVerify",data: data,}).then((response) => {console.log(response);this.result=response.data;console.log(this.result);if ( response.data) {this.submitForm();// alert("success!");} else {this.$message({type: "warning",message: "验证码错误",});this.getVerify();}// this.reload();});},getVerify() {console.log("hhhhh");// var timestmp = (new Date()).valueOf();// obj.src = "/api/Code/getVerify?" + Math.random();this.imgUrl = "/api/Code/getVerify?" + Math.random();// this.imgUrl = "/api/Code/getVerify?" + "&t=" +timestmp;},以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JavaScript实现页面动态验证码的实现示例
JavaScript实现页⾯动态验证码的实现⽰例引⾔:现在很多在⽤户登陆或注册的时候为了防⽌程序攻击,加⼊了动态验证的技术,⼀般是让⽤户输⼊随即⽣成的验证码来实现。
我⾃⼰写了⼀个没有跟后台交互的,就在前端验证,发出来给⼤家看看。
效果图:实现思路:把数字和字母放到⼀个数组中,通过随机的⽅式取得数组下标,总共取4个组成验证码;把验证码渲染出来(⼀个⼀个的渲染);绘制⼀定数量的⼲扰线,随机颜⾊;输⼊验证码,输⼊4位以后去验证,正确显⽰钩,错误显⽰叉并且刷新验证码。
编写构造函数⽂本构造函数//⽂字的构造函数function Text(o){this.x=0,//x坐标this.y=0,//y坐标this.text='',//内容this.font=null;//字体this.textAlign=null;//对齐⽅式this.init(o);}Text.prototype.init=function(o){for(var key in o){this[key]=o[key];}}Text.prototype.render=function(context){this.ctx=context;innerRender(this);function innerRender(obj){var ctx=obj.ctx;ctx.save()ctx.beginPath();ctx.translate(obj.x,obj.y);if(obj.font){ctx.font=obj.font;}if(obj.textAlign){ctx.textAlign=obj.textAlign;}if(obj.fill){//是否填充obj.fillStyle?(ctx.fillStyle=obj.fillStyle):null;ctx.fillText(obj.text,0,0);}ctx.restore();}return this;}线段构造函数//直线的构造function Line(ctx,o){this.x=0,//x坐标this.y=0,//y坐标this.startX=0,//开始点x位置this.startY=0, //开始点y位置this.endX=0,//结束点x位置this.endY=0;//结束点y位置this.thin=false;//设置变细系数this.ctx=ctx;this.init(o);}Line.prototype.init=function(o){for(var key in o){this[key]=o[key];}}Line.prototype.render=function(){innerRender(this);function innerRender(obj){var ctx=obj.ctx;ctx.save()ctx.beginPath();ctx.translate(obj.x,obj.y);if(obj.thin){ctx.translate(0.5,0.5);}if(obj.lineWidth){//设定线宽ctx.lineWidth=obj.lineWidth;if(obj.strokeStyle){ctx.strokeStyle=obj.strokeStyle;}//划线ctx.moveTo(obj.startX, obj.startY);ctx.lineTo(obj.endX, obj.endY);ctx.stroke();ctx.restore();}return this;}按长度获取验证码//根据指定长度⽣成随机字母数字Verifiable.prototype.randomWord=function(range){var str = "",pos,arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; for(var i=0; i<range; i++){pos = Math.round(Math.random() * (arr.length-1));str += arr[pos];}return str;}绘制⽂字//绘制⽂字Verifiable.prototype.drawText=function(){var that=this;var count = 4;//⽂字个数var textW = 40;//⽂字所占宽var code=this.code = this.randomWord(count);var codeArr = code.split("");var text,x ;codeArr.forEach(function(c,i){x = that.w/count*i+textW/2;//绘制⽂字text = new Text({x:x,y:textW-10,text:c,font:'30px ans-serif',textAlign:'center',fill:true,fillStyle:'#412D6A'});that.renderArr.push(text);})}此时效果:绘制⼲扰线//绘制⼲扰线Verifiable.prototype.interfering=function(){var count = this.lineCount=20,line,ctx=this.ctx;var startX,startY,endX,endY,color;for(var i=0;i<count;i++){//随机开始坐标,结束坐标、颜⾊startX = _.getRandom(0,140);startY = _.getRandom(0,40);endX = _.getRandom(0,140);endY = _.getRandom(0,40);color = _.getRandomColor();//定义⼀条直线line = new Line(ctx,{x:0,y:0,startX:startX,startY:startY,endX:endX,endY:endY,strokeStyle:color})this.renderArr.push(line);}}此时效果如下:加⼊页⾯布局<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><title>verifiable</title><style>width:140px;height:40px;position:absolute;}#inputDiv{width:220px;position:absolute;margin:0 auto;left:0;top:30px;right:0;bottom:0;}#container{width:220px;height:60px;position:absolute;margin:0 auto;left:0;top:60px;right:0;bottom:0;}.refresh{position:absolute;left:140px;}</style></head><body><div id='inputDiv'>验证码:<input size=10 id='codeInput'><img id='stateImg' style="vertical-align: middle;width:20px"></img></div><div id="container"><div id='box'></div><a href="javascript:void 0" class="refresh" onclick="refresh()">换⼀张</a></div></body><script type="text/javascript" src='verifiable.js'></script><script type="text/javascript">var box = document.getElementById('box');var stateImg = document.getElementById('stateImg');var codeInput = document.getElementById('codeInput');verifiable.init(box,codeInput,stateImg);//换⼀张function refresh(){verifiable.renderArr.length=0;verifiable.draw();}</script></html>加⼊输⼊框事件//输⼊框事件Verifiable.prototype.inputValid=function(input){var val = input.value;if(val.length<4) return ;if(this.code==val){console.log('suc');this.result(0);}else{this.result(1);}}加⼊成功、失败验证//处理结果Verifiable.prototype.result=function(result){var codeInput = this.codeInput;var stateImg = this.stateImg;if(result==0){//成功stateImg.src="./images/suc.jpeg";codeInput.readOnly=true;}else {//失败codeInput.readOnly=false;stateImg.src="./images/fail.jpeg";this.renderArr.length=0;this.draw();}}完成到此这篇关于JavaScript实现页⾯动态验证码的实现⽰例的⽂章就介绍到这了,更多相关JavaScript 动态验证码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
vue实现滑块验证码
vue实现滑块验证码图⼀为拖拽前效果,图⼆为拖拽后效果⼀、新建⽂件JcRange.vue,代码如下: 1、模板代码:1<template>2<div class="jc-component__range">3<div class="jc-range" :class="rangeStatus?'success':''">4<i @mousedown="rangeMove" :class="rangeStatus?successIcon:startIcon"></i>5 {{rangeStatus?successText:startText}}6</div>8</template> 2、js代码<script>export default {props: {// 成功之后的函数successFun: {type: Function},//成功图标successIcon: {type: String,default: 'el-icon-success'},//成功⽂字successText: {type: String,default: '验证成功'},//开始的图标startIcon: {type: String,default: 'el-icon-d-arrow-right'},//开始的⽂字startText: {type: String,default: '请拖住滑块,拖动到最右边'},//失败之后的函数errorFun: {type: Function},//或者⽤值来进⾏监听status: {type: String}},data(){return {disX : 0,rangeStatus: false}},methods:{//滑块移动rangeMove(e){let ele = e.target;let startX = e.clientX;let eleWidth = ele.offsetWidth;let parentWidth = ele.parentElement.offsetWidth;let MaxX = parentWidth - eleWidth;if(this.rangeStatus){//不运⾏return false;}document.onmousemove = (e) => {let endX = e.clientX;this.disX = endX - startX;if(this.disX<=0){this.disX = 0;}if(this.disX>=MaxX-eleWidth){//减去滑块的宽度,体验效果更好this.disX = MaxX;}ele.style.transition = '.1s all';ele.style.transform = 'translateX('+this.disX+'px)';e.preventDefault();}document.onmouseup = ()=> {if(this.disX !== MaxX){ele.style.transition = '.5s all';ele.style.transform = 'translateX(0)';//执⾏成功的函数this.errorFun && this.errorFun();}else{this.rangeStatus = true;if(this.status){this.$parent[this.status] = true;}//执⾏成功的函数this.successFun && this.successFun();document.onmousemove = null;document.onmouseup = null;}}}};</script> 3、css 代码(此处使⽤了sass)<style lang="scss" scoped>@mixin jc-flex{display: flex;justify-content: center;align-items: center;}.jc-component__range{.jc-range{background-color: #e9e9e9;position: relative;transition: 1s all;user-select: none;color: #585858;@include jc-flex;height: 50px; /*no*/&.success{background-color: #3bc923;color: #fff;i{color: #3bc923;}}i{position: absolute;left: 0;width: 50px;/*no*/height: 100%;color: #3fcd26;background-color: #fff;border: 1px solid #d8d8d8;cursor: pointer;font-size: 24px;@include jc-flex;}}}</style>⼆、引⽤⽅法(加上验证就可以了)<JcRange status="ruleForm.status":successFun="onMpanelSuccess":errorFun="onMpanelError"></JcRange> import JcRange from "@/components/common/JcRange.vue";status: [{ validator: checkStatus, trigger: "change" }]var checkStatus = (rule, value, callback) => {console.log(value);if (!value) {return callback(new Error("请拖动滑块完成验证"));} else {callback();}};转载⾃:。
登录验证码实现(Captcha)
登录验证码实现(Captcha)登录验证码登录验证是⼀般系统都会有的功能,验证的⽅式也多种多样,⽐如输⼊式验证码,拖动式验证条,拖动式验证拼图等等。
我们这⾥先实现常规的输⼊验证码的⽅式,右边显⽰验证码图⽚,点击可刷新,左边输⼊验证码。
如下图为实现的效果。
实现案例验证码的实现需要前后端协同,脱离彼此则不可⽤,故将前后端的实现放在⼀起,不再另写前端教程。
后端实现1.添加依赖打开 kitty-admin ⼯程,添加maven依赖。
pom.xml<!-- kaptcha --><dependency><groupId>com.github.axet</groupId><artifactId>kaptcha</artifactId><version>${kaptcha.version}</version></dependency>版本是 <kaptcha.version>0.0.9</kaptcha.version>2.添加配置添加验证码配置类 KaptchaConfig,配置验证码的⼀些样式。
KaptchaConfig.javapackage com.louis.kitty.admin.config;import java.util.Properties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.google.code.kaptcha.impl.DefaultKaptcha;import com.google.code.kaptcha.util.Config;/*** 验证码配置* @author Louis* @date Oct 29, 2018*/@Configurationpublic class KaptchaConfig {@Beanpublic DefaultKaptcha producer() {Properties properties = new Properties();properties.put("kaptcha.border", "no");properties.put("kaptcha.textproducer.font.color", "black");properties.put("kaptcha.textproducer.char.space", "5");Config config = new Config(properties);DefaultKaptcha defaultKaptcha = new DefaultKaptcha();defaultKaptcha.setConfig(config);return defaultKaptcha;}}3.添加验证码获取接⼝添加验证码获取接⼝,并将⽣成的验证码保存起来,在登录的时候⽤来跟前台输⼊验证码进⾏匹配。
springboot实现验证码功能
springboot实现验证码功能本⽂实例为⼤家分享了spring boot实现验证码功能的具体代码,供⼤家参考,具体内容如下流程是按照交互顺序。
1.controller层代码,获取验证码,以及⽣成验证码图⽚。
1.1获取html@RequestMapping(value="/authImage",method=RequestMethod.GET)public String authImage(){return "authImage";}1.2 html<!DOCTYPE html><html><head><title>验证码</title></head><body><table><tr><td nowrap width="437"></td><td><img id="img" src="/image" /><a href='#' οnclick="javascript:changeImg()" style="color:white;"><label style="color:black;">看不清?</label></a> </td></tr></table><!-- 触发JS刷新--><script type="text/javascript">function changeImg(){var img = document.getElementById("img");img.src = "/image?date=" + new Date();}</script></body></html>1.3.获取验证码图⽚@RequestMapping(value="/getImage",method=RequestMethod.GET)public void authImage(HttpServletRequest request, HttpServletResponse response) throws IOException {response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);response.setContentType("image/jpeg");// ⽣成随机字串String verifyCode = VerifyCodeUtils.generateVerifyCode(4);// 存⼊会话sessionHttpSession session = request.getSession(true);// 删除以前的session.removeAttribute("verCode");session.removeAttribute("codeTime");session.setAttribute("verCode", verifyCode.toLowerCase());session.setAttribute("codeTime", LocalDateTime.now());// ⽣成图⽚int w = 100, h = 30;OutputStream out = response.getOutputStream();VerifyCodeUtils.outputImage(w, h, out, verifyCode);}1.4 核对验证码@RequestMapping(value="validImage",method=RequestMethod.GET)public String validImage(HttpServletRequest request,HttpSession session){String code = request.getParameter("code");Object verCode = session.getAttribute("verCode");return "验证码已失效,请重新输⼊";}String verCodeStr = verCode.toString();LocalDateTime localDateTime = (LocalDateTime)session.getAttribute("codeTime");long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();if(verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)){request.setAttribute("errmsg", "验证码错误");return "验证码错误";} else if((now-past)/1000/60>5){request.setAttribute("errmsg", "验证码已过期,重新获取");return "验证码已过期,重新获取";} else {//验证成功,删除存储的验证码session.removeAttribute("verCode");return "200";}}2、VerifyCodeUtils的⼯具类package com.example.springboot.demo.util.varcode;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Arrays;import java.util.Random;import javax.imageio.ImageIO;public class VerifyCodeUtils{//使⽤到Algerian字体,系统⾥没有的话需要安装字体,字体只显⽰⼤写,去掉了1,0,i,o⼏个容易混淆的字符 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";private static Random random = new Random();/*** 使⽤系统默认字符源⽣成验证码* @param verifySize 验证码长度* @return*/public static String generateVerifyCode(int verifySize){return generateVerifyCode(verifySize, VERIFY_CODES);}/*** 使⽤指定源⽣成验证码* @param verifySize 验证码长度* @param sources 验证码字符源* @return*/public static String generateVerifyCode(int verifySize, String sources){if(sources == null || sources.length() == 0){sources = VERIFY_CODES;}int codesLen = sources.length();Random rand = new Random(System.currentTimeMillis());StringBuilder verifyCode = new StringBuilder(verifySize);for(int i = 0; i < verifySize; i++){verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));}return verifyCode.toString();}/*** @param h* @param outputFile* @param verifySize* @return* @throws IOException*/public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{ String verifyCode = generateVerifyCode(verifySize);outputImage(w, h, outputFile, verifyCode);return verifyCode;}/*** 输出随机验证码图⽚流,并返回验证码值* @param w* @param h* @param os* @param verifySize* @return* @throws IOException*/public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{ String verifyCode = generateVerifyCode(verifySize);outputImage(w, h, os, verifyCode);return verifyCode;}/*** ⽣成指定验证码图像⽂件* @param w* @param h* @param outputFile* @param code* @throws IOException*/public static void outputImage(int w, int h, File outputFile, String code) throws IOException{if(outputFile == null){return;}File dir = outputFile.getParentFile();if(!dir.exists()){dir.mkdirs();}try{outputFile.createNewFile();FileOutputStream fos = new FileOutputStream(outputFile);outputImage(w, h, fos, code);fos.close();} catch(IOException e){throw e;}}/*** 输出指定验证码图⽚流* @param w* @param h* @param os* @param code* @throws IOException*/public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{int verifySize = code.length();BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);Random rand = new Random();Graphics2D g2 = image.createGraphics();g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); Color[] colors = new Color[5];Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,Color.PINK, Color.YELLOW };float[] fractions = new float[colors.length];for(int i = 0; i < colors.length; i++){colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];fractions[i] = rand.nextFloat();Arrays.sort(fractions);g2.setColor(Color.GRAY);// 设置边框⾊g2.fillRect(0, 0, w, h);Color c = getRandColor(200, 250);g2.setColor(c);// 设置背景⾊g2.fillRect(0, 2, w, h-4);//绘制⼲扰线Random random = new Random();g2.setColor(getRandColor(160, 200));// 设置线条的颜⾊for (int i = 0; i < 20; i++) {int x = random.nextInt(w - 1);int y = random.nextInt(h - 1);int xl = random.nextInt(6) + 1;int yl = random.nextInt(12) + 1;g2.drawLine(x, y, x + xl + 40, y + yl + 20);}// 添加噪点float yawpRate = 0.05f;// 噪声率int area = (int) (yawpRate * w * h);for (int i = 0; i < area; i++) {int x = random.nextInt(w);int y = random.nextInt(h);int rgb = getRandomIntColor();image.setRGB(x, y, rgb);}shear(g2, w, h, c);// 使图⽚扭曲g2.setColor(getRandColor(100, 160));int fontSize = h-4;Font font = new Font("Algerian", Font.ITALIC, fontSize);g2.setFont(font);char[] chars = code.toCharArray();for(int i = 0; i < verifySize; i++){AffineTransform affine = new AffineTransform();affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2); g2.setTransform(affine);g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);}g2.dispose();ImageIO.write(image, "jpg", os);}private static Color getRandColor(int fc, int bc) {if (fc > 255)fc = 255;if (bc > 255)bc = 255;int r = fc + random.nextInt(bc - fc);int g = fc + random.nextInt(bc - fc);int b = fc + random.nextInt(bc - fc);return new Color(r, g, b);}private static int getRandomIntColor() {int[] rgb = getRandomRgb();int color = 0;for (int c : rgb) {color = color << 8;color = color | c;}return color;}private static int[] getRandomRgb() {int[] rgb = new int[3];for (int i = 0; i < 3; i++) {rgb[i] = random.nextInt(255);}return rgb;private static void shear(Graphics g, int w1, int h1, Color color) {shearX(g, w1, h1, color);shearY(g, w1, h1, color);}private static void shearX(Graphics g, int w1, int h1, Color color) {int period = random.nextInt(2);boolean borderGap = true;int frames = 1;int phase = random.nextInt(2);for (int i = 0; i < h1; i++) {double d = (double) (period >> 1)* Math.sin((double) i / (double) period+ (6.2831853071795862D * (double) phase)/ (double) frames);g.copyArea(0, i, w1, 1, (int) d, 0);if (borderGap) {g.setColor(color);g.drawLine((int) d, i, 0, i);g.drawLine((int) d + w1, i, w1, i);}}}private static void shearY(Graphics g, int w1, int h1, Color color) {int period = random.nextInt(40) + 10; // 50;boolean borderGap = true;int frames = 20;int phase = 7;for (int i = 0; i < w1; i++) {double d = (double) (period >> 1)* Math.sin((double) i / (double) period+ (6.2831853071795862D * (double) phase)/ (double) frames);g.copyArea(i, 0, 1, h1, 0, (int) d);if (borderGap) {g.setColor(color);g.drawLine(i, (int) d, i, 0);g.drawLine(i, (int) d + h1, i, h1);}}}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
ASP.net验证码实现代码(C#)
验证码实现代码(C#)public class ValidateCode : System.Web.UI.Page{private void Page_Load(object sender, System.EventArgs e){this.CreateCheckCodeImage(GenerateCheckCode());}#region Web 窗体设计器⽣成的代码override protected void OnInit(EventArgs e){//// CODEGEN: 该调⽤是 Web 窗体设计器所必需的。
//InitializeComponent();base.OnInit(e);}/// <summary>/// 设计器⽀持所需的⽅法 - 不要使⽤代码编辑器修改/// 此⽅法的内容。
/// </summary>private void InitializeComponent(){this.Load += new System.EventHandler(this.Page_Load);}#endregionprivate string GenerateCheckCode(){int number;char code;string checkCode = String.Empty;System.Random random = new Random();for(int i=0; i<5; i++){number = random.Next();if(number % 2 == 0)code = (char)('0' + (char)(number % 10));elsecode = (char)('A' + (char)(number % 26));checkCode += code.ToString();}Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));return checkCode;}private void CreateCheckCodeImage(string checkCode){if(checkCode == null || checkCode.Trim() == String.Empty)return;System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22); Graphics g = Graphics.FromImage(image);try{//⽣成随机⽣成器Random random = new Random();//清空图⽚背景⾊g.Clear(Color.White);//画图⽚的背景噪⾳线for(int i=0; i<25; i++){int x1 = random.Next(image.Width);int x2 = random.Next(image.Width);int y1 = random.Next(image.Height);int y2 = random.Next(image.Height);g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);}Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);g.DrawString(checkCode, font, brush, 2, 2);//画图⽚的前景噪⾳点for(int i=0; i<100; i++){int x = random.Next(image.Width);int y = random.Next(image.Height);image.SetPixel(x, y, Color.FromArgb(random.Next()));}//画图⽚的边框线g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);System.IO.MemoryStream ms = new System.IO.MemoryStream();image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);Response.ClearContent();Response.C;Response.BinaryWrite(ms.ToArray());}finally{g.Dispose();image.Dispose();}}} 假如以上验证码⽣成器页⾯名为:CheckCode.aspx,那么在登录页⾯中使⽤“<IMG>” 这个 HTML 元素来显⽰⽣成的验证码图⽚:<IMG src="CheckCode.aspx"> 在登录页⾯的登录按钮的处理事件中使⽤以下代码判断验证码:private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e){if(Request.Cookies["CheckCode"] == null){lblMessage.Text = "您的浏览器设置已被禁⽤ Cookies,您必须设置浏览器允许使⽤ Cookies 选项后才能使⽤本系统。
javaweb实现手机短信验证码登录实例
javaweb实现⼿机短信验证码登录实例java web实现⼿机短信验证码登录实例运⾏环境jdk7+tomcat7项⽬技术(必填)Servlet+Ajax+Bootstrap数据库⽂件我这⾥没⽤到数据库,⽐较简单,如果需要⽤到数据库不会的话可以私信我或者加我QQjar包⽂件jar包只有⼀个,在项⽬的lib⽂件夹下运⾏截图项⽬描述这个⼩案例呢⼤家可以在项⽬中⼩⼩的装个逼,本⼈在校⽣,反正在项⽬答辩的时候,看⼤家的反应还不错,哈哈。
本次案例呢⼤家不仅可以在登录的时候使⽤,另外注册的时候也可以⽤,⼤家⾃⾏决定,反正我在注册的时候⽤了,这次的案例没给⼤家敲注册,就简单写了个登录给⼤家分享⼀下。
没有使⽤任何框架,⽤了⼀个简单的Servlet,⾮常简单易懂,下载下来我的代码,只需要简单改⼏⾏代码就可以了,改成属于你⾃⼰的验证码就OK了!1、你需要登录秒嘀科技()这个官⽹去注册⼀个账号,这是我已经注册之后的是这个样⼦的,你需要做的就是,在开发者信息⾥⾯获得你⾃⼰的AUTH_TOK EN2、需要在配置管理中新建⼀个模板,这个模板就是发送验证码的模板,给⼤家看⼀下我的模板3、接着下载下来我的代码,导⼊开发⼯具之后,在java.aaa.util这个包中的GetMessageCode的类中,把我圈住的地⽅改成你⾃⼰的,我相信⼤家应该都能看懂,就不细说了,把我圈的地⽅改了就⾏了(ACCOUNT_SID和AUTH_TOKEN)最好就改这两个就好了;下⾯那个是要和你模板⾥⾯的对应的,上⾯说了,你需要⾃⼰新建⼀个模板,⽽我下⾯圈住那个就是和你模板⼀致,切记,⼀定要保持⼀致4、⼀切准备就绪之后,部署项⽬,启动项⽬,登录地址是:页⾯展⽰如下:验证码提⽰错误页⾯:(我收到的验证码是919805,我输⼊的,是919804,就会提⽰错误,当然输⼊正确就跳转成功页⾯)最后忘了跟⼤家说了,这个⽹站注册之后会赠送10元钱,⾜够⼤家学习使⽤了,所以不⽤担⼼需要充钱,放⼼⽤。
java 实现验证码类
java 实现验证码类
本章元练习通过对异常处理的应用实现验证码类。
本练习有3个类:MyException、Code和InputcodeException类,分别实现输出验证码、对验证码进行判断和抛出异常功能。
操作步骤:
(1)在【文件】菜单下选择【新建】|【类】命令,在弹出的对话框【新建Java类】中,创建MyException.java文件。
(2)添加验证类,主要实现功能是输入验证码并对验证码进行验证,当验证出错时抛出异常。
(4)添加MyException主类,主要功能是首先实例化验证类,调用验证类inputcode()方法供用户从键盘输入验证码,输入验证码后调用checkcode()方法对验证码进行验证,如果验证码正确则输出验证码信息,否则的话抛出异常。
所有代码
(5)执行上述代码,结果如图8-1所示。
图8-1 执行结果。
登录验证随机验证码的实现
登录验证随机验证码的实现今天我们来学习登录验证中,如何⽣成随机验证码?验证码使⽤基本都是找现成的组件来实现,⽤代码实现这个简单功能主要是了解了解验证码内部的实现。
友情链接⽣成随机验证码基本流程:⼀、效果图展⽰⼆、代码实现1、⾸先⽤bootstrap布⼀个上图简单的页⾯<div class="container"><div class="row"><div class="col-md-5 col-md-offset-3"><h1>账户登录</h1><span class="error"></span><form>{% csrf_token %}<div class="form-group"><label for="username">⽤户名</label><input type="text" class="form-control" id="username" placeholder="username"></div><div class="form-group"><label for="password">密码</label><input type="password" class="form-control" id="password" placeholder="password"></div><div class="row validCode"><div class="col-md-6"><div class="form-group"><label for="validCode">验证码</label><input type="text" class="form-control validCode_text" id="validCode"placeholder="validCode"></div></div><div class="col-md-6"><img class="validCode_img" src="/get_validCode_img/" alt="" width="200px" height="50px"></div></div><input type="button" value="登录" class="btn btn-primary" id="subBtn"></form></div></div></div>View Code2、在视图函数⾥写⼀个验证码⾸先下载图像处理的模块pip install PILpip install pillow第⼀个⽆法下载的话就下载第⼆个他们的引⽤都是from PIL没有区别实现随机验证码图⽚代码:def get_validCode_img(request):from io import BytesIO #内存import randomfrom PIL import Image,ImageDraw,ImageFontimg = Image.new(mode="RGB", size=(120, 40), color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) draw=ImageDraw.Draw(img,"RGB")font=ImageFont.truetype("static/font/kumo.ttf",25)valid_list=[]#随机五位数字⼤⼩写字母for i in range(5):random_num=str(random.randint(0,9))random_lower_zimu=chr(random.randint(65,90))random_upper_zimu=chr(random.randint(97,122))random_char=random.choice([random_num,random_lower_zimu,random_upper_zimu])draw.text([5+i*24,10],random_char,(random.randint(0,255),random.randint(0,255),random.randint(0,255)),font=font)valid_list.append(random_char)f=BytesIO()img.save(f,"png")data=f.getvalue() #在内存取值valid_str="".join(valid_list) #字符串的拼接# print(valid_str)request.session["keepValidCode"]=valid_str #存⼊sessionreturn HttpResponse(data)三、登录验证1、ajax实现验证<script src="/static/jquery-3.2.1.js"></script><script>$("#subBtn").click(function () {$.ajax({url: "/login/",type: "POST",data: {"username" : $("#username").val(),"password" : $("#password").val(),"validCode" : $("#validCode").val(),"csrfmiddlewaretoken" : $("[name='csrfmiddlewaretoken']").val()},success: function (data) {var response = JSON.parse(data);if (response["is_login"]) {location.href = "/index/"}else {$(".error").html(response["error_msg"]).css("color", "red")}}})})</script>2、view视图函数使⽤django中的⾃带⽤户验证需要导⼊模块from django.contrib import auth具体代码def log_in(request):if request.is_ajax():username=request.POST.get("username")password=request.POST.get("password")validCode=request.POST.get("validCode")login_response={"is_login":False,"error_msg":None}if validCode.upper()==request.session.get("keepValidCode").upper():user=auth.authenticate(username=username,password=password) if user:login_response["is_login"]=Truerequest.session["IS_LOGON"] = Truerequest.session["USER"] = username# auth.login(request,user) 与上⾯两步⾃⼰写session相同else:login_response["error_msg"] = "username or password error"else:login_response["error_msg"]='validCode error'import jsonreturn HttpResponse(json.dumps(login_response))return render(request,"login.html")⾸页视图函数def index(request):ret=request.session.get("IS_LOGON",None)if ret :username=request.session.get("USER")return render(request, "index.html",{"username":username})return redirect("/login/")# if not er.is_authenticated():# return redirect("/login/")# return render(request,"index.html")# 与上⾯auth.login(request,user)对应使⽤# 此时在template页⾯使⽤{{ ername }}显⽰⽤户直接使⽤不需传值。
vue实现手机验证码登录
vue实现⼿机验证码登录本⽂实例为⼤家分享了vue实现⼿机验证码登录的具体代码,供⼤家参考,具体内容如下验证码<template><div><el-main><el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> <el-form-item label="⼿机号" prop="phone"><el-input v-model="ruleForm.phone" placeholder="请输⼊⼿机号" size=""maxlength="11"></el-input></el-form-item><el-form-item label="验证码" prop="code"><el-row :span="24"><el-col :span="12"><el-input v-model="ruleForm.code" auto-complete="off" placeholder="请输⼊验证码" size=""maxlength="4"@keyup.enter.native="submitForm('ruleForm')"></el-input></el-col><el-col :span="12"><div class="login-code"><!--验证码组件--><el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}":disabled="getCodeBtnDisable">{{ codeBtnWord }}</el-button></div></el-col></el-row></el-form-item><!--滑动验证组件--><Verify></Verify><el-form-item><el-button type="primary" @click="submitForm('ruleForm')">登录</el-button></el-form-item></el-form></el-main></div></template>⽤到的vue验证⼯具类export default {// 限制只能输⼊数字(可以输⼊两位⼩数点)limitInputPointNumber(val) {if (val === 0 || val === "0" || val === "" || val === undefined) {return "";} else {let value = null;value = val.replace(/[^\d.]/g, ""); // 清除“数字”和“.”以外的字符value = value.replace(/\.{2,}/g, "."); // 只保留第⼀个. 清除多余的value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输⼊两个⼩数return value;}},handleRouteToArray(route) {const matchs = route.path.split('/')matchs.shift()let newMatch = []matchs.map((item, i) => {if (matchs[i - 1]) {item = newMatch[i - 1] + '/' + item}newMatch.push(item)})newMatch = newMatch.map(item => {return `/${item}`})return newMatch},// 密码长度8位以上,须包含⼤写、⼩写、数字、特殊符号中的任意3种testPassWord: function (str) {var rC = {lW: '[a-z]',uW: '[A-Z]',nW: '[0-9]',sW: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'}function Reg (str, rStr) {var reg = new RegExp(rStr)if (reg.test(str)) return trueelse return false}if (str.length < 8) {return false} else {var tR = {l: Reg(str, rC.lW),u: Reg(str, rC.uW),n: Reg(str, rC.nW),s: Reg(str, rC.sW)}if ((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s) || (tR.s && tR.u && tR.n) || (tR.s && tR.l && tR.n)) { // document.title = "密码符合要求"return true} else {return false}}},// 密码验证8-30位任意字符pwdReg: /^([0-9a-zA-Z]|(?:&)|(?:~)|(?:!)|(?:@)|(?:#)|(?:\$)|(?:%)|(?:\^)|(?:\*)){8,30}$/,// 电话号码验证phoneReg: /^1[3|4|5|6|7|8][0-9]{9}$/,// 格式化⾦钱formatUSD (val, currency) {if (val === '' || val === '--' || val === undefined) {return '--'}// 先判断数据是否有⼩数点let newVal = String(Number(val).toFixed(2))// 将科学计数转为正常的字符串显⽰if (newVal.includes('e+')) {newVal = Number(newVal).toLocaleString()newVal = this.unFormatAmount(newVal)}let dotIdx = stIndexOf('.')let dotVal = '.00' // 保留⼩数点后⾯的数据if (dotIdx >= 0) {dotVal = newVal.substr(dotIdx, newVal.length)newVal = newVal.slice(0, dotIdx)}let len = newVal.lengthlet arr = []let lastIndex = nullwhile (len > 0) {lastIndex = lenlen -= 3arr.unshift(newVal.substring(len, lastIndex))}val = arr.join(',')if (currency) {newVal = `${currency} ${val}${dotVal}`} else {// newVal = `$ ${val}${dotVal}`newVal = `¥ ${val}${dotVal}` // 默认⼈民币}return newVal},// 格式化⾦额数字,不包含⼩数点,⾦额符等输⼊整数formatAmount (val) {if (val === '' || val === '--' || val === undefined) {return '--'}if (val === 0 || val === '0') {return 0}// 先判断数据是否有⼩数点let newVal = String(val)let dotIdx = stIndexOf('.')let dotLength = 0if (newVal.split('.').length > 1) {dotLength = newVal.split('.')[1].length}let dotVal = '' // 保留⼩数点后⾯的数据if (dotIdx >= 0) {newVal = String(Number(val).toFixed(5))dotVal = newVal.substr(dotIdx, dotLength + 1)newVal = newVal.slice(0, dotIdx)}let len = newVal.lengthlet arr = []let lastIndex = nullwhile (len > 0) {lastIndex = lenlen -= 3arr.unshift(newVal.substring(len, lastIndex))}val = arr.join(',')if (dotVal.length < 2) {dotVal = ''}return val + dotVal},// 判断数据是否为空isEmptyVal (val) {if (val === undefined || val === '') {return '--'} else {return val}},// 格式化年⽉⽇ type: 中国显⽰⽅式(ch)及拼接的⽅式// 注: 只有在接⼝传参时才需要中国的显⽰⽅式,其它为美式formatYMD (now, type='ch') {if (!now || now === 'null' || now === '--' || now === undefined) {return '--'}if (Number(now)) {now = new Date(now)}// 兼容IE浏览器, YY-MM-DD 格式if (typeof now === 'string' && now.includes('-')) {now = this.NewDate(now)}if (now) {let year = ''let month = ''let date = ''// 这⾥的8位⽤于返回如 20180423 这样的格式if (String(now).length === 8 && String(now).indexOf('-') === -1 && String(now).indexOf('/') === -1) { const getNow = String(now)return `${getNow.substring(4, 6)}/${getNow.substring(6, 8)}/${getNow.substring(0, 4)}`} else {now = new Date(now)year = now.getFullYear()month = now.getMonth() + 1date = now.getDate()}if (month < 10) {month = `0${month}`}if (date < 10) {date = `0${date}`}if (type === 'ch') {return `${year}-${month}-${date}`} else if (type) {return `${year}${type}${month}${type}${date}`} else {return `${month}/${date}/${year}`}} else {return ''}},// 格式化时间年,⽉,⽇,时,分,秒formatDate (now, type) {if (!now || now === 'null' || now === '--' || now === undefined) {return '--'}if (now) {now = new Date(now)let year = now.getFullYear()let month = now.getMonth() + 1let date = now.getDate()let hour = now.getHours()let minute = now.getMinutes()let second = now.getSeconds()if (month < 10) {month = `0${month}`}if (date < 10) {date = `0${date}`}if (hour < 10) {hour = `0${hour}`}if (minute < 10) {minute = `0${minute}`}if (second < 10) {second = `0${second}`}if (type) {return `${month}/${date}/${year} ${hour}:${minute}:${second}`} else {return `${month}-${date}-${year}`}} else {return ''}},}直接放上完整的这样有助于看<template><div><el-main><el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> <el-form-item label="⼿机号" prop="phone"><el-input v-model="ruleForm.phone" placeholder="请输⼊⼿机号" size=""maxlength="11"></el-input></el-form-item><el-form-item label="验证码" prop="code"><el-row :span="24"><el-col :span="12"><el-input v-model="ruleForm.code" auto-complete="off" placeholder="请输⼊验证码" size=""maxlength="4"@keyup.enter.native="submitForm('ruleForm')"></el-input></el-col><el-col :span="12"><div class="login-code"><!--验证码组件--><el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable">{{ codeBtnWord }}</el-button></div></el-col></el-row></el-form-item><!--滑动验证组件--><Verify></Verify><el-form-item><el-button type="primary" @click="submitForm('ruleForm')">登录</el-button> </el-form-item></el-form></el-main></div></template><script>//导⼊⼯具类import Verify from "@/components/Verify";import event from "../utils/event"import common from "@/utils/common";let params;export default {name: "LoginIphone",components: {Verify},data() {//使⽤正则表达式验证⼿机号const checkPhone = (rule, value, callback) => {if (!value) {return callback(new Error('⼿机号不能为空'));} else {//获取⼯具类中的⼿机号正则表达式const reg = common.phoneReg// console.log(reg.test(value));if (reg.test(value)) {callback();} else {//如果验证输⼊错误就清空this.ruleForm.phone = ''return callback(new Error('请输⼊正确的⼿机号'));}}};return {ruleForm: {phone: '',code: '',},codeBtnWord: '获取验证码', // 获取验证码按钮⽂字// waitTime: 61, // 获取验证码按钮失效时间waitTime: 2, // 获取验证码按钮失效时间// 校验rules: {phone: [{validator: checkPhone, trigger: 'blur'}],code: [{required: true, message: '请输⼊验证密码', trigger: 'blur'}]}};},//计算属性computedcomputed: {// 控制获取验证码按钮是否可点击getCodeBtnDisable: {//设置按钮61s// get() {// if (this.waitTime === 61) {// if (this.ruleForm.phone) {// return false// }// return true// }// return true// }get() {if (this.waitTime === 2) {if (this.ruleForm.phone) {return false}return true}return true},// 注意:因为计算属性本⾝没有set⽅法,不⽀持在⽅法中进⾏修改,⽽下⾯我要进⾏这个操作,所以需要⼿动添加 set() {}},}, methods: {getCode() {const _this = thisparams = {}params.phone = this.ruleForm.phone// 调⽤获取短信验证码接⼝_this.$axios.post('/sendMessage', params).then(res => {console.log("--------查看后台响应的值-----", res)//把所有的数据存在const mydata = res.data.dataconsole.log("我在短信接⼝这利-->", mydata)//保存验证码params.yz = mydata.vCodeconsole.log("我是查看验证码-------" + mydata.vCode)console.log("我是查看调⽤的次数-------" + mydata.count)if (res.data.code === 200) {this.$message({message: '验证码已发送,请稍候...',type: 'success',center: true})}if (res.data.data.count >= 5) {//调⽤滑块验证的组件event.$emit("VERIFY")}})// 因为下⾯⽤到了定时器,需要保存this指向let that = thisthat.waitTime--that.getCodeBtnDisable = truethis.codeBtnWord = `${this.waitTime}s 后重新获取`let timer = setInterval(function () {if (that.waitTime > 1) {that.waitTime--that.codeBtnWord = `${that.waitTime}s 后重新获取`} else {clearInterval(timer)that.codeBtnWord = '获取验证码'that.getCodeBtnDisable = false// that.waitTime = 61that.waitTime = 2}}, 1000)},submitForm(formName) {const _this = this//判断输⼊的验证码是否为空if (this.ruleForm.code != null) {this.$refs[formName].validate((valid) => {if (valid) {_this.$axios.post("/iosLogin", {"phone": this.ruleForm.phone,"Verification": this.ruleForm.code}).then(res => {console.log(res.data)})// console.log("我是提交⾥⾯的:", par)//// const jwt = par.headers['authorization']// console.log("我是token->", jwt)// const userInfo = par.data.data// console.log("查看⽤户信息=", userInfo)//// // 把数据共享出去// _this.$mit("SET_TOKEN", jwt)// _this.$mit("SET_USERINFO", userInfo)//// // 获取// console.log("我是获取的_this.$store.getters.getUser")// console.log(_this.$store.getters.getUser)// _this.$router.push("/blogs")} else {console.log('error submit!!');return false;}});} else {this.$message({showClose: true,message: '请输⼊错误',type: 'error'});}}}}</script><style scoped>.el-button.disabled-style {background-color: #EEEEEE;color: #CCCCCC;}.demo-ruleForm {max-width: 500px;margin: 0 auto;}</style>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
<mapper namespace="erDao">
<select id="getUserByLoginName" parameterType="String" resultType="User">
url = url.substring(0, 1பைடு நூலகம்);
if ((url.indexOf("&") >= 0)) {
url = url + "×tamp=" + timestamp;
} else {
url = url + "?timestamp=" + timestamp;
//alert(111111111);
$("#info").html("验证码正确");
$("#formID").submit();
} else if (length == 4) {
$("#info").html("验证码错误");
} else if (length == 6) {
if (user == null) {
message = "用户名不对!";
return LOGIN;
}
if (!password.equals(user.getPassWord())) {
message = "密码不正确!";
return LOGIN;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/verifyCode.js"></script>
<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
</p>
<p>
<label>
密 码:
</label>
<input type="password" name="user.passWord" value="${user.passWord}"style="width: 150px;" />
private User user;
private String message;
public String login() {
String password = user.getPassWord();
user = loginUervice.getUserByLoginName(user.getUserName().trim());
}
public void setLoginUervice(LoginService loginUervice) {
this.loginUervice = loginUervice;
}
public User getUser() {
return user;
}
public void setUser(User user) {
"validateCode");
String veryCode = request.getParameter("c");
PrintWriter out = response.getWriter();
if (veryCode == null || "".equals(veryCode)) {
data : code,
success : callback
});
}
function callback(data) {
//alert(data);
var length = data.length;
//alert(length);
if (length == 9) {
登录Service:
@Component("LoginService")
public class LoginService {
@Autowired
private UserDao userdao;
/**
* 检查登陆名是否存在
* @return
*/
public User getUserByLoginName(String loginName) {
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String validateC = (String) request.getSession().getAttribute(
imgSrc.attr("src", chgUrl(src));
}
//为每次请求加上时间戳
//为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
function chgUrl(url) {
var timestamp = (new Date()).valueOf();
SELECT USERID,PASSWORD,USERNAME FROM SYS_USER WHERE USERNAME=#{loginName}
</select>
</mapper>
登录JSP:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
</p>
<p>
<label>
验证码:
</label>
<input id="veryCode" name="veryCode" type="text" />
<img id="imgObj" alt="" src="verifyCodeServlet" />
}
return url;
}
function isRightCode() {
var code = $("#veryCode").attr("value");
code = "c=" + code;
$.ajax({
type : "POST",
url : "resultServlet",
<p style="color: red; margin-left: 10px;">
${message}
</p>
<p>
<label>
用户名:
</label>
<input type="text" name="erName" value="${erName}"style="width: 150px;" />
return userdao.getUserByLoginName(loginName);
}
}
登录Dao:
public interface UserDao {
/**
* 检查登陆名是否存在
* @param loginName 登陆名
* @return
*/
er = user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">
<html>
</div>
</div>
</div>
</body>
</html>
验证码处理:
public class ResultServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)