spingboot 动态验证码组件
时间: 2023-08-03 12:03:02 浏览: 58
Spring Boot 提供了一个非常方便的验证码组件,可以用于生成动态验证码。
首先,我们需要在 pom.xml 文件中添加如下依赖:
```xml
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
```
然后,在 Spring Boot 的配置文件中添加如下配置:
```properties
# 验证码配置
kaptcha.border=yes
kaptcha.border.color=105,179,90
kaptcha.textproducer.font.color=blue
kaptcha.image.width=125
kaptcha.image.height=45
kaptcha.textproducer.font.size=30
kaptcha.session.key=code
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=Arial
```
这里我们使用了 kaptcha 库,配置了验证码的一些基本属性。
最后,在我们的控制器中添加如下代码即可生成验证码:
```java
@GetMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 设置响应头
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
// 生成验证码
String code = producer.createText();
BufferedImage image = producer.createImage(code);
// 将验证码存入 session
request.getSession().setAttribute("captcha", code);
// 输出验证码图片
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
out.close();
}
```
这里我们将验证码存入了 session 中,以便后续校验用户输入的验证码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)