美文网首页
kaptcha验证码实现

kaptcha验证码实现

作者: IT小池 | 来源:发表于2020-01-15 12:51 被阅读0次

这里我没有使用默认 web.xml配置,使用的是类的方式实现

首先导包:

<!-- kaptcha验证码 -->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

创建验证码类CaptchaUtil

package com.ssm.crm.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import java.util.Properties;
import java.util.Random;

/** kaptcha验证码
 * 验证码工具
 */
public class CaptchaUtil {

    private static CaptchaUtil instance;
    private int _width = 250;// 验证码宽度
    private int _height = 90;// 验证码高度
    private int _length = 4;// 验证码长度

    public static CaptchaUtil getInstance(){
        if (instance == null){
            instance = new CaptchaUtil();
        }
        return instance;
    }

    /**
     * 设置长度
     * @param length
     * @return
     */
    public CaptchaUtil length(int length){
        this._length = length;
        return this;
    }

    /**
     * 设置宽度
     * @param width
     * @return
     */
    public CaptchaUtil width(int width){
        this._width = width;
        return this;
    }

    /**
     * 设置高度
     * @param height
     * @return
     */
    public CaptchaUtil height(int height){
        this._height = height;
        return this;
    }

    /**
     * 参数设置并返回 DefaultKaptcha 对象
     * @return
     */
    public DefaultKaptcha getDefaultKaptcha(){
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border","no");
        properties.setProperty("kaptcha.border.color","105,179,90,0");
        properties.setProperty("kaptcha.image.width",String.valueOf(this._width));
        properties.setProperty("kaptcha.image.height",String.valueOf(this._height));
        properties.setProperty("kaptcha.textproducer.char.length",String.valueOf(this._length));
        properties.setProperty("kaptcha.session.key","code");
        properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");

        Random random = new Random();
        //properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.DefaultNoise");
        //properties.setProperty("kaptcha.obscurificator.impl",style[random.nextInt(style.length)]);
        properties.setProperty("kaptcha.textproducer.font.size",String.valueOf(this._height - random.nextInt(10)));
        properties.setProperty("kaptcha.textproducer.font.color",getColor());

        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(new Config(properties));
        // String code = defaultKaptcha.createText();
        // BufferedImage image = defaultKaptcha.createImage(code);
        return defaultKaptcha;
    }

    /**
     * 获取颜色
     * @return
     */
    private String getColor(){
        Random random = new Random();
        int r = random.nextInt(255);
        int g = random.nextInt(255);
        int b = random.nextInt(255);
        return r + "," + g + "," + b;
    }
}

使用方式:

package com.ssm.crm.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ssm.crm.constart.UserConstart;
import com.ssm.crm.util.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class CaptchaImageController {

    /**
     * 验证码(直接返回)
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/captcha")
    @ResponseBody
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DefaultKaptcha defaultKaptcha = CaptchaUtil.getInstance().width(300).height(100).length(6).getDefaultKaptcha();
        String code = defaultKaptcha.createText();
        request.getSession(true).setAttribute(UserConstart.VERIFY_CODE,code);
        BufferedImage image = defaultKaptcha.createImage(code);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        outputStream.flush();
        outputStream.close();
    }

   /**
     * Base64形式验证码
     * @return
     */
    @GetMapping("/captcha1")
    @ResponseBody
    public Map captcha1(){
        DefaultKaptcha kaptcha = CaptchaUtil.getInstance()
                .width(300)
                .height(100)
                .length(6)
                .getDefaultKaptcha();
        String code = kaptcha.createText();
        BufferedImage image = kaptcha.createImage(code);

        Map map = new HashMap<>();
        map.put("code",1);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // Base64OutputStream base64OutputStream = new Base64OutputStream(outputStream);
        try {
            // 使用 spring 提供的工具类 org.springframework.util.Base64Utils;
             ImageIO.write(image,"png",outputStream);
             map.put("url", Base64Utils.encodeToString(outputStream.toByteArray()));
            /* 使用 apache 提供的 commons-codec 包,org.apache.commons.codec.binary.Base64OutputStream;
            ImageIO.write(image,"png",base64OutputStream);
            map.put("url", outputStream.toString("UTF-8"));*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}

相关文章

网友评论

      本文标题:kaptcha验证码实现

      本文链接:https://www.haomeiwen.com/subject/dzltzctx.html