1.引入kaptcha所需要的jar包
com.github.penggle kaptcha 2.3.2 2.配置kapcha
@Configuration
public class CaptchaConfig {
@Bean(name="captchaProducer")
public DefaultKaptcha getKaptchaBean(){
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.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.Controller中这样使用
@RequestMapping(value = "/captcha-image")
public ModelAndView getKaptchaImage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control",
"no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
String capText = captchaProducer.createText();
System.out.println("capText: " + capText);
try {
String uuid=UUIDUtils.getUUID32().trim().toString();
redisTemplate.opsForValue().set(uuid, capText,60*5,TimeUnit.SECONDS);
Cookie cookie = new Cookie("captchaCode",uuid);
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
return null;
}
4.前台这样用
【喜欢这类文章可以关注我,我会继续发布类似文章,谢谢】
閱讀更多 程序猿老王 的文章
關鍵字: 技术