java实现验证码登录
一,场景:用户登录时需要输入验证码登录,如何实现用户通过验证码登录
二,实现逻辑
1,进入登录页面时,调用生成验证码接口,入参:当前时间戳(前端传入)
2,后台调用生成验证码接口,生成验证码,并以入参时间戳为 key,验证码为value,保存在redis,并设置有效时间为1分钟,超时需要重新输入
3,用户输入验证码,调用后台登录接口,入参:用户名,密码,验证码,key
4,登录时校验,比较当前输入验证码与从redis中获取验证码是否一致,是则登录成功
三,验证码生成
1,依赖jar包
compile('com.github.penggle:kaptcha:2.3.2')
2,
代码(Controller,工具类,验证码实体)
Controller
@RequestMapping("/validate/code")public void validateCode(HttpServletRequest request,HttpServletResponse response,@RequestParam("d") String d) throws Exception{ try { CaptchaUtil.out(request, response,d);} catch (Exception e) {e.printStackTrace();}}
工具类
@Component
public class CaptchaUtil {private final static String LOGIN_VALIDATE_CODE = "LOGIN_VALIDATE_CODE_";private final static Integer VALIDATE_CODE_EXPIRE_TIME = 60 * 1;@Autowiredprivate RedisUtils redisUtils;private static CaptchaUtil captchaUtil;public void setRedisUtils(RedisUtils redisUtils) {this.redisUtils = redisUtils;}@PostConstructpublic void init() {captchaUtil = this;captchaUtil.redisUtils = this.redisUtils;}/*** 清除验证码* @param request*/public static void clear(HttpServletRequest request) {captchaUtil.redisUtils.del(LOGIN_VALIDATE_CODE + BeansUtil.getIp(request));}public static void clear(String key) {captchaUtil.redisUtils.del(LOGIN_VALIDATE_CODE + key);}/*** 是否存在验证码* @param code* @param request* @return*/public static boolean exists(String code,HttpServletRequest request) {if (code != null && !code.trim().isEmpty()) {String redisCode = captchaUtil.redisUtils.get(LOGIN_VALIDATE_CODE + BeansUtil.getIp(request));CaptchaUtil.clear(request);return code.trim().toLowerCase().equals(redisCode);}return false;}public static boolean exists(String code,String key) {if (code != null && !code.trim().isEmpty()) {String redisCode = captchaUtil.redisUtils.get(LOGIN_VALIDATE_CODE + key);CaptchaUtil.clear(key);return code.trim().toLowerCase().equals(redisCode);}return false;}/*** 输出验证码** @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void out(HttpServletRequest request, HttpServletResponse response)throws IOException {out(5, request, response);}public static void out(HttpServletRequest request, HttpServletResponse response,String key)throws IOException {outCaptcha(130, 48, 5, null, 1, request, response,key);}/*** 输出验证码** @param len 长度* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void out(int len, HttpServletRequest request, HttpServletResponse response)throws IOException {out(130, 48, len, request, response);}/*** 输出验证码** @param len 长度* @param font 字体* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void out(int len, Font font, HttpServletRequest request, HttpServletResponse response)throws IOException {out(130, 48, len, font, request, response);}/*** 输出验证码** @param width 宽度* @param height 高度* @param len 长度* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void out(int width, int height, int len, HttpServletRequest request, HttpServletResponse response)throws IOException {out(width, height, len, null, request, response);}/*** 输出验证码** @param width 宽度* @param height 高度* @param len 长度* @param font 字体* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void out(int width, int height, int len, Font font, HttpServletRequest request, HttpServletResponse response)throws IOException {outCaptcha(width, height, len, font, 1, request, response);}/*** 输出验证码** @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void outPng(HttpServletRequest request, HttpServletResponse response)throws IOException {outPng(5, request, response);}/*** 输出验证码** @param len 长度* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void outPng(int len, HttpServletRequest request, HttpServletResponse response)throws IOException {outPng(130, 48, len, request, response);}/*** 输出验证码** @param len 长度* @param font 字体* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void outPng(int len, Font font, HttpServletRequest request, HttpServletResponse response)throws IOException {outPng(130, 48, len, font, request, response);}/*** 输出验证码** @param width 宽度* @param height 高度* @param len 长度* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void outPng(int width, int height, int len, HttpServletRequest request, HttpServletResponse response)throws IOException {outPng(width, height, len, null, request, response);}/*** 输出验证码** @param width 宽度* @param height 高度* @param len 长度* @param font 字体* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/public static void outPng(int width, int height, int len, Font font, HttpServletRequest request, HttpServletResponse response)throws IOException {outCaptcha(width, height, len, font, 0, request, response);}/*** 输出验证码** @param width 宽度* @param height 高度* @param len 长度* @param font 字体* @param cType 类型* @param request HttpServletRequest* @param response HttpServletResponse* @throws IOException IO异常*/private static void outCaptcha(int width, int height, int len, Font font, int cType, HttpServletRequest request,HttpServletResponse response) throws IOException {setHeader(response);Captcha captcha = new GifCaptcha(width, height, len);if (font != null) {captcha.setFont(font);}captchaUtil.redisUtils.set(LOGIN_VALIDATE_CODE, captcha.text().toLowerCase(),VALIDATE_CODE_EXPIRE_TIME);captcha.out(response.getOutputStream());}private static void outCaptcha(int width, int height, int len, Font font, int cType, HttpServletRequest request,HttpServletResponse response,String key) throws IOException {setHeader(response);Captcha captcha = new GifCaptcha(width, height, len);if (font != null) {captcha.setFont(font);}captchaUtil.redisUtils.set(LOGIN_VALIDATE_CODE + key, captcha.text().toLowerCase(),VALIDATE_CODE_EXPIRE_TIME);captcha.out(response.getOutputStream());}public static void setHeader(HttpServletResponse response) {response.setContentType("image/gif");response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);}
}
验证码实体类
public class GifCaptcha extends Captcha {public GifCaptcha() {}public GifCaptcha(int width, int height) {setWidth(width);setHeight(height);}public GifCaptcha(int width, int height, int len) {this(width, height);setLen(len);}public GifCaptcha(int width, int height, int len, Font font) {this(width, height, len);setFont(font);}@Overridepublic boolean out(OutputStream os) {checkAlpha();boolean ok = false;try {char[] rands = textChar(); // 获取验证码数组GifEncoder gifEncoder = new GifEncoder();gifEncoder.start(os);gifEncoder.setQuality(180);gifEncoder.setDelay(100);gifEncoder.setRepeat(0);BufferedImage frame;Color fontcolor[] = new Color[len];for (int i = 0; i < len; i++) {fontcolor[i] = new Color(20 + num(110), 20 + num(110), 20 + num(110));}for (int i = 0; i < len; i++) {frame = graphicsImage(fontcolor, rands, i);gifEncoder.addFrame(frame);frame.flush();}gifEncoder.finish();ok = true;} finally {try {os.close();} catch (IOException e) {e.printStackTrace();}}return ok;}/*** 画随机码图** @param fontcolor 随机字体颜色* @param strs 字符数组* @param flag 透明度使用* @return BufferedImage*/private BufferedImage graphicsImage(Color[] fontcolor, char[] strs, int flag) {BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g2d = (Graphics2D) image.getGraphics();// 填充背景颜色g2d.setColor(Color.WHITE);g2d.fillRect(0, 0, width, height);// 抗锯齿g2d.setFont(font);g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 随机画干扰线for (int i = 0; i < num(5, 12); i++) {g2d.setStroke(new BasicStroke(1.1f + RANDOM.nextFloat() / 2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));g2d.setColor(color(150, 250));int x1 = num(-10, width - 10);int y1 = num(5, height - 5);int x2 = num(10, width + 10);int y2 = num(2, height - 2);g2d.drawLine(x1, y1, x2, y2);// 画干扰圆圈g2d.setColor(color(100, 250));g2d.drawOval(num(width), num(height), 5 + num(25), 5 + num(25));}// 画验证码int hp = (height - font.getSize()) >> 1;int h = height - hp;int w = width / strs.length;//int sp = (w - font.getSize()) / 2;for (int i = 0; i < strs.length; i++) {AlphaComposite ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha(flag, i));g2d.setComposite(ac3);g2d.setColor(fontcolor[i]);// 计算坐标int x = i * w + num(6);int y = h - num(2, 8);if (x < 0) {x = 0;}if (x + font.getSize() > width) {x = width - font.getSize();}if (y > height) {y = height;}if (y - font.getSize() < 0) {y = font.getSize();}g2d.drawString(String.valueOf(strs[i]), x, y);}g2d.dispose();return image;}/*** 获取透明度,从0到1,自动计算步长** @param i* @param j* @return 透明度*/private float getAlpha(int i, int j) {int num = i + j;float r = (float) 1 / (len - 1);float s = len * r;return num >= len ? (num * r - s) : num * r;}}
java实现验证码登录相关推荐
- java手机验证码登录代码_java web实现手机短信验证码登录实例
运行环境 jdk7+tomcat7 项目技术(必填) Servlet+Ajax+Bootstrap 数据库文件 我这里没用到数据库,比较简单,如果需要用到数据库不会的话可以私信我或者加我QQ jar包 ...
- java图文验证码登录验证
<div class="tip verifyCode-box"><input class="verifyCode" name="ve ...
- Java基础——验证码登录
一.用随机数实现验证码 随机数的作用:随机生成一个数字. 随机数的使用: 1.导入random包 2.创建对象 3.获取随机数 二.for循环语句 语法: for(表达式1;条件表达式2;表达式3){ ...
- java生成验证码登录,生成验证码
这里写了一个生成验证码的demo 前台可以访问该servlet页面显示验证码 验证码 后台存的session名称为vCode 判断验证码是否正确时可以直接调用 前台通过 这里你就自己引入jq吧 < ...
- springBoot redis开发的Java快递代拿系统(含人脸识别,验证码登录)
源码获取:我的博客资源页面可以下载!!!! 项目名称 springBoot redis开发的Java快递代拿系统(含人脸识别,验证码登录) 系统介绍 快递代拿系统 > 该项目使用当前最为流行的 ...
- Java实现手机验证码登录和SpringSecurity权限控制
手机验证码登录和SpringSecurity权限控制 手机快速登录功能,就是通过短信验证码的方式进行登录.这种方式相对于用户名密码登录方式,用户不需要记忆自己的密码,只需要通过输入手机号并获取验证码就 ...
- java antd实现登录,基于 antd pro 的短信验证码登录
概要 整体流程 前端 页面代码 请求验证码和登录的 service (src/services/login.js) 处理登录的 model (src/models/login.js) 后端 短信验证码 ...
- java短信验证码登录功能设计与实现
前言 现在不管是各类的网站,还是大小社交app,登录方式是越来越多了,其中基于短信验证码的登录可以说是各类app必不可少的方式,短信验证码登录以其高效,安全,便捷等特性受到许多用户的青睐 业务案例 如 ...
- Java登录专题-----手机验证码登录 发送验证码
1.打印日志 ,检验入参 入参为 mobile 手机号 action动作 分为注册,与登录 2. UserInfoModel userInfoModel = new UserInfoModel() ...
- 各种登录源码来了!基础登录、验证码登录、小程序登录...全都要!
现在开发个应用登录比以前麻烦的多.产品经理说用户名密码登录.短信登录都得弄上,如果搞个小程序连小程序登录也得安排上,差不多就是我全都要. 多种登录途径达到一个效果确实不太容易,今天胖哥在Spring ...
最新文章
- mysql分页案例_php+mysql 进行分页案例
- linux下查看当前用户的 三个命令
- 谈判如何在博弈中获得更多_读后感--《谈判--如何在博弈中获得更多》
- 在Office 365 添加就地保留用户邮箱
- bool类型0和1真假_MySQL整理5—数据类型和运算符
- 一起来玩树莓派--解决官方docker源安装失败的问题
- 毕业季offer怎么拿?收下这份非典型求职面试指南
- 学 Python 没找对路到底有多惨?| 码书
- 七天LLVM零基础入门(Linux版本)------总结
- 预处理,编译,汇编,链接程序的区别
- I Think I Can!
- 解除webservice上下传文件大小限制
- 常用软件官方下载地址
- 2048小游戏最佳算法C语言,2048游戏的最佳算法是什么?
- EKL语言的核心语法
- vulfocus——骑士cms任意代码执行(CVE-2020-35339)
- codeup27943 星号实心六边形
- 陈艾盐:春燕百集访谈节目第二十一集
- Java | 加密技术 | 摘要加密算法(不含原理)
- java xml中的冒号_带冒号的xml元素名称
热门文章
- GitHub使用笔记
- haproxy之安装与配置详解
- java类加载器和父类委托机制
- Directx11教程(54) 简单的基于GS的billboard实现
- 几个负载均衡软件比较(Haproxy vs LVS vs Nginx)
- Android 四大组件学习之Activity三
- matlab xls转csv,使用python或Matlab将csv文件中的数据转换为csv文件
- Linux内核空间内存申请函数kmalloc、kzalloc、vmalloc的区别【转】
- 使用FreeSWITCH SIP落地的配置总结
- freeswitch 文件包含关系图