Java实现springBoot项目图片验证码生成及验证代码实例!

本篇文章主要讲解springBoot项目下图片验证码的生成及验证实现方式。
作者:任聪聪
日期:2024年8月18日
独立博客:https://rccblogs.com/603.html
文章附件:Java实现图片文字类型验证码显示及验证的代码实例 (结合此附件可以更快掌握此项功能的开发能力)

一、实际效果:

页面效果:

file

验证成功后:

file

二、代码实例:

步骤一、引入pom文件依赖,如下:

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

位置说明:
file

步骤二、执行mvn进行安装:

命令:

mvn clean install

执行效果:
file

步骤三、创建我们的验证码工具类:

file
代码实例:

package com.thymeleaf.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class CaptchaUtil {

    private final DefaultKaptcha kaptchaProducer;
    private final static String CAPTCHA_SESSION_KEY = "cache_verify_code_text";

    public CaptchaUtil() {
        this.kaptchaProducer = createKaptchaProducer();
    }

    /**
     * 实例化验证码
     */
    private DefaultKaptcha createKaptchaProducer() {
        // 实例配置参数对象
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.textproducer.char.space", "4");
        properties.setProperty("kaptcha.image.width", "120");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier,monospace,sans-serif");

        // 依据配置创建实例
        Config config = new Config(properties);
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        kaptcha.setConfig(config);
        return kaptcha;
    }

    /**
     * 生成验证码图片
     */
    public void outCodeImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(true); // 获取或创建Session
        String captchaText = kaptchaProducer.createText();

        // 存储验证码文本到Session
        session.setAttribute(CAPTCHA_SESSION_KEY, captchaText);

        BufferedImage image = kaptchaProducer.createImage(captchaText);
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setDateHeader("Expires", 0);

        // 将验证码图片写入响应输出流
        javax.imageio.ImageIO.write(image, "png", response.getOutputStream());
    }

    /**
     * 验证验证码
     */
    public boolean validateCode(HttpServletRequest request, String input) {
        HttpSession session = request.getSession(false); 
        if (session == null) {
            return false;
        }
        String storedCaptcha = (String) session.getAttribute(CAPTCHA_SESSION_KEY);
        if (storedCaptcha == null || !storedCaptcha.equalsIgnoreCase(input)) {
            session.removeAttribute(CAPTCHA_SESSION_KEY); 
            return false;
        }
        session.removeAttribute(CAPTCHA_SESSION_KEY); 
        return true;
    }

}

步骤四、创建控制器方法

/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.thymeleaf.demos.web;

import com.thymeleaf.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
public class IndexController {

    @Autowired
    private CaptchaUtil captchaUtil;

    //首页
    @RequestMapping("/")
    public ModelAndView index(ModelAndView model) {
        model.setViewName("index");
        return model;
    }

    //显示验证码
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        captchaUtil.outCodeImg(request, response);
    }


    //验证验证码
    @RequestMapping("/check_captcha")
    public ResponseEntity<String> checkCaptcha(HttpServletRequest request, String input) {
        try {
            if (captchaUtil.validateCode(request, input)) {
                return ResponseEntity.ok("200");
            } else {
                return ResponseEntity.status(400).body("验证失败~");
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body("异常!");
        }
    }

}

步骤五、创建html页面内容

演示用表单

<form th:action="@{/check_captcha}" method="post">
    <img id="captchaImage" src="/captcha" alt="验证码">
    <p>请输入验证码</p>
    <input type="text" name="input" placeholder="请输入验证码">
    <input type="submit" value="提交">
</form>

演示用js脚本

 document.querySelector("form").addEventListener("submit", function (e) {
        e.preventDefault();
        let codeInput = document.querySelector("input[name='input']");
        let code = codeInput.value.trim();

        if (code.length !== 4) {
            alert("验证码长度错误,请输入4位验证码。");
            return;
        }

        let xhr = new XMLHttpRequest();
        xhr.open("POST", "/check_captcha");
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("input=" + encodeURIComponent(code));
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                if (xhr.responseText === "200") {
                    alert("验证码正确!");
                } else {
                    alert("验证码错误,请重新输入。");
                }
                codeInput.value = "";
                updateCaptchaImage();
            }
        };
    });

    function updateCaptchaImage() {
        document.getElementById("captchaImage").src = "/captcha?time=" + new Date().getTime();
    }

    document.getElementById("captchaImage").addEventListener("click", updateCaptchaImage);

步骤六、完成设置后,整体项目目录如下:

file
End:点击idea的运行按钮即可查看运行效果。
file

三、常见问题汇总:

1.pom无法有效安装验证码依赖的情况

解决办法:如果springBoot版本过高或者过低,那么就需要安装指定的验证码依赖版本,如果不知道是哪个版本可以再版本部分留空即可。

2.安装完毕后无法引入验证码依赖包的情况

解决办法:更新maven的索引即可解决问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任聪聪

创作不易,你的打赏是我的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值