springBoot 图片验证码
时间: 2023-10-27 19:07:22 浏览: 86
Spring Boot可以使用Google的Kaptcha库生成图像验证码。以下是使用Kaptcha生成图像验证码的示例代码:
1. 添加依赖
在pom.xml中添加以下依赖:
```
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
```
2. 添加配置
在application.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.textproducer.char.length=4
kaptcha.textproducer.char.space=5
kaptcha.noise.color=black
kaptcha.background.clear.from=239,239,239
kaptcha.background.clear.to=239,239,239
```
3. 创建验证码控制器
创建一个名为CaptchaController的控制器,用于生成和验证验证码。以下是示例代码:
```
@RestController
public class CaptchaController {
@Autowired
private Producer kaptchaProducer;
@GetMapping("/captcha.jpg")
public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// 生成验证码字符串并保存到session中
String captcha = kaptchaProducer.createText();
request.getSession().setAttribute("captcha", captcha);
// 生成验证码图片并写入输出流
BufferedImage challenge = kaptchaProducer.createImage(captcha);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// 设置响应头,指定返回的是jpeg格式的图片
byte[] captchaChallengeAsJpegBytes = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
response.setContentLength(captchaChallengeAsJpegBytes.length);
// 将验证码图片写入响应输出流
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.write(captchaChallengeAsJpegBytes);
servletOutputStream.flush();
servletOutputStream.close();
}
@PostMapping("/checkCaptcha")
public boolean checkCaptcha(HttpServletRequest request, @RequestParam("captcha") String captcha) {
String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
if (sessionCaptcha != null && sessionCaptcha.equalsIgnoreCase(captcha)) {
return true;
} else {
return false;
}
}
}
```
4. 在页面上显示验证码
在页面上添加以下代码,用于显示验证码图片和验证用户输入的验证码:
```
<form>
<img src="/captcha.jpg" />
<input type="text" name="captcha" />
<input type="button" value="提交" onclick="checkCaptcha()" />
</form>
<script>
function checkCaptcha() {
var captcha = document.getElementsByName("captcha")[0].value;
$.ajax({
url: "/checkCaptcha",
type: "POST",
data: {captcha: captcha},
success: function(result) {
if (result) {
alert("验证码正确");
} else {
alert("验证码错误");
}
}
});
}
</script>
```
这样就可以在Spring Boot应用中使用Kaptcha库生成图像验证码了。
阅读全文