1.导入工具包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.7</version>
</dependency>
2.创建controller
@RestController
@RequestMapping("/login")
public class CaptchaController {
public static final String STRING_RANGE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@GetMapping("/getCaptcha")
public void setCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
RandomGenerator randomGenerator = new RandomGenerator(STRING_RANGE, 4);
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(140, 50, 4, 16);
captcha.setGenerator(randomGenerator);
request.getSession().setAttribute("captcha", captcha.getCode());
final ServletOutputStream outputStream = response.getOutputStream();
captcha.write(outputStream);
outputStream.flush();
outputStream.close();
}
@GetMapping("/checkCaptcha")
public boolean checkCaptcha(HttpServletRequest request,String captcha) {
String captchaSession = (String) request.getSession().getAttribute("captcha");
return !StrUtil.isEmpty(captcha) && captcha.equalsIgnoreCase(captchaSession);
}
}
3.测试
4.1获取验证码
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/eaaf062fed046c8e982ed24441fa01c4.png)
4.2验证
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cee22b4b8fc44647994bcf23fce9aceb.png)