zoukankan      html  css  js  c++  java
  • 登录功能的验证码实现

    Controller: 

    public class SysLoginController extends AbstractController {
    
        @Autowired
        private SysCaptchaService sysCaptchaService;
            /**
         * 验证码
         */
        @GetMapping("captcha.jpg")
        public void captcha(HttpServletResponse response, String uuid)throws IOException {
    
            response.setHeader("Cache-Control", "no-store, no-cache");
            response.setContentType("image/jpeg");
    
            //获取图片验证码
            BufferedImage image = sysCaptchaService.getCaptcha(uuid);
    
    
            ServletOutputStream out = response.getOutputStream();
            //ImageIO 類別的 write() 接受一個 OutputStream 物件,可以將你指定的 BufferedImage 寫入至指定的 OutputStream
            ImageIO.write(image, "jpg", out);
    
    
            //优雅的关闭流,只不过commom-io在2.6版本之后,就不使用了(也是jdk7以前)
            IOUtils.closeQuietly(out);
        }
    }
    SysCaptchaServiceImpl:
    /**
     * 验证码
     * @author
     */
    @Service("sysCaptchaService")
    public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements SysCaptchaService {
        @Autowired
        private Producer producer;
    
        @Override
        public BufferedImage getCaptcha(String uuid) {
    
            if(StringUtils.isBlank(uuid)){
                throw new RRException("uuid不能为空");
            }
            //生成文字验证码
            String code = producer.createText();
    
            SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
            captchaEntity.setUuid(uuid);
            captchaEntity.setCode(code);
            //5分钟后过期
            captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
            this.save(captchaEntity);
    //        System.out.println(captchaEntity);
            //做成的图片大小和样式可以控制吗?还是默认的?
            return producer.createImage(code);
        }
    
         //登录时验证 
        @Override
        public boolean validate(String uuid, String code) {
            SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid));
            if(captchaEntity == null){
                return false;
            }
    
            //删除验证码
            this.removeById(uuid);
    
            if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
                return true;
            }
    
            return false;
        }
    }
    一个小小后端的爬行痕迹
  • 相关阅读:
    jQuery.qrcode二维码插件生成网页二维码
    JavaScript 常用方法
    jQuery——样式与动画
    jQuery——事件
    js基础(使用Canvas画图)
    ES6
    正则表达式总结及常规的正则表达式校验
    jQuery基础介绍
    weblogic 数据源高可用配置
    win10 查看端口是否被占用以及杀进程
  • 原文地址:https://www.cnblogs.com/heikedeblack/p/14449170.html
Copyright © 2011-2022 走看看