spring boot验证码

验证码在实际工作中还是经常会使用上的。所以,在这儿,我也先来一个最简单的验证码,在为我也还是一个初学java的小白,有好多东东都还不是很了解。希望大家多多指教
1、引入依赖,这个不用多说,想必大家都懂。

<dependency>
     <groupId>cn.hutool</groupId>
     <artifactId>hutool-captcha</artifactId>
     <version>5.8.31</version>
 </dependency>

2、在控制器中使用,在代码中,我就加一些注释作为讲解吧

@GetMapping("/getCode")
/**
 * 返回的是图片流
 */
public ResponseEntity<byte[]> getCode() throws IOException {
    //配置验证码图片的宽度,以及验证码字符的个数,还有它的模糊程度(也就是干扰线),这儿设置4个字符,没有干扰线
    LineCaptcha captcha = new LineCaptcha(130, 40  , 4 , 0);
    //配置只有纯数字 1到9
    captcha.setGenerator(new RandomGenerator("123456789" , 4));
    //配置背景颜色
    captcha.setBackground(Color.pink);
    //配置字体
    captcha.setFont(new Font("微软雅黑", Font.BOLD, 18));
    //这儿就是生成验证码了
    String captchaCode = captcha.getCode();
    //其实,到这儿,验证码已配置完成,大家可以打印下 captchaCode 是可以出来4个字符的字符串的。

    //下面两行是生成图片的文件流
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(captcha.getImage() , "png" , outputStream);


    //在这儿还需要生成唯一的uuid,将来需要结合当前生成验证码结合起来
    //把它们存到缓存中,这样,前端发送过后就可以拿来做比较

	
	//生成uuid
	String uuid = UUID.randomUUID().toString().replace("-", "");
    redisClass.setString(uuid , captchaCode);


    //这儿就是设置返回体以及返回的内容(最后返回的是一个图片的文件流,直接在浏览器访问看到是一个图片)
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(org.springframework.http.MediaType.IMAGE_PNG);
    headers.set("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
    headers.setPragma("no-cache");
    headers.set("uuid" , uuid);//uuid返回响应头给前端
    headers.setDate("Expires", 0);

    byte[] b = outputStream.toByteArray();
    return new ResponseEntity<>(b, headers, HttpStatus.OK);
}
//验证 验证码是否有效或者是否正确
@PostMapping("/login")
public ApiResponse login(HttpServletRequest httpServletRequest  , HttpServletResponse httpServletResponse) {

    String uuid = httpServletRequest.getHeader("uuid");
    if(uuid == null) {
        httpServletResponse.setStatus(500);
        api = new ApiResponse(500 , "error" , "uuid无效");
        return api;
    }
    //redisClass 是 redis的工具类,需要有依赖,这儿我就先不往下写了
    String code = redisClass.getString(uuid);
    if(code == null) {
        httpServletResponse.setStatus(500);
        api = new ApiResponse(500 , "error" , "验证码不能为空");
        return api;
    }
    return api;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值