利用 kaptcha 构建验证码

利用 kaptcha 构建验证码

一、导入 jar 包

<!-- 验证码包 -->
<dependency>
	<groupId>com.github.axet</groupId>
	<artifactId>kaptcha</artifactId>
	<version> 0.0.9</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--eacache-->
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
</dependency>

二、配置 yml


cache:
    ehcache:
      config: classpath:/ehcache.xml

三、新建 ehcache.xml

在 resources 下新建 ehcache.xml 文件,并把以下内容导入进去


<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="java.io.tmpdir"/>
    <!--defaultCache:echcache的默认缓存策略  -->
    <!--
          缓存配置
             diskStore:指定数据在磁盘中的存储位置。
             name:缓存名称。
             defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略,以下属性是必须的:
             maxElementsInMemory:缓存最大个数。
             eternal:对象是否永久有效,一但设置了,timeout将不起作用。
             timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
             timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
             overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
             diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
             maxElementsOnDisk:硬盘最大缓存个数。
             diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
             diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
             memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
             clearOnFlush:内存数量最大时是否清除。
      -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <cache name="captchaCache"
           maxElementsInMemory="1000000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

四、在启动类上添加 @EnableCaching 注解

五、验证码配置


package com.livekeys.captcha.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class CaptchaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

还有更多的配置可设置


properties.put("kaptcha.border","yes"); //是否需要外边框(yes,no)
properties.put("kaptcha.border.thickness","2"); //边框厚度,合法值:>0
properties.put("kaptcha.border.color","blue");  //框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue
properties.put("kaptcha.textproducer.font.color","black");  //字体颜色
properties.put("kaptcha.obscurificator.impl","com.google.code.kaptcha.impl.FishEyeGimpy"); //渲染效果:水纹:WaterRipple;鱼眼:FishEyeGimpy;阴影:ShadowGimpy
properties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.DefaultNoise");   //配置干扰线–噪点(只改变最后一个单词:NoNoise,DefaultNoise)
properties.put("kaptcha.noise.color","yellow"); //干扰 颜色,合法值: r,g,b 或者 white,black,blue.
properties.put("kaptcha.image.width","90"); // 设置宽度
properties.put("kaptcha.image.height","33");    // 设置高度
properties.put("kaptcha.textproducer.font.size","25");  // 设置字号
properties.put("kaptcha.textproducer.char.length","4"); //生成验证码的长度(也就是要几个字)
properties.put("kaptcha.textproducer.char.space","5");  //文字间隔

//和登录框背景颜色一致
//背景颜色渐变,开始颜色
properties.put("kaptcha.background.clear.from","247,247,247");

//背景颜色渐变, 结束颜色
properties.put("kaptcha.background.clear.to","247,247,247");
properties.put("kaptcha.word.impl","com.google.code.kaptcha.text.impl.DefaultWordRenderer");

六、Controller 层


package com.livekeys.captcha.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.code.kaptcha.Producer;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class CaptchaController {

    @Autowired
    private Producer producer;

    @Autowired
    private CacheManager cacheManager;

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpServletRequest request, @RequestParam("deviceId") String deviceId) throws IOException {
        // 设置 response 禁止图像缓存
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();

        // 生成图片验证码
        BufferedImage image = producer.createImage(text);

        // 保存到验证码到 session
        Cache cache = cacheManager.getCache("captchaCache");
        Element element = new Element(deviceId, text);
        log.info("generateCaptcha:" + deviceId);
        cache.put(element);

        // 将验证码图片输出到前端
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);

        // 关闭 out
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {}
    }
}

七、前端

用于生成机器码的 js:Math.uuid.js (来源于网上)


(function() {
    // Private array of chars to use
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    
    Math.uuid = function (len, radix) {
      var chars = CHARS, uuid = [], i;
      radix = radix || chars.length;
      if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
      } else {
        // rfc4122, version 4 form
        var r;
    
        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
    
        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random()*16;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join('');
    };
})();

获取验证码


<img id="captcha" name="captcha" src="" />

let uuid = Math.uuid();
(function getCaptcha() {
    /* 图形验证码 */
    var captchaUrl = "http://localhost:8080/captcha";
    $('#captcha').click(function () {
        this.src = captchaUrl + '?deviceId='+uuid+'&t=' + (new Date).getTime();
    }).trigger('click');
})();

这样,页面上就可以获取验证码了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供制作验证码的步骤: 1. 添依赖 在 pom.xml 文件中添以下依赖: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` 2. 配置 Kaptcha 在 application.properties 或 application.yml 文件中添以下配置: ```yaml kaptcha: border: no border.color: black textproducer.font.color: black textproducer.char.length: 4 noise.impl: com.github.axet.kaptcha.impl.DefaultNoise noise.color: black ``` 这些配置项可以根据实际需求进行修改。 3. 生成验证码 在控制器中添以下代码: ```java @GetMapping("/captcha.jpg") public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception { // 创建 Kaptcha 对象 ConfigurableKaptcha kaptcha = new ConfigurableKaptcha(); // 生成验证码 String code = kaptcha.createText(); // 将验证码存入 Session request.getSession().setAttribute("captcha", code); // 将验证码输出到页面 response.setContentType("image/jpeg"); ServletOutputStream outputStream = response.getOutputStream(); BufferedImage image = kaptcha.createImage(code); ImageIO.write(image, "jpg", outputStream); outputStream.flush(); outputStream.close(); } ``` 这段代码会在 /captcha.jpg 路径下生成验证码图片,并将验证码存入 Session 中。 4. 验证验证码 在需要验证验证码的地方,可以使用如下代码: ```java String captcha = request.getParameter("captcha"); String sessionCaptcha = (String) request.getSession().getAttribute("captcha"); if (!captcha.equalsIgnoreCase(sessionCaptcha)) { // 验证码错误 } ``` 这段代码会从请求参数中获取验证码,然后和 Session 中的验证码进行比对,如果不一致则说明验证码错误。 以上就是使用 Kaptcha 制作验证码的步骤,希望对您有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值