100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java验证码画布类型 【Java工具类】使用Kaptcha生成验证码写回页面中

java验证码画布类型 【Java工具类】使用Kaptcha生成验证码写回页面中

时间:2022-08-12 21:55:18

相关推荐

java验证码画布类型 【Java工具类】使用Kaptcha生成验证码写回页面中

1. 导入依赖

导入kaptcha依赖:

com.github.penggle

kaptcha

2.3.2

2. 编写配置类:

@Configuration

public class KaptchaConfig {

@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","0123456789ABCDEFGHIJKLMOPQRSTUVWXYZ");

properties.setProperty("kaptcha.textproducer.char.length","4"); // 验证码长度

properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");

DefaultKaptcha kaptcha = new DefaultKaptcha();

Config config = new Config(properties);

kaptcha.setConfig(config);

return kaptcha;

}

}

3. 编写 Controller 将验证码存入 session 并以图片的形式传回前端

/**

* 生成验证码并返回

*

* @param response

* @param session

*/

@GetMapping("/kaptcha")

public void getKaptchaImage(HttpServletResponse response, HttpSession session) {

String text = producer.createText();

BufferedImage image = producer.createImage(text);

// 将验证码存到session中

session.setAttribute("kaptcha", text);

// 将图片返回给浏览器

response.setContentType("image/png");

try {

OutputStream os = response.getOutputStream();

// 利用写出图片的工具类

ImageIO.write(image, "png", os);

} catch (IOException e) {

logger.error(e.getMessage());

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。