导入依赖
<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
编写配置类,配置验证码图片基本信息
@Component
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.image.width", "150");
properties.put("kaptcha.image.height", "40");
properties.put("kaptcha.textproducer.font.size", "30");
properties.put("kaptcha.session.key", "verifyCode");
properties.put("kaptcha.textproducer.char.space", "5");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
编写一个验证码生产的Controller,用于前端调用
@Controller
public class CommonController {
@Autowired
private DefaultKaptcha captchaProducer;
@GetMapping("/common/kaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
byte[] captchaOutputStream = null;
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串(看源码)
String verifyCode = captchaProducer.createText();
// 并保存到session中
httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
// 变成图片
BufferedImage challenge = captchaProducer.createImage(verifyCode);
ImageIO.write(challenge, "jpg", imgOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
captchaOutputStream = imgOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
responseOutputStream.write(captchaOutputStream);
responseOutputStream.flush();
responseOutputStream.close();
}
}
生产验证码的源码
public String getText() {
int length = this.getConfig().getTextProducerCharLength();
char[] chars = this.getConfig().getTextProducerCharString();
Random rand = new Random();
StringBuffer text = new StringBuffer();
for(int i = 0; i < length; ++i) {
text.append(chars[rand.nextInt(chars.length)]);
}
return text.toString();
}
前端代码,对于图片的刷新注意看onclick
<div class="row">
<div class="col-6">
<input type="text" class="form-control" name="verifyCode" placeholder="请输入验证码" required="true">
</div>
<div class="col-6">
<img alt="单击图片刷新!" class="pointer" th:src="@{/common/kaptcha}"
<!--?d='+new Date()*1不影响链接,它唯一的作用是向IE表明: 图片链接发生了变化,图片需要刷新.-->
onclick="this.src='/common/kaptcha?d='+new Date()*1">
</div>
</div>