SSM框架Kaptcha验证码的使用

1.在pom中引入依赖

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

2.在web.xml中配置其对于的Servelet 设置以及相应的servlet-mapping

<servlet>
        <servlet-name>Kaptcha</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
        <!-- 是否有边框-->
        <init-param>
            <param-name>kaptcha.border</param-name>
            <param-value>no</param-value>
        </init-param>
        <!-- 字体颜色-->
        <init-param>
            <param-name>kaptcha.textproducer.font.color</param-name>
            <param-value>red</param-value>
        </init-param>
        <!-- 图片宽带-->
        <init-param>
            <param-name>kaptcha.image.width</param-name>
            <param-value>135</param-value>
        </init-param>
        <!-- 使用那些字符生成验证码-->
        <init-param>
            <param-name>kaptcha.textproducer.char.string</param-name>
            <param-value>ABCDEFGHIJKLMNOPQRST345679</param-value>
        </init-param>
        <!-- 图片高度-->
        <init-param>
            <param-name>kaptcha.image.height</param-name>
            <param-value>50</param-value>
        </init-param>
        <!-- 字体大小-->
        <init-param>
            <param-name>kaptcha.textproducer.font.size</param-name>
            <param-value>43</param-value>
        </init-param>
        <!-- 干扰线颜色-->
        <init-param>
            <param-name>kaptcha.noise.color</param-name>
            <param-value>black</param-value>
        </init-param>
        <!--验证码字符个数-->
        <init-param>
            <param-name>kaptcha.textproducer.char.length</param-name>
            <param-value>4</param-value>
        </init-param>
        <!-- 字体-->
        <init-param>
            <param-name>kaptcha.textproducer.font.names</param-name>
            <param-value>Arial</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>Kaptcha</servlet-name>
        <url-pattern>/Kaptcha</url-pattern>
    </servlet-mapping>

3.前端html页面部分

 

当刚进入页面时 验证码图片部分调用web.xml中的Kaptcha Servelet(src=“../Kaptcha”)

当发生点击事件时会调用changeVerifyCode(this)的方法

 注:调用changeVerifyCode(this) 时路径要生成随机四位数 

 

 

4.将前端获取的实际输入验证码传入后台与Kaptcha图片验证码进行匹配

public class CodeUtil {
    public static boolean checkVerifyCode(HttpServletRequest request){
        String verifyCodeExpected=(String)request.getSession().getAttribute(
                Constants.KAPTCHA_SESSION_KEY);
        String verifyCodeActual=HttpServletRequestUtil.getString(request,"verifyCodeActual");
        if (!verifyCodeActual.equals(verifyCodeExpected)||verifyCodeActual==null){
            return false;
        }else
            return true;
    }
}

 

posted @ 2019-03-06 16:54  饼先生  阅读(1043)  评论(0编辑  收藏  举报