• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

springboot项目使用redis进行验证码验证

武飞扬头像
大磊程序员(轻大)
帮助1

第一步引入依赖

  1.  
    <dependency>
  2.  
    <groupId>com.github.penggle</groupId>
  3.  
    <artifactId>kaptcha</artifactId>
  4.  
    <version>2.3.2</version>
  5.  
    </dependency>

第二步下载并配置redis数据库,了解redis一些基本知识

第三步控制层处理

读取验证码

  1.  
    @Autowired
  2.  
    private Producer captchaProducer;
  3.  
    @RequestMapping("/kaptcha")
  4.  
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
  5.  
    response.setDateHeader("Expires", 0);
  6.  
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  7.  
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
  8.  
    response.setHeader("Pragma", "no-cache");
  9.  
    response.setContentType("image/jpeg");
  10.  
    //生成验证码
  11.  
    String capText = captchaProducer.createText();
  12.  
    session.setAttribute("kaptcha", capText);
  13.  
    System.out.println(session.getAttribute("kaptcha"));
  14.  
    //将验证码存储到redis数据库中
  15.  
    redisTemplate.opsForValue().set("kaptchaKsy",capText,60, TimeUnit.SECONDS );
  16.  
    //向客户端写出
  17.  
    BufferedImage bi = captchaProducer.createImage(capText);
  18.  
    ServletOutputStream out = response.getOutputStream();
  19.  
    ImageIO.write(bi, "jpg", out);
  20.  
    try {
  21.  
    out.flush();
  22.  
    } finally {
  23.  
    out.close();
  24.  
    }
  25.  
     
  26.  
    }

调用Producer 得到验证码,并且存储到redis数据库中,可以设置存储时间等一些参数。

验证验证码

  1.  
    //登录
  2.  
    @ApiOperation("用户登录")
  3.  
    @PostMapping("/login/{code}")
  4.  
    public R login(@PathVariable("code")String code, User user1,HttpSession session){
  5.  
    User user = userService.login(user1);
  6.  
    if(user==null){
  7.  
    R.error("用户不存在");
  8.  
    }
  9.  
    //比较验证码
  10.  
    String code2= (String) redisTemplate.opsForValue().get("kaptchaKsy");
  11.  
    System.out.println(code2);
  12.  
    boolean codeFlag=code.equalsIgnoreCase(code2);
  13.  
    if(!codeFlag){
  14.  
    return R.error("验证码错误");
  15.  
    }
  16.  
    if(user1!=null){
  17.  
     
  18.  
    return R.ok().put("user",user);
  19.  
    }else {
  20.  
    return R.error("登陆失败!请检查用户名或密码");
  21.  
    }
  22.  
    }

调用redisTemplate进行读取验证码,进而验证

到此springboot验证码验证的教程已经完毕,感兴趣的朋友们可以点个赞加个关注,我们一块学习java

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcgjee
系列文章
更多 icon
同类精品
更多 icon
继续加载