Springboot+kaptcha验证码的生成与校验

今天发现了一个有意思的生成验证码的工具,研究了一下 

  
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.baomidou
            kaptcha-spring-boot-starter
            1.0.0
        
        
            com.github.penggle
            kaptcha
            2.3.2
        
        
            org.projectlombok
            lombok
            true
        

yml配置:


kaptcha:
  height: 50
  width: 200
  content:
    length: 4 # 字符个数
    source: abcdefghjklmnopqrstuvwxyz23456789 #生成的验证码字符,不支持中文,自动会转大小写
    space: 6
  font:
    color: 56,99,216
    name: Arial #字体名称
    size: 40 #字体大小
  background-color:
    to: white
    from: 25,60,91  #这里可以配RGB,也可以配颜色的单词,white,blue,red
  border:
    enabled: true
    color: black #同理也可以RGB
    thickness: 1

controller:

@Controller
@Log4j2
public class DemoController {
    /**
     * 1、验证码工具
     */
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/code")
    public ResponseEntity downloadFile(HttpServletRequest httpServletRequest) throws IOException {
        // 生产验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        httpServletRequest.getSession().setAttribute("code", createText);
        // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(challenge, "jpeg", os);
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.valueOf("image/jpeg");
        headers.add("Cache-Control", "no-store");
        headers.add("Pragma", "no-cache");
        headers.setContentType(mediaType);
        return new ResponseEntity<>(os.toByteArray(), headers, HttpStatus.OK);
    }

    @GetMapping("/check")
    public ResponseEntity verify(HttpServletRequest request) {
        String rightCode = (String) request.getSession().getAttribute("code");
        String tryCode = request.getParameter("code");
            HttpHeaders headers = new HttpHeaders();
        if (!rightCode.equals(tryCode)) {
            log.info( "错误的验证码");
            return new ResponseEntity("错误的验证码", headers, HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity("成功", headers, HttpStatus.BAD_REQUEST);
        }
    }
}

好了,上面就是简单的demo,剩下的就自己玩吧

你可能感兴趣的:(spring,boot,kaptcha,SpringBoot)