利用kaptcha生成验证码的详细教程

kaptcha是一个简单好用的验证码生成工具,有了它,你可以生成各种样式的验证码,因为它是可配置的。kaptcha工作的原理是调用 com.google.code.kaptcha.servlet.KaptchaServlet,生成一个图片。同时将生成的验证码字符串放到 HttpSession中。

使用kaptcha可以方便的配置:

  • 验证码的字体
  • 验证码字体的大小
  • 验证码字体的字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线(可以自己继承com.google.code.kaptcha.NoiseProducer写一个自定义的干扰线)
  • 验证码的样式(鱼眼样式、3D、普通模糊……当然也可以继承com.google.code.kaptcha.GimpyEngine自定义样式)

第一步:添加kaptcha依赖的jar包

第二步:配置web.xml 文件

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- kaptcha验证码配置 -->
    <servlet>
        <!-- 生成图片的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>ACDEFHKPRSTWX345679</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>

    <!-- 映射的url -->
    <servlet-mapping>
        <servlet-name>Kaptcha</servlet-name>
        <url-pattern>/Kaptcha.jpg</url-pattern>
    </servlet-mapping>


    <!-- 检查验证码是否输入正确 -->
    <servlet>
        <servlet-name>VerifyServlet</servlet-name>
        <servlet-class>
            me.gacl.web.controller.VerifyServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>VerifyServlet</servlet-name>
        <url-pattern>/servlet/VerifyServlet</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

 

 

 

第三步:添加控制器

 

package me.gacl.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VerifyServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charaset=utf-8");
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        PrintWriter out = null;
        try {
            // 响应数据
            String resultData;
            // 获取传过来的验证码
            String verifyCode = request.getParameter("verifyCode");
            System.out.println("verifyCode----" + verifyCode);
            if (verifyCode == "") {
                resultData = "N";
            } else {
                // 获取kaptcha生成存放在session中的验证码
                String kaptchaValue = (String) request
                        .getSession()
                        .getAttribute(
                                com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
                // 比较输入的验证码和实际生成的验证码是否相同
                if (kaptchaValue == null || kaptchaValue == ""
                        || !verifyCode.equalsIgnoreCase(kaptchaValue)) {
                    resultData = "N";
                } else {
                    resultData = "Y";
                }
            }
            out = response.getWriter();
            out.write(resultData);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

 

 

 

 第四步:添加页面index.jsp .

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
    <head>
        <title>显示KaptchaServlet生成的验证码</title>
        <script type="text/javascript"
            src="${pageContext.request.contextPath}/js/jquery-1.9.1.min.js"></script>

        <script type="text/javascript">        
        //点击切换验证码
        function changeVerifyCode(){
            $("#yzmImg").attr("src","Kaptcha.jpg?"+Math.floor(Math.random()*100));
        }
        
        //提交
        function doSubmit() {
            var verifyCodeValue = $("#verifyCode").val();
            if(verifyCodeValue.replace(/\s/g,"") == "") {
                alert("请输入验证码");
            }else {
                //提交前先异步检查验证码是否输入正确
                var verifyUrl = "${pageContext.request.contextPath}/servlet/VerifyServlet?verifyCode="+verifyCodeValue;
                $.ajax({
                    type:"GET",
                    url:verifyUrl,
                    success:function(returnData){
                        if(returnData!="Y") {
                            alert("请输入正确的验证码!");
                        }else {
                            //验证码正确,进行提交操作
                            alert("验证码输入正确,提交表单");
                        }
                    },
                    error:function(e){
                        alert(e);
                    }
                });
            }
        }
    </script>
    </head>

    <body>
        <form>
            <table>
                <tr>
                    <td>
                        请输入验证码:
                    </td>
                    <td>
                        <input type="text" name="verifyCode" id="verifyCode">
                        <img src="Kaptcha.jpg" onclick="changeVerifyCode()" id="yzmImg"
                            style="cursor: pointer;">
                        <a href="javascript:void(0)" onclick="changeVerifyCode()">看不清,换一张</a>
                    </td>
                </tr>
                <tr>
                    <td>
                        &nbsp;
                    </td>
                    <td>
                        <input type="button" value="提交" onclick="doSubmit()">
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

 

 

源码下载:http://yunpan.cn/cwrSZdFaJv2sS  访问密码 888e

 

你可能感兴趣的:(kaptcha)