1.在pom文件中添加依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.新建KaptchaConfig.java,在其中配置验证码相关的属性
/**
* Created By Seven.wk
* Description: 验证码配置类
* Created At 2018/08/07
*/
@Component
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", "110");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "30");
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;
}
}
3.在控制器中生成验证码并保存为图片
@RestController
@RequestMapping("/api")
public class ILoginController {
@Autowired
private DefaultKaptcha defaultKaptcha;
/**
* 生成验证码
* @param response
* @param session
* @throws IOException
*/
@GetMapping("/captcha")
public void captcha(HttpServletResponse response,
HttpSession session) throws IOException {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String createText = defaultKaptcha.createText();
session.setAttribute(Const.CAPTCHA_CODE, createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
//定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
4.现在我们可以通过访问/api/captcha,就可以看到验证码了
5.前端使用方法如下:
<img src="/api/captcha" title="验证码" alt="验证码" class="captchaCode" onclick = "this.src='/api/captcha?d='+new Date()*1"/>
这样每次点击图片时就可以更换验证码了。