Java工具

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

2021-03-12  本文已影响0人  itlu

1. 导入依赖

  1. 导入kaptcha依赖:
        <!-- 验证码生成 -->
        <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

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());
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读