欢迎光临
我们一直在努力

java验证码生成

依赖导入

<!– 添加图形验证码依赖 –>

<dependency>

<groupId>cn.hutool</groupId>

<artifactId>hutool-captcha</artifactId>

<version>5.8.5</version>

</dependency>

————————————————

/**

* 生成验证码图片

* @return

*/

@ApiOperation(“获取图形验证码”)

@GetMapping(“/identifyImage”)

public Result<String> identifyImage(HttpServletResponse response,

@ApiParam(value = “图形验证码id,无值:生成验证码,有值:刷新验证码”)

@RequestParam(name = “codeId”, required = false) String codeId) throws IOException {

// 创建验证码,设置宽、高、长度、干扰线数量

LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);

// 获取验证码字符串,赋值code

String code = lineCaptcha.getCode();

if (codeId == null) {

// IdWorker.getId():IdWorker工具类生成唯一ID,并转换成String类型

codeId = String.valueOf(IdWorker.getId());

// 将codeId、code.toUpperCase()、过期时间60秒:存储入Redis中

// code.toUpperCase():code装换成大写形式存储

redisOps.set(codeId,code.toUpperCase(),60);

} else {

redisOps.set(codeId,code.toUpperCase(),60);

}

// 将图片验证码codeId设置请求头中

response.setHeader(“codeId”, codeId);

// 获取向客户端发送响应数据的输出流

try (ServletOutputStream outputStream = response.getOutputStream()) {

// 验证码图片数据写入到输出流

lineCaptcha.write(outputStream);

} catch (Exception e) {

throw new AuthException(“图形验证码输出错误”);

}

return Result.succ(codeId);

}

————————————————

赞(0) 打赏
未经允许不得转载:划界MBA » java验证码生成

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册