java uses kaptcha plugin to generate graphic verification code

Generate graphic captcha using kaptcha plugin

When doing maintenance on a project recently, the customer suggested that the previous verification code was too simple and needed to be replaced with a relatively complex verification code, so this time, kaptcha was used to generate the graphic verification code.

First, download the jar package

If it is a maven project, use maven to download directly,

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

If it is not managed by maven, download the jar package directly and put it
under
lib

Configure spring beans

Because I use the springmvc architecture, I configure it directly in application.xml,

    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                     <props>
                        <prop key="kaptcha.border">yes</prop>
                        <prop key="kaptcha.border.color">228,228,228</prop>
                        <prop key="kaptcha.border.thickness">1</prop>
                        <prop key="kaptcha.image.width">260</prop>
                        <prop key="kaptcha.image.height">50</prop>
                        <prop key="kaptcha.producer.impl">com.google.code.kaptcha.impl.DefaultKaptcha</prop>
                        <prop key="kaptcha.textproducer.impl">com.google.code.kaptcha.text.impl.DefaultTextCreator</prop>
                        <prop key="kaptcha.textproducer.char.string">abcdefhjkmnopqrstuvwxyz2345678</prop>
                        <prop key="kaptcha.textproducer.char.length">5</prop>
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
                        <prop key="kaptcha.textproducer.font.size">40</prop>
                        <prop key="kaptcha.textproducer.char.space">5</prop>
                        <prop key="kaptcha.session.key">KAPTCHA_SESSION_KEY</prop>
                        <prop key="kaptcha.session.date">KAPTCHA_SESSION_DATE</prop>
                    </props> 
                </constructor-arg>
            </bean>
        </property>
    </bean>

This is a captchaProducer configured, mainly relying on this bean to generate the verification code

Create a tool class KaptchaUtils.java

package com.hzseek.util;

import java.awt.image.BufferedImage;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.code.kaptcha.Producer;

public class KaptchaUtils {

    private static Producer captchaProducer;

    private static Logger logger = LoggerFactory.getLogger(KaptchaUtils.class);

    public void setCaptchaProducer(Producer captchaProducer) {
        KaptchaUtils.captchaProducer = captchaProducer;
    }

    public static BufferedImage getKapthaImage(HttpSession session) {
        String capText = captchaProducer.createText();
        logger.info("getKapthaImage :" + capText);
        session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);

        return captchaProducer.createImage(capText);
    }

    public static boolean validCode(HttpSession session, String code) {
        if(StringUtils.isEmpty(code))
            return false;
        else
            return code.equals(session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY));
    }
}

call in the controller layer

Because I use struts2, the image stream is output directly in the execute method.

package com.hzseek.web.action;

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springside.modules.web.struts2.Struts2Utils;
import com.hzseek.util.KaptchaUtils;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class KaptchaAction extends ActionSupport{

    @Override
    public String execute() throws Exception {
        HttpServletResponse response = Struts2Utils.getResponse();

        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //利用生成的字符串构建图片
        BufferedImage image = KaptchaUtils.getKapthaImage(Struts2Utils.getSession());
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpeg", out); 
        try {
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            out.close();
        }
        return null;
    }
}

front-end code

call directly through the url

<img id="validCodeImage" src="${request.contextPath}/kaptcha.action"/><a href="javascript:changeValidCode('#validCodeImage');" tabindex="5">看不清,换一张</a>

If you want to click to switch, you can add a js method

function changeValidCode(obj) {
    $(obj).attr('src','${request.contextPath}/kaptcha.action?id=' + Math.random());
}

Effect

write picture description here

The following are the kaptcha graphic verification code configurable items

Constant describe Defaults
kaptcha.border Image border, legal values: yes , no yes
kaptcha.border.color Border color, legal values: r,g,b (and optional alpha) or white,black,blue. black
kaptcha.border.thickness Border thickness, legal value: >0 1
kaptcha.image.width picture width 200
kaptcha.image.height Picture high 50
kaptcha.producer.impl Image implementation class com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl Text implementation class com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string A collection of text from which the captcha value is obtained abcde2345678gfynmnpwx
kaptcha.textproducer.char.length verification code length 5
kaptcha.textproducer.font.names font Arial, Courier
kaptcha.textproducer.font.size font size 40px.
kaptcha.textproducer.font.color Font color, legal values: r,g,b or white,black,blue. black
kaptcha.textproducer.char.space text spacing 2
kaptcha.noise.impl Interference implementation class com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color Interference color, legal values: r,g,b or white,black,blue. black
kaptcha.obscurificator.impl Image styles: Water Ripple com.google.code.kaptcha.impl.WaterRipple Fisheye com.google.code.kaptcha.impl.FishEyeGimpy Shadow com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple
kaptcha.background.impl background implementation class com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from background color gradient, start color light grey
kaptcha.background.clear.to background color gradient, end color white
kaptcha.word.impl text renderer com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DATE

Readers can choose according to their own needs, and they can experiment by themselves, which is quite interesting.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326415101&siteId=291194637