Kaptcha是一个Java验证码生成工具,用于生成和验证图像验证码。它基于Java的AWT图形库,能够生成包含数字和字母的验证码图像。Kaptcha还提供了验证功能,通过比较用户输入的验证码和生成的验证码来判断是否匹配,防止机器人和恶意攻击。
Kaptcha的使用非常简单,在项目中引入Kaptcha库后,只需要设置一些参数,如验证码的宽度、高度、字体样式等,就可以生成验证码图像。在用户提交表单后,再通过Kaptcha提供的验证方法,将用户输入的验证码与生成的验证码进行比较,从而实现验证码的验证功能。
Kaptcha还提供了一些自定义的功能,如可自定义验证码样式、字体、颜色等;支持将验证码图像保存到本地或输出到流中;支持配置过期时间,在一定时间内有效;支持多语言等。
依赖导入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
基础使用
首先添加一个配置类:
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "blue");
properties.setProperty("kaptcha.image.width", "125");
properties.setProperty("kaptcha.image.height", "45");
properties.setProperty("kaptcha.textproducer.font.size", "45");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}}
然后在 controller 中使用即可:
@Resource
private DefaultKaptcha defaultKaptcha;
@GetMapping("/captcha")
@ResponseBody
public void generateCaptcha(HttpServletResponse response, HttpSession session) throws Exception {
// 生成验证码字符串
String code = defaultKaptcha.createText();
// 将验证码字符串放到session中
session.setAttribute("captcha", code);
log.info("captcha: " + session.getAttribute("captcha"));
// 生成验证码图片
BufferedImage image = defaultKaptcha.createImage(code);
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", jpegOutputStream);
// 设置响应类型
response.setContentType("image/jpeg");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.getOutputStream().write(jpegOutputStream.toByteArray());
response.getOutputStream().flush();
response.getOutputStream().close();
}
此时访问 /captchar
就可以得到该生成的图片,并且支持点击刷新。