分享两种实现图片验证码校验登录方法

第一种使用ValidateCode实现验证码

ValidateCode是第三方依赖包,我们要先通过命令行引用一下

1.添加jar包到本地仓库

mvn install:install-file -DgroupId=cn.dsna.util.images -DartifactId=ValidateCode -Dversion=1.0 -Dfile=D:\ValidateCode.jar -Dpackaging=jar -DgeneratePom=true

根据自身情况修改对应的-DgroupId,-Dversion,和-Dfile。

2.更新本地仓库索引

以IDEA为例,操作如下:

File–>Settings–>搜索maven–>选择子项Repositores–>选中本地仓库–>update

3.在pom中使用jar

<dependency>
  <groupId>cn.dsna.util.images</groupId>
  <artifactId>ValidateCode</artifactId>
  <version>1.0</version>
</dependency>

具体代码实现


    public void getCode(HttpServletRequest request, HttpServletResponse response){
        //参数列表:宽度,⾼度,字符数,⼲扰线数量
        ValidateCode vs = new ValidateCode(120,40,5,100);
        //获取文本
        //String code = vs.getCode();
        
        try {
            //将文本放入redis中,一个公共的存储空间,存值的方式是key-value
            redisTemplate.opsForValue().set("code",vs.getCode());
            request.getSession().setMaxInactiveInterval(300);//永不过期为-1
            vs.write(response.getOutputStream());
        } catch (IOException e) {//有io流就可能有io流异常,就要加try catch语句
            e.printStackTrace();
        }
    }

第二种使用base64实现验证码

   private String doKaptcha(HttpServletRequest request) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        logger.info("kaptcha:" + text);
        BufferedImage image = kaptchaProducer.createImage(text);
        //将文本放入session中,一个公共的存储空间,存值的方式是key-value
        HttpSession session = request.getSession();
        session.setAttribute("kaptcha", text);

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
        } catch (IOException e) {
            return null;
        }
    }

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值