SpringBoot集成Kaptcha实现(代码+注释)

本文介绍了如何在SpringBoot项目中集成Kaptcha库生成验证码,并提供了详细的配置步骤和代码示例。从添加依赖、配置文件设置、创建测试类,到前端接收和验证验证码的流程,都有详尽说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot集成Kaptcha实现(代码+详细)

1.添加依赖

 <!--谷歌验证码 kaptcha依赖-->
        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>0.0.9</version>
        </dependency>

2.写配置文件

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 KaptchaConfig {
    @Bean
    public DefaultKaptcha getDDefaultKaptcha() {
        DefaultKaptcha dk = new DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "yes");
        // 边框颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        // 图片宽
        properties.setProperty("kaptcha.image.width", "110");
        // 图片高
        properties.setProperty("kaptcha.image.height", "40");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        // session key
        properties.setProperty("kaptcha.session.key", "code");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        dk.setConfig(config);
        return dk;
    }
}

3.写个测试pojo层中的类

import lombok.Data;

@Data
public class LoginTwoVo {
    //用户名
    String userName;
    //密码
    String password;
    //验证码
    String code;
}

4.写个controller层测试类

import com.fourgirls.xiaoxiang.pojo.User.LoginTwoVo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


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.ByteArrayOutputStream;


@Api(tags = "验证码类")//用了Swagger,要是没有就注释即可
@RestController
public class KaptchaController {
    /**
     * 验证码工具
     */
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "验证码")//用了Swagger,要是没有就注释即可
    @RequestMapping(value = "defaultKaptcha",produces = "image/jpg")//produces = "image/jpg"这里,用了Swagger,要是没有就注释即可
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            //Key-value的形式,key:vrifyCode  value:createText
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //输出保存到session中的验证码
            System.out.println("createText:"+createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

     /**
     *校对验证码
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public boolean CheckDefaultKaptcha(@RequestBody LoginTwoVo loginTwoVo, HttpServletRequest httpServletRequest){
        //得到session里面的,key为“vrifyCode”的value值
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        //输出该value值和自己测试时填写的值
        System.out.println(("Session  vrifyCode ---->" + captchaId + "---- form code --->" + loginTwoVo.getCode()));
        //判断session里面的验证码与自己填写的值是否一致
        if (!captchaId.equals(loginTwoVo.getCode())) {
            System.out.println(("错误的验证码"));
            return false;
        } else {
           //判断账号和密码是否一致
            if(loginTwoVo.getUserName().equals("wsw")&&loginTwoVo.getPassword().equals("123456")){
                System.out.println("登录成功");
                return true;
            }
            return false;
        }
    }
}

5.结果为

1.生成验证码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gFLoW5b6-1613912501951)(SpringBoot集成Kaptcha实现(代码+详细)].assets/image-20210221205725158.png)

2.输入错误校验码

在这里插入图片描述

3.输入正确的验证码

在这里插入图片描述

6.前端接受验证码

<template>
    <!-- 登录 -->
    <div id="app" class="app1">
        <router-view></router-view>
        <div class="link">
            <router-link type="primary" to="/register">立即注册</router-link>还没有账号?
        </div>
        <el-divider></el-divider>
        <el-card class="box-card" >
            <div id="flexx">
                <div class="flexx-from">
                    <h2>软特来福账号密码登录</h2>
                    <div class="flexx-from1">
                        <el-form ref="form" :model="form" label-width="80px">
                            <el-form-item label="用户账号:">
                                <el-col :span="30">
                                    <el-input type="text" v-model="form.name" prefix-icon="el-icon-user" placeholder="输入邮箱号/手机号"></el-input>
                                </el-col>
                            </el-form-item>
                            <el-form-item label="用户密码:">
                                <el-col :span="30">
                                    <el-input type="password" v-model="form.password" prefix-icon="el-icon-lock" placeholder="输入密码"></el-input>
                                </el-col>
                            </el-form-item>

                            <el-form-item label="验证码:">
                                <el-col :span="15">
                                    <el-input type="text"  placeholder="点击更换图片" v-model="form.code"></el-input>
                                </el-col>
                                //接受验证码的图片
                                <img :src="imgurl" @click="updateCode">
                            </el-form-item>
                            <el-form-item>
                                <template slot-scope="scope">
                                    <el-button type="primary" @click="onSubmit">立即登录</el-button>
                                    <el-button size="mini" round @click="onForget">忘记密码</el-button>
                                </template>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>
        </el-card>

        <div>
            <el-dialog title="忘记密码" :visible.sync="updatePwdVisible" width="80%" :before-close="handleClose">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="电话号码:">
                        <el-input></el-input>
                    </el-form-item>
                    <el-form-item label="输入验证码:">
                        <el-input></el-input>
                        <el-button type="primary" @click="onSend">发送验证码</el-button>
                    </el-form-item>
                    <el-form-item label="输入新密码:">
                        <el-input></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onUpdateCommit">修改密码</el-button>
                        <el-button @click="onupdatecancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>

        <el-divider></el-divider>
    </div>
</template>

<script>
    export default {
        methods: {
            onSubmit() {
                    //axios 获取网络
                    this.$axios.post("http://localhost:8081/findLoginUser", {
                        userName: this.form.name,
                        userPassword: this.form.password,
                        code: this.code
                    }).then(function(res) { //请求成功
                        console.log("res.data"+res.data)
                    }).catch(function(err) { //请求失败
                        console.log(err)
                    })
            },
            onForget() {
                console.log('open')
                this.updatePwdVisible = true
            },
            onSend() {
                console.log('send')
            },
            onUpdateCommit() {

            },
            onupdatecancel() {
                console.log('cancel')
                this.updatePwdVisible = false
            },
            //点击就修改验证码
            updateCode(){
                this.imgurl='http://localhost:8081/defaultKaptcha?time'+new Date()
            }
        },
        data() {
            return {
                form: {
                    name: '',
                    password: '',
                    code: '',
                    type: [],
                    updatePwdVisible: false
                },
                imgurl:'http://localhost:8081/defaultKaptcha',
                url: 'https://img-blog.csdnimg.cn/20201220233836522.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2Rldm90aW9uX0lU,size_16,color_FFFFFF,t_70#pic_center'
            }
        },
        beforeRouteUpdate(to, from, next) {
            // 做一些想要做的处理...
            // this.errCode = to.params.code
            // this.info = formatErrorMsg(this.errCode)
            next() // 一定要有next
        }
    }
</script>

<style>
    .app1{
        margin-top: 0rem;
        margin-bottom: 0rem;
        /*background-image: url(../assets/huaxue.png);*/

    }
    .link {
        display: flex;
        flex-direction: row-reverse;
        margin-right: 10%;
    }

    .demo-image {
        margin-left: 10%;
        margin-top: 3%;
    }

    .demo-image1 {
        margin-left: 40%;
        margin-top: 5%;
    }

    .flexx {
        display: flex;
        flex-direction: row;
        margin-top: 50%;
        margin-left: 50%;

    }

    .flexx-from {
        display: flex;
        flex-direction: column;
        align-items: center;

    }

    .flexx-from1 {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .box-card {
        margin: auto;
        width: 50%;
        height: 50%;
        top: 50%;
        left: 50%;
        padding: 6px;

    }
</style>

7.结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值