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

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_27948811/article/details/89404946

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

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>kaptcha-spring-boot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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<byte[]> 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,剩下的就自己玩吧

猜你喜欢

转载自blog.csdn.net/qq_27948811/article/details/89404946