整合kaptcha (验证码)

kaptcha 是一个非常实用的验证码生成工具。有了它,你可以生成各种样式的验证码,因为它是可配置的。kaptcha工作的原理是调用 com.google.code.kaptcha.servlet.KaptchaServlet,生成一个图片。同时将生成的验证码字符串放到 HttpSession中。

使用kaptcha可以方便的配置:

  • 验证码的字体

  • 验证码字体的大小

  • 验证码字体的字体颜色

  • 验证码内容的范围(数字,字母,中文汉字!)

  • 验证码图片的大小,边框,边框粗细,边框颜色

  • 验证码的干扰线(可以自己继承com.google.code.kaptcha.NoiseProducer写一个自定义的干扰线)

  • 验证码的样式(鱼眼样式、3D、普通模糊……

下面介绍一下用法:

一. 依赖

<!-- 验证码 -->
    <dependency>
      <groupId>com.github.penggle</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3.2</version>
    </dependency>


二.配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <!-- 自定义 -->
                    <props>
                        <!-- 验证码宽度 -->
                        <prop key="kaptcha.image.width">110</prop>
                        <!-- 验证码高度 -->
                        <prop key="kaptcha.image.height">50</prop>
                        <!-- 生成验证码内容范围 -->
                        <prop key="kaptcha.textproducer.char.string">123456789abcDeFGHjkLmnoQqrsTUVWXYZ</prop>
                        <!-- 验证码个数 -->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <!-- 是否有边框 -->
                        <prop key="kaptcha.border">no</prop>
                        <!-- 边框颜色 -->
                        <prop key="kaptcha.border.color">105,179,90</prop>
                        <!-- 边框厚度 -->
                        <prop key="kaptcha.border.thickness">1</prop>
                        <!-- 验证码字体颜色 -->
                        <prop key="kaptcha.textproducer.font.color">black</prop>
                        <!-- 验证码字体大小 -->
                        <prop key="kaptcha.textproducer.font.size">30</prop>
                        <!-- 验证码所属字体样式 -->
                        <prop key="kaptcha.textproducer.font.names">微软雅黑</prop>
                        <!-- 干扰线颜色 -->
                        <prop key="kaptcha.noise.color">black</prop>
                        <!-- 验证码文本字符间距 -->
                        <prop key="kaptcha.textproducer.char.space">3</prop>
                        <!-- 图片样式 :水纹 -->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>

</beans>


三.样式

Constant描述默认值
kaptcha.border图片边框,合法值:yes , noyes
kaptcha.border.color边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.black
kaptcha.border.thickness边框厚度,合法值:>01
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.FishEyeGimpy
阴影com.google.code.kaptcha.impl.ShadowGimpy
com.google.code.kaptcha.impl.WaterRipple
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.keysession keyKAPTCHA_SESSION_KEY
kaptcha.session.datesession dateKAPTCHA_SESSION_DATE

四.项目运用

<div class="form-group">
       <input type="text" placeholder="请输入验证码" id="yzm">
       <img id="captcha_img" alt="点击更换" title="点击更换"
              οnclick="refresh()" src="kaptcha.jpg" />
</div>
如果想设置点击图片更换验证码,可以加上如下js,需要jquery
<script type="text/javascript">
    function refresh() {
        document.getElementById('captcha_img').src="kaptcha.jpg?"+Math.random();
    }
</script>
/**
 * @author Ray
 * @date 2018/6/19 0019
 * 随机验证码控制层
 * 使用kaptcha-2.3.2.jar支持
 */
@Controller
public class CodeController {

    @Autowired
    private Producer producer = null;

    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        // 禁止服务器缓存
        response.setDateHeader("Expires",0);
        // 设置标准的 HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // 设置标准 HTTP/1.0 不缓存图片
        response.setHeader("Pragma", "no-cache");
        // 返回一个 jpeg图片, 默认是text/html
        response.setContentType("image/jpeg");

        // 生成验证码
        String capText = producer.createText(); // 为图片创建文本
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // 将文本保存在session中

        // 向客户端写出
        BufferedImage bufferedImage = producer.createImage(capText); // 创建带有文本的图片
        ServletOutputStream outputStream = response.getOutputStream();
        // 图片数据输出
        ImageIO.write(bufferedImage, "jpg", outputStream);
        try{
            outputStream.flush();
        }finally {
            outputStream.close();
        }
    }
}

/**
 * @author Ray
 * @date 2018/6/19 0019
 * 比对验证码
 */
public class CodeUtil {

    /**
     * 将获取到的前端参数转为String类型
     * @param request
     * @param key
     * @return
     */
    public static String getString(HttpServletRequest request, String key){
        try{
            String result = request.getParameter(key);
            if (result != null) {
                result = result.trim();
            }
            if("".equals(result)){
                result = null;
            }
            return result;
        }catch (Exception e){
            return null;
        }
    }

    public static boolean checkVerifyCode(HttpServletRequest request){
        // 获取生成的验证码
        String sessionyzm = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("sessionyzm: " + sessionyzm);
        // 获取用户输入的验证码
        String yzm = CodeUtil.getString(request, "yzm");
        System.out.println("yzm: " + yzm);
        if(yzm == null || !yzm.equals(sessionyzm)){
            return false;
        }
        return true;
    }
}


五.运行效果




  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中整合Kaptcha,你可以按照以下步骤进行操作: 步骤1:添加Kaptcha依赖 在你的Spring Boot项目的pom.xml文件中,添加Kaptcha的依赖: ```xml <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 步骤2:配置Kaptcha 在application.properties(或application.yml)文件中,添加以下配置: ```properties # Kaptcha Configurations kaptcha.border = no kaptcha.border.color = black kaptcha.textproducer.font.color = black kaptcha.image.width = 150 kaptcha.image.height = 50 kaptcha.textproducer.char.string = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 kaptcha.textproducer.char.length = 4 kaptcha.noise.impl = com.google.code.kaptcha.impl.NoNoise kaptcha.background.clear.from = white kaptcha.background.clear.to = white kaptcha.textproducer.font.size = 40 ``` 步骤3:创建验证码接口 在你的控制器中创建一个用于生成验证码图片的接口,例如: ```java @RestController public class CaptchaController { @GetMapping("/captcha") public void getCaptcha(HttpServletRequest request, HttpServletResponse response) { // 创建DefaultKaptcha对象并配置参数 DefaultKaptcha kaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "no"); properties.setProperty("kaptcha.textproducer.font.color", "black"); kaptcha.setConfig(new Config(properties)); // 生成验证码文本 String text = kaptcha.createText(); // 将验证码文本保存到session中 request.getSession().setAttribute("captcha", text); // 创建验证码图片并输出到response中 BufferedImage image = kaptcha.createImage(text); try { OutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); } catch (IOException e) { e.printStackTrace();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值