GoogleKaptcha生成验证码 SpringMvc使用GoogleKaptcha生成验证码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

GoogleKaptcha生成验证码 SpringMvc使用GoogleKaptcha生成验证码

FlyHeLanMan   2021-03-29 我要评论
想了解SpringMvc使用GoogleKaptcha生成验证码的相关内容吗,FlyHeLanMan在本文为您仔细讲解GoogleKaptcha生成验证码的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringMvc,GoogleKaptcha,验证码,下面大家一起来学习吧。

前言:google captcha 是google生成验证码的一个工具类,其原理是将随机生成字符串保存到session中,同时以图片的形式返回给页面,之后前台页面提交到后台进行对比。

1、jar包准备

官方提供的pom应该是

<dependency> 
  <groupId>com.google.code.kaptcha</groupId> 
  <artifactId>kaptcha</artifactId> 
  <version>2.3.2</version> 
</dependency>

但是下载不下来,我在阿里的maven仓库找到的pom如下:

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

测试可以正常下载,这里推荐阿里的maven仓库,下载速度还行,挺稳定,附地址:http://maven.aliyun.com/nexus/

2、spring bean的配置

<!-- google kaptcha的相关配置-->
  <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> 
    <property name="config"> 
      <bean class="com.google.code.kaptcha.util.Config"> 
        <constructor-arg> 
          <props> 
            <!-- 是否有边框 可选yes 或者 no --> 
            <prop key="kaptcha.border">yes</prop> 
            <!-- 边框颜色 -->
            <prop key="kaptcha.border.color">105,179,90</prop> 
            <!-- 验证码文本字符颜色 -->
            <prop key="kaptcha.textproducer.font.color">blue</prop> 
            <!-- 验证码文本字符大小 -->
            <prop key="kaptcha.textproducer.font.size">45</prop> 
            <!-- 验证码图片的宽度 默认200 -->
            <prop key="kaptcha.image.width">125</prop> 
            <!-- 验证码图片的高度 默认50 -->
            <prop key="kaptcha.image.height">45</prop> 
            <!-- 验证码文本字符长度 默认为5 -->
            <prop key="kaptcha.textproducer.char.length">4</prop> 
            <!-- 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) -->
            <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop> 
          </props> 
        </constructor-arg> 
      </bean> 
    </property> 
  </bean>

3、Controller的两个方法

package com.ccg.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
@RequestMapping("captcha")
public class CaptchaController {

  @Resource
  private Producer captchaProducer;
  /**
   *       
   *        获取验证码图片
   * @author     ccg
   * @param     request
   * @param     response
   * @return
   * @throws     IOException
   * Created    2017年1月17日 下午5:07:28
   */
  @RequestMapping("getCaptchaCode")
  public ModelAndView getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
    HttpSession session = request.getSession();
    
    response.setDateHeader("Expires", 0); 
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); 
    response.addHeader("Cache-Control", "post-check=0, pre-check=0"); 
    response.setHeader("Pragma", "no-cache"); 
    response.setContentType("image/jpeg"); 
    
    //生成验证码文本
    String capText = captchaProducer.createText(); 
    session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    System.out.println("生成验证码文本===="+capText);
    //利用生成的字符串构建图片
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream(); 
    ImageIO.write(bi, "jpg", out); 
    
    try { 
      out.flush(); 
    } finally { 
      out.close(); 
    }
    return null;
  }
  
  /**
   *       
   *        前端输入的验证码与生成的对比
   * @author     ccg
   * @param     request
   * @param     response
   * @param     captchaCode
   * Created    2017年1月17日 下午5:34:23
   */
  @RequestMapping("checkCaptchaCode")
  public void checkCaptchaCode(HttpServletRequest request, HttpServletResponse response,@RequestParam("captchaCode") String captchaCode){
    System.out.println("页面输入验证码===="+captchaCode);
    
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    
    String generateCode =(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
    String result = "";
    if(generateCode.equals(captchaCode)){
      result = "验证成功";
    }else{
      result = "输入错误";
    }
    PrintWriter out = null;
    try {
      out = response.getWriter();
    } catch (IOException e) {
      e.printStackTrace();
    }
    out.print(result);
    out.flush();
  }
}

4、前台页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="${pageContext.request.contextPath}/js/jquery.min.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  生成的验证码:<img id="changeCaptcha" src="http://127.0.0.1/captcha/getCaptchaCode.htm"> <a href="javascript:changeCaptcha()" rel="external nofollow" >看不清,换一张</a>
  <br>
  <br>
  请输入验证码:<input id="captchaCode" type="text"> <input type="button" value="提交验证" onclick="checkCaptcha()">
</body>
<script type="text/javascript">
//获取验证码图片 
function changeCaptcha(){
  $("#changeCaptcha").attr("src","http://127.0.0.1/captcha/getCaptchaCode.htm");
}
//验证输入的验证码 
function checkCaptcha(){
  var captchaCode = $("#captchaCode").val();
  $.ajax({
    type:'post',
    async : false,
    url:'http://127.0.0.1/captcha/checkCaptchaCode.htm',
    data:{"captchaCode" : captchaCode},
    success:function(res){
      alert(res);
    }
  });
}
</script>
</html>

需要注意到引用了jquery.min.js

5、运行效果

附Google Captcha 可配置项

kaptcha.border  是否有边框  默认为true  我们可以自己设置yes,no 
kaptcha.border.color   边框颜色   默认为Color.BLACK 
kaptcha.border.thickness  边框粗细度  默认为1 
kaptcha.producer.impl   验证码生成器  默认为DefaultKaptcha 
kaptcha.textproducer.impl   验证码文本生成器  默认为DefaultTextCreator 
kaptcha.textproducer.char.string   验证码文本字符内容范围  默认为abcde2345678gfynmnpwx 
kaptcha.textproducer.char.length   验证码文本字符长度  默认为5 
kaptcha.textproducer.font.names    验证码文本字体样式  默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) 
kaptcha.textproducer.font.size   验证码文本字符大小  默认为40 
kaptcha.textproducer.font.color  验证码文本字符颜色  默认为Color.BLACK 
kaptcha.textproducer.char.space  验证码文本字符间距  默认为2 
kaptcha.noise.impl    验证码噪点生成对象  默认为DefaultNoise 
kaptcha.noise.color   验证码噪点颜色   默认为Color.BLACK 
kaptcha.obscurificator.impl   验证码样式引擎  默认为WaterRipple 
kaptcha.word.impl   验证码文本字符渲染   默认为DefaultWordRenderer 
kaptcha.background.impl   验证码背景生成器   默认为DefaultBackground 
kaptcha.background.clear.from   验证码背景颜色渐进   默认为Color.LIGHT_GRAY 
kaptcha.background.clear.to   验证码背景颜色渐进   默认为Color.WHITE 
kaptcha.image.width   验证码图片宽度  默认为200 
kaptcha.image.height  验证码图片高度  默认为50

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们