kaptcha验证码使用方法详解

本文为大家分享了kaptcha验证码的使用方法,供大家参考,具体内容如下

1.首先在pom.xml文件中导入Maven依赖


  com.github.penggle
  kaptcha
  2.3.2

2.在web.xml文件中配置一个servlet


 
 Kaptcha
 com.google.code.kaptcha.servlet.KaptchaServlet
 
  
        kaptcha.border
 no
 
 
 
   kaptcha.textproducer.font.color
 red
 
 
 
 kaptcha.image.width
 135
 
 
 
 kaptcha.textproducer.char.string
  ACDEFHKPRSTWX345679
 
 
 
  kaptcha.image.height
  50
 
 
 
  kaptcha.textproducer.font.size
  43
 
 
 
  kaptcha.noise.color
  black
 
 
 
  kaptcha.textproducer.char.length
  4
 
 
 
  kaptcha.textproducer.font.names
  Arial
 
 
 
 
 Kaptcha
 /Kaptcha
 

3.页面代码如下

点击更换

向后端提交数据

var verifyCodeActual = $('#j_captcha').val();
 if (!verifyCodeActual) {
  $.toast('请输入验证码!');
  return;
 }
 formData.append("verifyCodeActual", verifyCodeActual);

4.js交互

function changeVerifyCode(img) {
 img.src = "../Kaptcha?" + Math.floor(Math.random() * 100);
}

5.后端验证

import javax.servlet.http.HttpServletRequest;

public class CodeUtil {
 public static boolean checkVerifyCode(HttpServletRequest request) {
 String verifyCodeExpected = (String) request.getSession().getAttribute(
  com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
 String verifyCodeActual = HttpServletRequestUtil.getString(request,
  "verifyCodeActual");
 if (verifyCodeActual == null
  || !verifyCodeActual.equalsIgnoreCase(verifyCodeExpected)) {
  return false;
 }
 return true;
 }
}
import javax.servlet.http.HttpServletRequest;

public class HttpServletRequestUtil {
 public static int getInt(HttpServletRequest request, String name) {

 try {
  return Integer.decode(request.getParameter(name));
 } catch (Exception e) {
  return -1;
 }
 }

 public static long getLong(HttpServletRequest request, String name) {

 try {
  return Long.valueOf(request.getParameter(name));
 } catch (Exception e) {
  return -1;
 }
 }

 public static Double getDouble(HttpServletRequest request, String name) {

 try {
  return Double.valueOf(request.getParameter(name));
 } catch (Exception e) {
  return -1d;
 }
 }

 public static Boolean getBoolean(HttpServletRequest request, String name) {

 try {
  return Boolean.valueOf(request.getParameter(name));
 } catch (Exception e) {
  return false;
 }
 }

 public static String getString(HttpServletRequest request, String name) {
 try {
  String result = request.getParameter(name);
  if (result != null) {
  result = result.trim();
  }
  if ("".equals(result))
  result = null;
  return result;
 } catch (Exception e) {
  return null;
 }

 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(kaptcha验证码使用方法详解)