[Java]Spring/SpringBoot实现验证码(Kaptcha的多种自定义使用)

2021-03-18 2874点热度 0人点赞 1条评论

前言

Kaptcha是我项目中在用的一个验证码产生工具,产生的验证码比较漂亮且可定制程度比较高,所以很好用。

可配置的项目如下:

  • 字体
  • 字体的大小
  • 字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线
  • 验证码的样式(鱼眼样式、3D、普通模糊...)

生成的验证码示例:

使用

如果是Maven,加入pom.xml:

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

如果是Gradle,加入build.gradle

implementation("com.google.code.kaptcha:kaptcha:2.3")

新建KaptchaController.java

生成的captcha验证码的文本,存在session的com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY里面,下一次用户提交验证码,只要从session里取出key:com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,和用户输入的对比就可以了

package com.terrynow.test.controller;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.servlet.KaptchaExtend;
import com.google.code.kaptcha.util.Config;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

import static com.google.code.kaptcha.Constants.*;

/**
 * @description These values are stored in the com.google.code.kaptcha.Constants class.
 * <p>
 * Constant	Description	Default
 * kaptcha.border	Border around kaptcha. Legal values are yes or no.	yes
 * kaptcha.border.color	Color of the border. Legal values are r,g,b (and optional alpha) or white,black,blue.	black
 * kaptcha.border.thickness	Thickness of the border around kaptcha. Legal values are > 0.	1
 * kaptcha.image.width	Width in pixels of the kaptcha image.	200
 * kaptcha.image.height	Height in pixels of the kaptcha image.	50
 * kaptcha.producer.impl	The image producer.	com.google.code.kaptcha.impl.DefaultKaptcha
 * kaptcha.textproducer.impl	The text producer.	com.google.code.kaptcha.text.impl.DefaultTextCreator
 * kaptcha.textproducer.char.string	The characters that will create the kaptcha.	abcde2345678gfynmnpwx
 * kaptcha.textproducer.char.length	The number of characters to display.	5
 * kaptcha.textproducer.font.names	A list of comma separated font names.	Arial, Courier
 * kaptcha.textproducer.font.size	The size of the font to use.	40px.
 * kaptcha.textproducer.font.color	The color to use for the font. Legal values are r,g,b.	black
 * kaptcha.textproducer.char.space	The space between the characters	2
 * kaptcha.noise.impl	The noise producer.	com.google.code.kaptcha.impl.DefaultNoise
 * kaptcha.noise.color	The noise color. Legal values are r,g,b.	black
 * kaptcha.obscurificator.impl	The obscurificator implementation.	com.google.code.kaptcha.impl.WaterRipple
 * kaptcha.background.impl	The background implementation.	com.google.code.kaptcha.impl.DefaultBackground
 * kaptcha.background.clear.from	Starting background color. Legal values are r,g,b.	light grey
 * kaptcha.background.clear.to	Ending background color. Legal values are r,g,b.	white
 * kaptcha.word.impl	The word renderer implementation.	com.google.code.kaptcha.text.impl.DefaultWordRenderer
 * kaptcha.session.key	The value for the kaptcha is generated and is put into the HttpSession. This is the key value for that item in the session.	KAPTCHA_SESSION_KEY
 * kaptcha.session.date	The date the kaptcha is generated is put into the HttpSession. This is the key value for that item in the session.	KAPTCHA_SESSION_DATE
 */
@Controller
public class KaptchaController extends KaptchaExtend {

    //--kaptcha验证码设置参数
    private Properties props = new Properties();
    private Producer kaptchaProducer = null;

    public KaptchaController() {
        ImageIO.setUseCache(false);

        this.props.put(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
        this.props.put(KAPTCHA_TEXTPRODUCER_CHAR_STRING, "1234567890");
        this.props.put(KAPTCHA_BORDER, "no");
        this.props.put(KAPTCHA_IMAGE_WIDTH, "300");
        this.props.put(KAPTCHA_IMAGE_HEIGHT, "100");
        this.props.put(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "80");


        Config config1 = new Config(this.props);
        this.kaptchaProducer = config1.getProducerImpl();
    }

    @RequestMapping({"/captcha.jpg", "**/captcha.jpg"})
    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
        // flush it in the response
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        String capText = this.kaptchaProducer.createText();
        BufferedImage bi = this.kaptchaProducer.createImage(capText);
        ServletOutputStream responseOutputStream = response.getOutputStream();
        // 本次产生的验证码文本存在session里,下次用户提交的时候,从session里取出后,和用户输入的对比来判断验证码是否正确
        session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
        ImageIO.write(bi, "jpeg", responseOutputStream);
        // 以下关闭输入流!
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}

上面代码里有英文关于验证码操作的介绍,这边翻译下整理如下:

com.google.code.kaptcha.Constants的参数如下

KEY 说明 默认值
kaptcha.border 图片边框,合法值:yes , no yes
kaptcha.border.color 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
kaptcha.image.width 图片宽 200
kaptcha.image.height 图片高 50
kaptcha.producer.impl 图片实现类 com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl 文本实现类 com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string 文本集合,验证码值从此集合中获取 abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 验证码长度 5
kaptcha.textproducer.font.names 字体 Arial, Courier
kaptcha.textproducer.font.size 字体大小 40px.
kaptcha.textproducer.font.color 字体颜色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.textproducer.char.space 文字间隔 2
kaptcha.noise.impl 干扰实现类 com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color 干扰 颜色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.obscurificator.impl 图片样式: com.google.code.kaptcha.impl.WaterRipple
水纹
com.google.code.kaptcha.impl.WaterRipple
鱼眼
com.google.code.kaptcha.impl.FishEyeGimpy
阴影
com.google.code.kaptcha.impl.ShadowGimpy
kaptcha.background.impl 背景实现类 com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from 背景颜色渐变,开始颜色 light grey
kaptcha.background.clear.to 背景颜色渐变, 结束颜色 white
kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DATE

网页上输出并更换验证码,简单示例不多做介绍:

<img id="captcha" src="/captcha" style="cursor: pointer;" title="点击换一张" />

$(function () { // 刷新验证码,这个根据所使用的JS框架自由实现
    $("#captcha").click(function () { 
        $(this).hide().attr('src', '/captcha?r=' + Math.random()).fadeIn(); 
    });
});

 

admin

这个人很懒,什么都没留下

文章评论

  • Tipicle

    Fqwvit Acheter Cialis Doctissimo buy viagra cialis online L Thyroxin Kaufen Gfvoco cialis super active akgimages Erich Lessing. Fpprzj

    2022-06-07
  • 您需要 登录 之后才可以评论