zoukankan      html  css  js  c++  java
  • springboot+kaptcha生成数学运算验证码和字符验证码

    使用以下代码只需要复制粘贴,修改一处文本生成器路径即可,文中有交代。

    1.添加kaptcha依赖

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

    2.编写验证码文本生成器,为了给数据运算验证码用的

    /**
     * 验证码文本生成器
     * 
     * @author shw
     */
    public class KaptchaTextCreator extends DefaultTextCreator
    {
        private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");
    
        @Override
        public String getText()
        {
            Integer result = 0;
            Random random = new SecureRandom();
            int x = random.nextInt(10);
            int y = random.nextInt(10);
            StringBuilder suChinese = new StringBuilder();
            int randomoperands = (int) Math.round(Math.random() * 2);
            if (randomoperands == 0)
            {
                result = x * y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("*");
                suChinese.append(CNUMBERS[y]);
            }
            else if (randomoperands == 1)
            {
                if (!(x == 0) && y % x == 0)
                {
                    result = y / x;
                    suChinese.append(CNUMBERS[y]);
                    suChinese.append("/");
                    suChinese.append(CNUMBERS[x]);
                }
                else
                {
                    result = x + y;
                    suChinese.append(CNUMBERS[x]);
                    suChinese.append("+");
                    suChinese.append(CNUMBERS[y]);
                }
            }
            else if (randomoperands == 2)
            {
                if (x >= y)
                {
                    result = x - y;
                    suChinese.append(CNUMBERS[x]);
                    suChinese.append("-");
                    suChinese.append(CNUMBERS[y]);
                }
                else
                {
                    result = y - x;
                    suChinese.append(CNUMBERS[y]);
                    suChinese.append("-");
                    suChinese.append(CNUMBERS[x]);
                }
            }
            else
            {
                result = x + y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("+");
                suChinese.append(CNUMBERS[y]);
            }
            suChinese.append("=?@" + result);
            return suChinese.toString();
        }
    }

    3.编写配置文件

    @Configuration
    public class CaptchaConfig
    {
        @Bean(name = "captchaProducer")
        public DefaultKaptcha getKaptchaBean()
        {
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 是否有边框 默认为true 我们可以自己设置yes,no
            properties.setProperty(KAPTCHA_BORDER, "yes");
            // 验证码文本字符颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
            // 验证码图片宽度 默认为200
            properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
            // 验证码图片高度 默认为50
            properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
            // 验证码文本字符大小 默认为40
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
            // KAPTCHA_SESSION_KEY
            properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
            // 验证码文本字符长度 默认为5
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
            // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
            // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
    
        @Bean(name = "captchaProducerMath")
        public DefaultKaptcha getKaptchaBeanMath()
        {
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 是否有边框 默认为true 我们可以自己设置yes,no
            properties.setProperty(KAPTCHA_BORDER, "yes");
            // 边框颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
            // 验证码文本字符颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
            // 验证码图片宽度 默认为200
            properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
            // 验证码图片高度 默认为50
            properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
            // 验证码文本字符大小 默认为40
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
            // KAPTCHA_SESSION_KEY
            properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
            // 验证码文本生成器
            properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.qjwl.rabbitmq.config.KaptchaTextCreator");
            // 验证码文本字符间距 默认为2
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
            // 验证码文本字符长度 默认为5
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
            // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
            // 验证码噪点颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
            // 干扰实现类
            properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
            // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
    }

    注意:

     这个位置的com.qjwl.rabbitmq.config.KaptchaTextCreator路径要改成你自己的验证码文本生成器的路径。

    4.编写controller层

    @Controller
    @RequestMapping("/captcha")
    public class CodeController
    {
        @Resource(name = "captchaProducer")
        private Producer captchaProducer;
    
        @Resource(name = "captchaProducerMath")
        private Producer captchaProducerMath;
    
        /**
         * 验证码生成
         */
        @GetMapping(value = "/captchaImage")
        public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response)
        {
            ServletOutputStream out = null;
            try
            {
                HttpSession session = request.getSession();
                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 type = request.getParameter("type");
                String capStr = null;
                String code = null;
                BufferedImage bi = null;
                if ("math".equals(type))
                {
                    String capText = captchaProducerMath.createText();
                    capStr = capText.substring(0, capText.lastIndexOf("@"));
                    code = capText.substring(capText.lastIndexOf("@") + 1);
                    bi = captchaProducerMath.createImage(capStr);
                }
                else if ("char".equals(type))
                {
                    capStr = code = captchaProducer.createText();
                    bi = captchaProducer.createImage(capStr);
                }
                session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
    
                out = response.getOutputStream();
                ImageIO.write(bi, "jpg", out);
                out.flush();
    
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    if (out != null)
                    {
                        out.close();
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

    注:生成验证码的时候,已经把字符验证码或者数字运算的结果code存在session之中,键为Constants.KAPTCHA_SESSION_KEY,取得时候只要从session中取这个建即可。

    Constants类是kaptcha包里面的,源码如下:

    package com.google.code.kaptcha;
    
    public class Constants
    {
        public final static String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    
        public final static String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    
        public final static String KAPTCHA_SESSION_CONFIG_KEY = "kaptcha.session.key";
    
        public final static String KAPTCHA_SESSION_CONFIG_DATE = "kaptcha.session.date";
    
        public final static String KAPTCHA_BORDER = "kaptcha.border";
    
        public final static String KAPTCHA_BORDER_COLOR = "kaptcha.border.color";
    
        public final static String KAPTCHA_BORDER_THICKNESS = "kaptcha.border.thickness";
    
        public final static String KAPTCHA_NOISE_COLOR = "kaptcha.noise.color";
    
        public final static String KAPTCHA_NOISE_IMPL = "kaptcha.noise.impl";
    
        public final static String KAPTCHA_OBSCURIFICATOR_IMPL = "kaptcha.obscurificator.impl";
    
        public final static String KAPTCHA_PRODUCER_IMPL = "kaptcha.producer.impl";
    
        public final static String KAPTCHA_TEXTPRODUCER_IMPL = "kaptcha.textproducer.impl";
    
        public final static String KAPTCHA_TEXTPRODUCER_CHAR_STRING = "kaptcha.textproducer.char.string";
    
        public final static String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length";
    
        public final static String KAPTCHA_TEXTPRODUCER_FONT_NAMES = "kaptcha.textproducer.font.names";
    
        public final static String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color";
    
        public final static String KAPTCHA_TEXTPRODUCER_FONT_SIZE = "kaptcha.textproducer.font.size";
    
        public final static String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space";
        
        public final static String KAPTCHA_WORDRENDERER_IMPL = "kaptcha.word.impl";
    
        public final static String KAPTCHA_BACKGROUND_IMPL = "kaptcha.background.impl";
    
        public static final String KAPTCHA_BACKGROUND_CLR_FROM = "kaptcha.background.clear.from";
    
        public static final String KAPTCHA_BACKGROUND_CLR_TO = "kaptcha.background.clear.to";
    
        public static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width";
    
        public static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height";
    }

    5.测试结果,如果type=math,则是算数验证码,此时得session中得code值为8,可自行验证

    如果type参数为char,则是字符验证码,所以此时得code为 4eym

  • 相关阅读:
    牛客前缀和题、枚举---[HNOI2003]激光炸弹
    牛客贪心题---拼数
    牛客枚举题---明明的随机数
    牛客模拟、差分题---校门外的树
    牛客贪心题---纪念品分组
    03_7_继承和权限控制
    03_6_package和import语句
    03_5_static关键字
    01_8_sql主键生成方式
    01_7_模糊查询实体对象
  • 原文地址:https://www.cnblogs.com/sun2020/p/12931562.html
Copyright © 2011-2022 走看看