kaptcha验证码组件用法

1.添加依赖

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

2.在applicationContext.xml配置Kaptcha

    <!-- 配置Kaptcha -->
    <bean id="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <props>
                        <!--验证码图片不生成边框-->
                        <prop key="kaptcha.border">no</prop>
                        <!-- 验证码图片宽度为120像素 -->
                        <prop key="kaptcha.image.width">120</prop>
                        <!-- 验证码图片字体颜色为蓝色 -->
                        <prop key="kaptcha.textproducer.font.color">blue</prop>
                        <!-- 每个字符最大占用40像素 -->
                        <prop key="kaptcha.textproducer.font.size">40</prop>
                        <!-- 验证码包含4个字符 -->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>

3.在KaptchaController中实现逻辑功能

@Controller
public class KaptchaController {
    @Resource
    private Producer kaptchaProducer;

    @GetMapping("/verify_code")
    public void createVerifyCode(HttpServletRequest request , HttpServletResponse response) throws IOException {
        //响应立即过期
        response.setDateHeader("Expires",0);
        //不缓存任何图片数据
        response.setHeader("Cache-Control" , "no-store,no-cache,must-revalidate");
        response.setHeader("Cache-Control" , "post-check=0,pre-check=0");
        response.setHeader("Pragma" , "no-cache");
        response.setContentType("image/png");
        //生成验证码字符文本
        String verifyCode = kaptchaProducer.createText();
        request.getSession().setAttribute("kaptchaVerifyCode",verifyCode);
        System.out.println(request.getSession().getAttribute("kaptchaVerifyCode"));
        BufferedImage image = kaptchaProducer.createImage(verifyCode);//创建验证码图片
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "png", out);//输出图片流
        out.flush();
        out.close();
    }

文章来源地址https://uudwc.com/A/Nx69v

原文地址:https://blog.csdn.net/qq_41787812/article/details/133104940

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

上一篇 2023年09月24日 18:57
Go for Add a Test for 20230921 Day2
下一篇 2023年09月24日 18:58