首先导入依赖:
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
完成配置文件:
@Configuration
public class KapthchaConfig {
@Bean
public Producer kaptchaProducer(){
//用于设置验证码具体细节
Properties properties = new Properties();
//设置验证码图片宽度
properties.setProperty("kaptcha.image.width", "100");
//设置验证码图片高度
properties.setProperty("kaptcha.image.height", "40");
//设置验证码文字大小
properties.setProperty("kaptcha.textproducer.font.size", "32");
//设置验证码图片颜色
properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
//设置验证码文字内容
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ");
//设置生成随机字符数量
properties.setProperty("kaptcha.textproducer.char.length", "4");
//图片干扰设置
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
//Kaptcha实现类
DefaultKaptcha kaptcha = new DefaultKaptcha();
//将properties配置封装到Config对象中
Config config = new Config(properties);
//将config传入实现类
kaptcha.setConfig(config);
return kaptcha;
}
}
复制过去 遇到类名冲突的 有Katpth的就选它 没有默认第一个。
完成controller 的配置:
@Controller
public class KapthchaController {
//注入生成验证码所需要的Producer对象
@Autowired
private Producer kaptcha;
/**
* 获取验证码
*/
@RequestMapping("/kaptcha")
public void getKpthcha(HttpServletResponse response, HttpSession session){
//生成验证码内容
String text = kaptcha.createText();
//生成验证码图片
BufferedImage image = kaptcha.createImage(text);
//将文字保存进session中
session.setAttribute("code",text);
//将图片写回流中,输出给浏览器
response.setContentType("image/png");
try {
ServletOutputStream os = response.getOutputStream();
ImageIO.write(image,"png",os);
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端如何实现:
js:
html:
可以实现点一下刷新验证码。