SpringBoot 集成 kaptcha 验证码插件

kaptcha : 验证码插件,可以使用它生成自定义的验证码

1. kaptcha 依赖

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

2. kaptcha 配置

创建 kaptcha.xml 配置文件,配置文件信息如下?:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <!-- Kaptcha组件配置 -->
    <bean id="kaptchaProducer" 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">120</prop>
                        <!-- 验证码高度 -->
                        <prop key="kaptcha.image.height">50</prop>
                        <!-- 生成验证码内容范围 -->
                        <prop key="kaptcha.textproducer.char.string">0123456789AKWUEHPMRX</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">yellow</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">8</prop>
                        <!-- 图片样式 :阴影-->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>

 3. kaptcha 在 springboot 中配置

打开spring boot 的启动类,将上面所写的 kaptcha.xml 配置文件引入?:

4. 编写 kaptcha 使用controller

创建 CaptchaController ?:

CaptchaController 内容?:

package guet.hj.travel.controller;

import com.google.code.kaptcha.Producer;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

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;

/**
 * 验证码
 */
@Controller
public class CaptchaController {
    private Producer kaptchaProducer=null;

    @Autowired
    public void setCaptchaProducer(Producer kaptchaProducer) {
        this.kaptchaProducer = kaptchaProducer;
    }

    @GetMapping(value = "/getVerifyCode")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response){
        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 = kaptchaProducer.createText();
        request.getSession().setAttribute("verifyCode", capText);
        BufferedImage bi = kaptchaProducer.createImage(capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

5. 前端引用

温馨附上 οnclick="change()" 用来点击更换验证码图片 

function change() {
        $('#kaptchaImage').click(function () {
            $(this).attr('src', '[[@{/getVerifyCode?}]]' + Math.floor(Math.random() * 100));
        })
    }

展示:

6. 总结:

对于上述的配置,通过 CaptchaController 中的 getVerifyCode 获取验证码图片,并同时将验证码图片的内容信息保存在 httpSession 中

 谢谢大家观看!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
好的,我可以为您提供制作验证码的步骤: 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 制作验证码的步骤,希望对您有帮助!
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值