0%

Kaptcha生成验证码

基本步骤

  • 导入jar包

  • 编写Kaptcha配置类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @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.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    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;
    }
    }
  • 引入bean,生成随机字符,生成图片

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @RequestMapping(path="/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
    //生成验证码
    String text = kaptchaProducer.createText();
    BufferedImage image = kaptchaProducer.createImage(text);

    //存入session
    session.setAttribute("kaptcha", image);

    //将图片输出给浏览器
    response.setContentType("image/png");
    try {
    OutputStream os = response.getOutputStream();
    ImageIO.write(image, "png", os);
    } catch (IOException e) {
    logger.error("响应验证码失败" + e.getMessage());
    }
    }
------ THEEND ------

欢迎关注我的其它发布渠道