kaptcha is a simple and easy-to-use verification code generation tool. Through configuration, you can define the verification code size, color, displayed characters, etc. yourself. Let’s talk about how to use kaptcha to generate verification codes and extract verification codes on the server side for verification.
1. Build a test environment
1.1. Create a web test project
Create a new web project and place kaptcha-2.3.2.jar in the project's WEB-INF/lib directory as shown in the figure below:
1.2. Configure KaptchaServlet to generate verification code in the web.xml file
The detailed configuration of KaptchaServlet is as follows:
<?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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- kaptcha verification code configuration --> <servlet> <!-- Servlet generating image --> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- Is there a border--> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <!-- Font color--> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>red</param-value> </init-param> <!-- Image width --> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>135</param-value> </init-param> <!-- Which characters to use to generate verification codes--> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>ACDEFHKPRSTWX345679</param-value> </init-param> <!-- Image height --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- Font size --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- Color of the interference line --> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- Number of characters --> <init-param> <init-param> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- Number of characters --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- Which fonts to use --> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial</param-value> </init-param> </servlet> <!-- Mapping url --> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/Kaptcha.jpg</url-pattern> </servlet-mapping></web-app>
1.3. Display the generated verification code
Display verification code on page index.jsp
<%@ page language="java" pageEncoding="UTF-8"%><!DOCTYPE HTML><html> <head> <title>Show the verification code generated by KaptchaServlet</title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script> <script type="text/javascript"> //Click to switch verification code function changeVerifyCode(){ $("#yzmImg").attr("src","Kaptcha.jpg?"+Math.floor(Math.random()*100)); } //Submit function doSubmit() { var verifyCodeValue = $("#verifyCode").val(); if(verifyCodeValue.replace(//s/g,"") == "") { alert("Please enter the verification code"); }else { //Asynchronously check whether the verification code is entered correctly before submitting var verifyUrl = "${pageContext.request.contextPath}/servlet/VerifyServlet?verifyCode="+verifyCodeValue; $.ajax({ type:"GET", url:verifyUrl, success:function(returnData){ if(returnData!="Y") { alert("Please enter the correct verification code!"); }else { //The verification code is correct, perform the submission operation alert("The verification code is correct, submit the form"); } }, error:function(e){ alert(e); } }); } } </script> </head> <body> <form> <table> <tr> <td> Please enter the verification code: </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()"> Can't see clearly, change another one</a> </td> </tr> <tr> <td> </td> <td> <input type="button" value="submit" onclick="doSubmit()"> </td> </tr> </table> </form> </body></html>The operation effect is shown in the figure below:
1.4. Verify the submitted verification code on the server side
After the user submits the verification code in the form form, we will verify it on the server side and write a VerifyServlet with the following code:
/** */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 { //Response data String resultData; //Get the passed verification code String verifyCode = request.getParameter("verifyCode"); System.out.println("verifyCode----"+verifyCode); if(verifyCode=="") { resultData = "N"; }else { //Get the verification code stored in the session String kaptchaValue = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); //Compare whether the entered verification code and the actual generated verification code are the same 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(); } } }} Register VerifyServlet in web.xml
<!-- Check whether the verification code is entered correctly-> <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>
The operation results are as follows:
1. Do not enter the verification code
2. Enter the wrong verification code
3. Enter the correct verification code
Using kaptcha to generate verification codes feels good, it is very easy to use and convenient. I hope everyone can master it.